Skip to content

Implement fmsg-webapi: production HTTP API for messaging with JWT auth#1

Merged
markmnl merged 2 commits intomainfrom
copilot/create-http-api-for-messaging
Mar 8, 2026
Merged

Implement fmsg-webapi: production HTTP API for messaging with JWT auth#1
markmnl merged 2 commits intomainfrom
copilot/create-http-api-for-messaging

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Mar 8, 2026

Greenfield implementation of a Go HTTP API exposing CRUD operations for a PostgreSQL-backed messaging datastore. JWT tokens issued externally are validated and user identity is enforced for all authorization decisions.

Structure

All code lives under /src as a standard Go module (github.com/markmnl/fmsg-webapi).

src/
├── main.go                  # Env config, DB init, JWT middleware, route registration
├── models/models.go         # Message & Attachment JSON structs
├── db/db.go                 # pgxpool connection + ping
├── middleware/jwt.go        # gin-jwt setup, fmsgid validation, identity extraction
└── handlers/
    ├── messages.go          # POST/GET/PUT/DELETE /messages + /send
    └── attachments.go       # Upload/download/delete attachments

Authorization

  • All /api/v1 routes require Authorization: ******; identity (@user@domain`) extracted from JWT claims
  • Owner (msg.from_addr == identity) required for all write operations
  • Recipients (msg_to.addr) may only read messages and download attachments
  • Sent messages (time_sent IS NOT NULL) are immutable — updates, deletes, and attachment mutations rejected with 403

fmsgid Integration

After JWT validation, every request checks the user against the fmsgid service:

  • 404400 "User <addr> not found"
  • 200 + acceptingNew: false403 "User <addr> not authorised to send new messages"

File Storage

Message data: <FMSG_DATA_DIR>/<domain>/<user>/out/<msg_id>/data.<ext>
Attachments: same directory, collision-resolved via numeric suffix (file_1.pdf, file_2.pdf, …). msg_attachment.filename always stores the original intended name; filepath stores the resolved path on disk.

Path traversal protection validates all resolved paths are prefixed by FMSG_DATA_DIR before serving downloads.

Dependencies

Package Role
github.com/gin-gonic/gin HTTP framework
github.com/appleboy/gin-jwt/v2 JWT middleware
github.com/jackc/pgx/v5 PostgreSQL driver + pool
github.com/joho/godotenv .env file loading
Original prompt

You are building a production-quality HTTP API from scratch.

The API exposes CRUD operations for a messaging datastore implemented in PostgreSQL.
Authentication is not implemented by this service — it trusts JWT tokens issued by another system.

The service must strictly enforce authorization rules based on the user identity contained in the JWT.


Technology Stack

Implement the system using:

  • Go 1.25
  • Gin web framework
  • JWT authorization middleware using github.com/appleboy/gin-jwt
  • PostgreSQL 18

No user registration, authentication, or identity management should be implemented.
The API must simply validate JWT tokens and extract the user identity.


Repository Layout

Create the repository with the following the Gin Web Framework best practices. All code should live under /src directory.

The project must compile with:

go build ./...

JWT Authorization

The API must use github.com/appleboy/gin-jwt middleware.

JWT tokens contain a string identity representing the user address.

Example identity:

@user@example.com

This identity must be extracted from the JWT and used for authorization checks.

Handlers must obtain the user identity from the Gin request context.


Authorization Rules

All access control must follow these rules.

Message Ownership

A message is owned by the user where:

msg.from_addr == <JWT identity>

Only the owner may:

  • create messages
  • update draft messages
  • delete draft messages
  • upload attachments
  • delete attachments

Draft vs Sent Messages

A message is considered sent when:

msg.time_sent IS NOT NULL

Rules:

Operation Allowed if Draft Allowed if Sent
Update message yes no
Delete message yes no

Once a message has been sent it becomes immutable.


Recipient Access

Users whose address appears in:

msg_to.addr

may only perform read operations.

Allowed:

  • GET /messages/{id}
  • GET /messages/{id}/attachments/{filename}

Recipients must never modify messages or attachments.


JSON Message Format

The HTTP API must send and receive messages using the following JSON structure:

{
    "version": 1,
    "flags": 0,
    "pid": null,
    "from": "@markmnl@fmsg.io",
    "to": [
        "@世界@example.com",
        "@chris@fmsg.io"
    ],
    "time": 1654503265.679954,
    "topic": "Hello fmsg!",
    "type": "text/plain;charset=UTF-8",
    "size": 45,
    "data": "The quick brown fox jumps over the lazy dog.",
    "attachments": [
        {
            "size": 1024,
            "filename": "doc.pdf"
        }
    ]
}

Notes:

  • time corresponds to msg.time_sent
  • to corresponds to entries in msg_to
  • attachments correspond to rows in msg_attachment

Attachment Handling

Attachments must be handled independently of message JSON.

Uploads and downloads must occur one attachment at a time.

Endpoints must operate using:

msg_id
filename

Authorization rules are identical to message rules:

Operation Owner Recipient
Upload attachment yes no
Delete attachment yes no
Download attachment yes yes

Attachments cannot be modified or deleted once the message has been sent.


API Routes

Base prefix:

/api/v1

Message Routes

Create message (draft):

POST /api/v1/messages

Retrieve message:

GET /api/v1/messages/{id}

Update message (draft only):

PUT /api/v1/messages/{id}

Delete message (draft only):

DELETE /api/v1/messages/{id}

Send message:

POST /api/v1/messages/{id}/send

Sending a message sets time_sent.


Attachment Routes

Upload attachment:

POST /api/v1/messages/{id}/attachments

Download attachment:

GET /api/v1/messages/{id}/attachments/{filename}

Delete attachment:

DELETE /api/v1/messages/{id}/attachments/{filename}

Uploads must store files on disk using the filepath column.


PostgreSQL Schema

ASSUME database schema already created

create table if not exists msg (
    id              bigserial primary key,
    version         int not null,
    pid             bigint references msg (id),
    flags           int not null,
    time_sent       double precision,
    from_addr       varchar(255) not null,
    topic           varchar(255) not null,
    type            varchar(255) not null,
    sha256          bytea unique not null,
    psha256         bytea,
    size            int not null,
    filepath        text not null
);
create table if not exists msg_to (
    id                 bigserial primary key,
    msg_id             bigint not null references msg (id),
    addr               varchar(255) not nu...

</details>



<!-- START COPILOT CODING AGENT TIPS -->
---

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more [Copilot coding agent tips](https://gh.io/copilot-coding-agent-tips) in the docs.

…ttachment handling

Co-authored-by: markmnl <2630321+markmnl@users.noreply.github.com>
Copilot AI changed the title [WIP] Create production-quality HTTP API for messaging datastore Implement fmsg-webapi: production HTTP API for messaging with JWT auth Mar 8, 2026
@markmnl markmnl marked this pull request as ready for review March 8, 2026 06:56
@markmnl markmnl merged commit 6329770 into main Mar 8, 2026
1 check failed
Copilot stopped work on behalf of markmnl due to an error March 8, 2026 06:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants