Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ HTTP API providing user/client message handling for an fmsg host. Exposes CRUD o
| `FMSG_API_PORT` | `443` (TLS) / `8000` (plain) | TCP port to listen on. |
| `FMSG_ID_URL` | `http://127.0.0.1:8080` | Base URL of the fmsgid identity service |
| `FMSG_API_MAX_DATA_SIZE`| `10` | Maximum message data size in megabytes |
| `FMSG_API_MAX_ATTACH_SIZE`| `10` | Maximum attachment file size in megabytes |
| `FMSG_API_MAX_ATTACH_SIZE`| `10` | Maximum attachment file size in megabytes (HTTP `ReadTimeout` of 60s and `WriteTimeout` of 65s bound upload/download duration) |
| `FMSG_API_MAX_MSG_SIZE`| `20` | Maximum total message size (data + attachments) in megabytes |
| `FMSG_API_SHORT_TEXT_SIZE`| `768` | Maximum bytes of message body returned inline as `short_text` for `text/*` UTF-8 messages |
| `FMSG_RETRY_MAX_AGE` | `86400` | Seconds fmsgd keeps retrying a delivery after the message was sent (its `FMSG_RETRY_MAX_AGE`; set both the same). A delivery older than this has been given up on and no longer keeps a deleted-for-good message on the host. |
Expand Down Expand Up @@ -1152,6 +1152,7 @@ and send time. Ancestors the caller is not a participant of appear as
| ------ | --------- |
| `404` | Message not found |
| `403` | Authenticated user is not a participant of the requested message |
| `413` | Aggregate inline text exceeds 32 MiB (`thread_too_large`) |

### GET `/fmsg/:id/thread/messages`

Expand Down
23 changes: 15 additions & 8 deletions cmd/fmsg-webapi/apikey_cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"errors"
"flag"
"fmt"
"net/http"
Expand Down Expand Up @@ -57,23 +58,26 @@ func runAPIKeyCreate(ctx context.Context, args []string) error {
// Match the self-service sub-account flow: derived addresses are created in
// fmsgid, in the owner's quota pool, before their API key is persisted, and
// one used before is reinstated.
reinstated, err := middleware.RegisterLinkedFmsgID(idURL, subAddr, *owner)
created, reinstated, err := middleware.RegisterLinkedFmsgIDContext(ctx, idURL, subAddr, *owner)
if err != nil {
return fmt.Errorf("registering derived address with fmsgid: %w", err)
}
if err := requireAcceptingCLIAddress(idURL, subAddr, "derived address"); err != nil {
return err
}
granted := false
if reinstated {
conflict := false
if created || reinstated {
defer func() {
if !granted {
if err := middleware.DisableFmsgID(idURL, subAddr); err != nil {
fmt.Fprintf(os.Stderr, "re-disabling reinstated address %s: %v\n", subAddr, err)
if !granted && !conflict {
disableCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := middleware.DisableFmsgIDContext(disableCtx, idURL, subAddr); err != nil {
fmt.Fprintf(os.Stderr, "disabling address %s after failed create: %v\n", subAddr, err)
}
}
}()
}
if err := requireAcceptingCLIAddress(idURL, subAddr, "derived address"); err != nil {
return err
}
database, err := db.New(ctx, "")
if err != nil {
return err
Expand All @@ -82,6 +86,9 @@ func runAPIKeyCreate(ctx context.Context, args []string) error {

store := apiauth.NewStore(database)
if err := store.Create(ctx, *owner, *agent, subAddr, key.ID, hash, allowed, expires); err != nil {
if errors.Is(err, apiauth.ErrAlreadyExists) {
conflict = true
}
return err
}
granted = true
Expand Down
52 changes: 40 additions & 12 deletions cmd/fmsg-webapi/apikey_cli_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,23 +301,43 @@ func TestAPIKeyExchangeRejectsUnregisteredDerivedAddress(t *testing.T) {
}

// TestAPIKeyCLICreateReinstates creates a derived sub-account whose address was
// used before: fmsgid reinstates it, the CLI says so, and when the grant can't
// be created the address is stopped accepting new messages again.
// used before: fmsgid reinstates it, the CLI says so; when the grant can't be
// created due to a non-conflict error (e.g. limit exceeded), the address is
// stopped accepting new messages again; on conflict (ErrAlreadyExists, such as
// a concurrent winner), the active address is left untouched.
func TestAPIKeyCLICreateReinstates(t *testing.T) {
for _, conflict := range []bool{false, true} {
t.Run(fmt.Sprintf("conflict=%v", conflict), func(t *testing.T) {
for _, mode := range []string{"success", "limit_exceeded", "conflict"} {
t.Run(mode, func(t *testing.T) {
database := newAPIKeyCLIDB(t)
const owner = "@alice@example.com"
const target = "@alice_bot@example.com"
if conflict {
store := apiauth.NewStore(database)
switch mode {
case "conflict":
key, err := apiauth.GenerateAPIKey()
if err != nil {
t.Fatal(err)
}
if err := apiauth.NewStore(database).Create(context.Background(), owner, "bot", target, key.ID,
if err := store.Create(context.Background(), owner, "bot", target, key.ID,
apiauth.HashAPIKey(key.Value), []string{"127.0.0.0/8"}, time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
case "limit_exceeded":
for i := range apiauth.DefaultMaxSubAccounts {
key, err := apiauth.GenerateAPIKey()
if err != nil {
t.Fatal(err)
}
agent := fmt.Sprintf("other%d", i)
addr, err := apiauth.DeriveSubAccountAddr(owner, agent)
if err != nil {
t.Fatal(err)
}
if err := store.Create(context.Background(), owner, agent, addr, key.ID,
apiauth.HashAPIKey(key.Value), []string{"127.0.0.0/8"}, time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
}
}
var mu sync.Mutex
accepting := false // the address exists and was disabled
Expand Down Expand Up @@ -357,17 +377,25 @@ func TestAPIKeyCLICreateReinstates(t *testing.T) {
"-expires", time.Now().Add(time.Hour).UTC().Format(time.RFC3339)})
mu.Lock()
defer mu.Unlock()
if conflict {
switch mode {
case "limit_exceeded":
if err == nil {
t.Fatal("create succeeded despite an existing grant")
t.Fatal("create succeeded despite exceeding sub-account limit")
}
if accepting {
t.Fatal("address left reinstated although its grant wasn't created")
}
return
}
if err != nil || !strings.Contains(output, "\nreinstated=true\n") || !accepting {
t.Fatalf("create: err=%v accepting=%v output=%q", err, accepting, output)
case "conflict":
if err == nil {
t.Fatal("create succeeded despite an existing grant")
}
if !accepting {
t.Fatal("conflicting create disabled an already-granted address")
}
default:
if err != nil || !strings.Contains(output, "\nreinstated=true\n") || !accepting {
t.Fatalf("create: err=%v accepting=%v output=%q", err, accepting, output)
}
}
})
}
Expand Down
64 changes: 58 additions & 6 deletions cmd/fmsg-webapi/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import (
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"

"github.com/MicahParks/keyfunc/v3"
Expand Down Expand Up @@ -83,8 +85,12 @@ func main() {
pushIconURL := envOrDefault("FMSG_PUSH_ICON_URL", "/icon-192.png")
pushEnabled := vapidPublic != "" && vapidPrivate != "" && vapidSubject != ""

// Root context cancelled on SIGINT/SIGTERM for graceful shutdown of the
// HTTP server, JWKS refresher, LISTEN/NOTIFY hub, and Web Push workers.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

// Connect to PostgreSQL (uses standard PG* environment variables).
ctx := context.Background()
database, err := db.New(ctx, "")
if err != nil {
log.Fatalf("failed to connect to database: %v", err)
Expand Down Expand Up @@ -170,7 +176,14 @@ func main() {
// The hub also dispatches a Web Push for every new_msg notification.
hub.SetPushNotifier(pushHandler.NotifyNewMsg)
}
go hub.Run(context.Background())
// The hub runs on its own context so it keeps LISTENing for notifications
// from in-flight HTTP requests while the server drains on shutdown.
hubCtx, cancelHub := context.WithCancel(context.Background())
hubDone := make(chan struct{})
go func() {
defer close(hubDone)
hub.Run(hubCtx)
}()
wsHandler := handlers.NewWSHandler(jwtVerifier, hub, corsOrigins)

var tokenHandler *handlers.TokenHandler
Expand All @@ -185,26 +198,65 @@ func main() {
srv := &http.Server{
Handler: router,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the record, since it now bounds uploads: ReadTimeout covers the whole request body, so an attachment at the default 10 MiB FMSG_API_MAX_ATTACH_SIZE needs about 1.4 Mbit/s sustained to make it in 60s. That is not a new ceiling in practice, because the 65s WriteTimeout deadline is set when the headers are read, so a slower upload was already stored and then failed to answer. Failing the read is the cleaner of the two. If larger limits are configured these two timeouts need to scale with them; a line in the README next to FMSG_API_MAX_ATTACH_SIZE would save someone the debugging.

WriteTimeout: 65 * time.Second, // generous, to allow large file transfers
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 1 << 20, // 1 MB
}

serveErr := make(chan error, 1)
if tlsEnabled {
port := envOrDefault("FMSG_API_PORT", "443")
srv.Addr = ":" + port
log.Printf("fmsg-webapi starting on :%s (HTTPS)", port)
srv.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
if err = srv.ListenAndServeTLS(tlsCert, tlsKey); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("server error: %v", err)
}
go func() {
if err := srv.ListenAndServeTLS(tlsCert, tlsKey); err != nil && !errors.Is(err, http.ErrServerClosed) {
serveErr <- err
}
close(serveErr)
}()
} else {
port := envOrDefault("FMSG_API_PORT", "8000")
srv.Addr = ":" + port
log.Printf("fmsg-webapi starting on :%s (plain HTTP)", port)
if err = srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
serveErr <- err
}
close(serveErr)
}()
}

select {
case err := <-serveErr:
stop()
cancelHub()
<-hubDone
pushDrainCtx, cancelPushDrain := context.WithTimeout(context.Background(), 5*time.Second)
if closeErr := hub.CloseContext(pushDrainCtx); closeErr != nil {
log.Printf("push shutdown error: %v", closeErr)
}
cancelPushDrain()
if err != nil {
log.Fatalf("server error: %v", err)
}
case <-ctx.Done():
log.Println("fmsg-webapi shutting down...")
stop()

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ordering: the hub runs on this same signal context, so it stops LISTENing the moment the signal arrives, while srv.Shutdown then lets in-flight requests run for up to 15s. Any send / react / edit / add-to that commits during that drain fires NOTIFY new_msg with nobody listening, so its WebSocket events and Web Pushes are silently lost. (stop() here only restores default signal handling; the context is already cancelled.)

Giving the hub its own context.WithCancel(context.Background()) and cancelling it after srv.Shutdown returns closes the gap: stop accepting, drain requests, then stop the listener, then drain pushes.

Also note 15s is longer than Docker's default 10s stop grace, so under compose a slow drain is cut off by SIGKILL unless stop_grace_period is raised.

shutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutCtx); err != nil {
log.Printf("server shutdown error: %v", err)
}
<-serveErr
cancelHub()
<-hubDone
pushDrainCtx, cancelPushDrain := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelPushDrain()
if err := hub.CloseContext(pushDrainCtx); err != nil {
log.Printf("push shutdown error: %v", err)
}
}
}

Expand Down
6 changes: 6 additions & 0 deletions internal/apiauth/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,12 @@ func (s *Store) createGrant(ctx context.Context, ownerAddr, agent, subAddr, gran
}
defer tx.Rollback(ctx) //nolint:errcheck

// Serialize concurrent grant creations for the same owner so max_sub_accounts
// cannot be bypassed via a read-then-insert race.
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext(lower($1)))`, ownerAddr); err != nil {
return err
}

max, err := maxSubAccountsTx(ctx, tx, ownerAddr)
if err != nil {
return err
Expand Down
1 change: 1 addition & 0 deletions internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func New(ctx context.Context, dsn string) (*DB, error) {
return nil, fmt.Errorf("db: failed to create pool: %w", err)
}
if err = pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("db: failed to ping: %w", err)
}
return &DB{Pool: pool}, nil
Expand Down
Loading