From c488a01367f22a4cbe16aa902f9855ea643f7be0 Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Thu, 26 Nov 2026 10:08:38 +0800 Subject: [PATCH 1/3] Sub-accounts: a failed create never disables an address that has a grant A create that registered or reinstated its address disables it again when no grant comes of it. It decided that from its own error, skipping the disable only on ErrAlreadyExists. But the owner's limit is checked before the insert, so the loser of a race for the same address can be told the limit is reached instead, and it then disabled the address under the winner's grant. - Before disabling, ask the store whether the address has a grant, holding the lock grant creation takes for the owner (Store.UnlessGranted). The error only decides when the store can't be asked. - A create that found its address already registered confirms it accepts once its own grant is stored, in case the create that registered it failed and undid the registration in between. - api-key create (CLI) uses the same check, and opens the database before registering the address. Fixes #72. Co-Authored-By: Claude Fable 5.2 --- cmd/fmsg-webapi/apikey_cli.go | 26 +++---- internal/apiauth/store.go | 29 +++++++ internal/handlers/subaccounts.go | 71 +++++++++++++++--- .../handlers/subaccounts_lifecycle_test.go | 75 ++++++++++++++++++- 4 files changed, 176 insertions(+), 25 deletions(-) diff --git a/cmd/fmsg-webapi/apikey_cli.go b/cmd/fmsg-webapi/apikey_cli.go index 8088dc2..1a792d8 100644 --- a/cmd/fmsg-webapi/apikey_cli.go +++ b/cmd/fmsg-webapi/apikey_cli.go @@ -12,6 +12,7 @@ import ( "github.com/markmnl/fmsg-webapi/internal/apiauth" "github.com/markmnl/fmsg-webapi/internal/db" + "github.com/markmnl/fmsg-webapi/internal/handlers" "github.com/markmnl/fmsg-webapi/internal/middleware" ) @@ -55,6 +56,14 @@ func runAPIKeyCreate(ctx context.Context, args []string) error { if err := requireAcceptingCLIAddress(idURL, *owner, "owner"); err != nil { return err } + // Open the database first: undoing a registration needs it. + database, err := db.New(ctx, "") + if err != nil { + return err + } + defer database.Close() + store := apiauth.NewStore(database) + // 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. @@ -65,26 +74,17 @@ func runAPIKeyCreate(ctx context.Context, args []string) error { if err := requireAcceptingCLIAddress(idURL, subAddr, "derived address"); err != nil { return err } + // Undo registration or reinstatement if no grant comes of it, unless the + // address has a grant after all (a concurrent create won the race). granted := false conflict := false if created || reinstated { defer func() { - 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 !granted { + handlers.UndoLinkedRegistration(store, idURL, *owner, subAddr, conflict) } }() } - database, err := db.New(ctx, "") - if err != nil { - return err - } - defer database.Close() - - 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 diff --git a/internal/apiauth/store.go b/internal/apiauth/store.go index 5631597..6fde08b 100644 --- a/internal/apiauth/store.go +++ b/internal/apiauth/store.go @@ -173,6 +173,35 @@ func (s *Store) createGrant(ctx context.Context, ownerAddr, agent, subAddr, gran return tx.Commit(ctx) } +// UnlessGranted runs fn only if no grant exists for subAddr, and reports +// whether it ran. It holds the lock createGrant takes for ownerAddr while it +// checks and while fn runs, so a concurrent create for the same owner either +// commits its grant first (fn is skipped) or inserts after fn has finished. +func (s *Store) UnlessGranted(ctx context.Context, ownerAddr, subAddr string, fn func() error) (bool, error) { + tx, err := s.DB.Pool.Begin(ctx) + if err != nil { + return false, err + } + defer tx.Rollback(ctx) //nolint:errcheck + + if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext(lower($1)))`, ownerAddr); err != nil { + return false, err + } + var granted bool + if err := tx.QueryRow(ctx, + `SELECT EXISTS (SELECT 1 FROM fmsg_api_sub_account WHERE lower(sub_addr) = lower($1))`, + subAddr).Scan(&granted); err != nil { + return false, err + } + if granted { + return false, nil + } + if err := fn(); err != nil { + return true, err + } + return true, tx.Commit(ctx) +} + func (s *Store) RotateKey(ctx context.Context, ownerAddr, agent, keyID string, keyHash []byte, keyExpiresAt time.Time) (string, error) { var subAddr string err := s.DB.Pool.QueryRow(ctx, diff --git a/internal/handlers/subaccounts.go b/internal/handlers/subaccounts.go index f5c72ca..1da3941 100644 --- a/internal/handlers/subaccounts.go +++ b/internal/handlers/subaccounts.go @@ -150,15 +150,14 @@ func (h *SubAccountHandler) Create(c *gin.Context) { } // Undo registration or reinstatement if no grant comes of it, so a // newly-registered or deleted address doesn't stay accepting new messages - // without a grant. An already-active address or a concurrent create that - // won the race (ErrAlreadyExists) is left untouched so an active grant is - // never disabled. + // without a grant. An address that has a grant after all (a concurrent + // create won the race) is left as it is. granted := false conflict := false if created || reinstated { defer func() { - if !granted && !conflict { - disableAfterFailedCreate(h.idURL, subAddr) + if !granted { + UndoLinkedRegistration(h.store, h.idURL, owner, subAddr, conflict) } }() } @@ -177,6 +176,13 @@ func (h *SubAccountHandler) Create(c *gin.Context) { return } granted = true + if !created && !reinstated { + // The address was registered by a create that may since have failed + // and undone its registration; make sure this grant's address accepts. + if err := ensureLinkedRegistration(h.idURL, owner, subAddr); err != nil { + log.Printf("sub-account create: confirming address accepts: addr=%s: %v", subAddr, err) + } + } c.JSON(http.StatusCreated, createSubAccountResponse{ subAccountResponse: subAccountResponse{ Agent: in.Agent, @@ -191,15 +197,58 @@ func (h *SubAccountHandler) Create(c *gin.Context) { }) } -// disableAfterFailedCreate stops a newly-registered or reinstated derived -// address accepting new messages after its grant couldn't be created. It is -// best effort: the create has already failed, so a failure here is only logged. -func disableAfterFailedCreate(idURL, addr string) { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) +// linkedRegistrationTimeout bounds the identity-service calls made after a +// create has been decided, which run detached from the request. +const linkedRegistrationTimeout = 5 * time.Second + +// UndoLinkedRegistration stops a newly-registered or reinstated derived +// address accepting new messages after its grant couldn't be created, unless +// the address has a grant after all: a concurrent create for the same address +// can win, and the loser doesn't always learn that from its own error (it may +// be told the owner's limit is reached instead). It is best effort: the create +// has already failed, so a failure here is only logged. +// +// conflict reports that the store refused the create because the grant +// exists. It decides only when the store can't be asked. +func UndoLinkedRegistration(store *apiauth.Store, idURL, owner, addr string, conflict bool) { + ctx, cancel := context.WithTimeout(context.Background(), 2*linkedRegistrationTimeout) defer cancel() - if err := middleware.DisableFmsgIDContext(ctx, idURL, addr); err != nil { + attempted := false + _, err := store.UnlessGranted(ctx, owner, addr, func() error { + attempted = true + return disableLinkedAddress(idURL, addr) + }) + if err == nil { + return + } + if attempted { log.Printf("sub-account create: disabling address after failure: addr=%s: %v", addr, err) + return + } + log.Printf("sub-account create: checking for a grant before disabling: addr=%s: %v", addr, err) + if conflict { + return } + if err := disableLinkedAddress(idURL, addr); err != nil { + log.Printf("sub-account create: disabling address after failure: addr=%s: %v", addr, err) + } +} + +func disableLinkedAddress(idURL, addr string) error { + ctx, cancel := context.WithTimeout(context.Background(), linkedRegistrationTimeout) + defer cancel() + return middleware.DisableFmsgIDContext(ctx, idURL, addr) +} + +// ensureLinkedRegistration makes sure a derived address that now has a grant +// accepts new messages. A create that found the address already registered +// calls it once its grant is stored, because the create that registered the +// address may have failed and undone the registration in the meantime. +func ensureLinkedRegistration(idURL, owner, addr string) error { + ctx, cancel := context.WithTimeout(context.Background(), linkedRegistrationTimeout) + defer cancel() + _, _, err := middleware.RegisterLinkedFmsgIDContext(ctx, idURL, addr, owner) + return err } func (h *SubAccountHandler) RotateKey(c *gin.Context) { diff --git a/internal/handlers/subaccounts_lifecycle_test.go b/internal/handlers/subaccounts_lifecycle_test.go index edf3973..49d356b 100644 --- a/internal/handlers/subaccounts_lifecycle_test.go +++ b/internal/handlers/subaccounts_lifecycle_test.go @@ -32,6 +32,10 @@ type fakeFmsgID struct { // legacy answers POST /fmsgid like an fmsgid without accepting_new: it // ignores accepting_new and quota_pool and returns no body. legacy bool + // afterPost, when set, runs once a POST /fmsgid has been applied and + // before it is answered, with f.mu held. Tests use it to interleave a + // concurrent request at that point. + afterPost func(addr string) } func newFakeFmsgID(t *testing.T, addrs ...string) (*fakeFmsgID, *httptest.Server) { @@ -93,6 +97,10 @@ func (f *fakeFmsgID) ServeHTTP(w http.ResponseWriter, r *http.Request) { if p, ok := body["quota_pool"].(string); ok { f.pool[addr] = strings.ToLower(p) } + reinstated := existed && !was && f.accepting[addr] + if f.afterPost != nil { + f.afterPost(addr) + } status := http.StatusCreated if existed { status = http.StatusOK @@ -100,7 +108,7 @@ func (f *fakeFmsgID) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(status) _ = json.NewEncoder(w).Encode(map[string]bool{ "created": !existed, - "reinstated": existed && !was && f.accepting[addr], + "reinstated": reinstated, }) default: w.WriteHeader(http.StatusNotFound) @@ -338,6 +346,71 @@ func TestSubAccountCreateFailureUndoesReinstatement(t *testing.T) { } } +// TestSubAccountCreateLoserLeavesWinnersAddress: two creates race for the same +// address with the owner one below the limit. The one that registered the +// address loses, and is told the limit is reached rather than that the grant +// exists. It must not disable the address under the winner's grant. +func TestSubAccountCreateLoserLeavesWinnersAddress(t *testing.T) { + store := newSubAccountTestStore(t) + id, server := newFakeFmsgID(t, lifecycleOwner) + r := subAccountRouter(NewSubAccountHandler(store, server.URL)) + + for i := range apiauth.DefaultMaxSubAccounts - 1 { + createSubAccount(t, r, fmt.Sprintf("bot%d", i), http.StatusCreated) + } + + const addr = "@alice_race@example.com" + // The winner's grant lands between the loser's registration of the address + // and the loser's own attempt to store a grant. + id.afterPost = func(posted string) { + if posted != addr { + return + } + id.afterPost = nil + if err := store.Create(context.Background(), lifecycleOwner, "race", addr, "winner-key", []byte("hash"), + []string{"127.0.0.0/8"}, time.Now().Add(time.Hour)); err != nil { + t.Errorf("winner's create: %v", err) + } + } + + createSubAccount(t, r, "race", http.StatusForbidden) + + if accepting, exists := id.isAccepting(addr); !exists || !accepting { + t.Fatalf("the losing create disabled the address under the winner's grant (exists=%t accepting=%t)", exists, accepting) + } + if _, err := store.Get(context.Background(), lifecycleOwner, "race"); err != nil { + t.Fatalf("winner's grant: %v", err) + } +} + +// TestSubAccountCreateConfirmsAddressItDidNotRegister: a create that finds +// its address already registered (by a concurrent create that then fails and +// undoes its registration) makes sure the address accepts once its own grant +// is stored. +func TestSubAccountCreateConfirmsAddressItDidNotRegister(t *testing.T) { + store := newSubAccountTestStore(t) + const addr = "@alice_race@example.com" + id, server := newFakeFmsgID(t, lifecycleOwner, addr) + id.pool[addr] = lifecycleOwner + r := subAccountRouter(NewSubAccountHandler(store, server.URL)) + + // The other create's undo lands after this create saw the address + // accepting and before its grant is stored. + id.afterPost = func(posted string) { + if posted != addr { + return + } + id.afterPost = nil + id.accepting[addr] = false + } + + createSubAccount(t, r, "race", http.StatusCreated) + + if accepting, _ := id.isAccepting(addr); !accepting { + t.Fatal("the address of a stored grant was left not accepting new messages") + } +} + // TestSubAccountCreateRefusesSomeoneElsesAddress: a derived address that // already exists outside the owner's pool (an account someone else signed up // for, or a closed one) is refused, and neither fmsgid nor the grants change. From 98d21fd93ff57b387d731a3bce8cae639de2782d Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Thu, 26 Nov 2026 10:09:37 +0800 Subject: [PATCH 2/3] Web Push: send what is queued on shutdown instead of cancelling it Shutdown cancelled the push context before waiting, so the 5 seconds it allowed only bounded how long workers took to notice. Pushes for messages committed just before or during the HTTP drain were dropped. Hub.DrainContext stops accepting jobs, lets the workers send what is queued and in flight, and cancels the remainder only when its deadline passes. Graceful shutdown uses it; the server-error path still cancels. Fixes #73. Co-Authored-By: Claude Fable 5.2 --- cmd/fmsg-webapi/main.go | 6 ++- internal/handlers/hub.go | 78 +++++++++++++++++++++++++++-------- internal/handlers/hub_test.go | 71 +++++++++++++++++++++++++++++++ 3 files changed, 136 insertions(+), 19 deletions(-) diff --git a/cmd/fmsg-webapi/main.go b/cmd/fmsg-webapi/main.go index 83b6dfc..b1c5939 100644 --- a/cmd/fmsg-webapi/main.go +++ b/cmd/fmsg-webapi/main.go @@ -252,10 +252,12 @@ func main() { <-serveErr cancelHub() <-hubDone + // Send the Web Pushes already queued, including those for requests + // that committed during the drain above, before giving up on the rest. 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) + if err := hub.DrainContext(pushDrainCtx); err != nil { + log.Printf("push shutdown: gave up on queued pushes: %v", err) } } } diff --git a/internal/handlers/hub.go b/internal/handlers/hub.go index 06796b4..88fb66e 100644 --- a/internal/handlers/hub.go +++ b/internal/handlers/hub.go @@ -171,39 +171,83 @@ func (h *Hub) Close() { _ = h.CloseContext(context.Background()) } -// CloseContext shuts down the bounded Web Push worker pool, cancelling its -// push context so queued jobs are skipped and in-flight pushes abort promptly, -// and waits for workers to exit until ctx is cancelled. -func (h *Hub) CloseContext(ctx context.Context) error { +// pushAbortGrace is how long DrainContext waits for workers to exit after it +// has cancelled their pushes. +const pushAbortGrace = time.Second + +// closePushQueue stops the pool accepting jobs. Workers exit once they have +// taken everything already queued. +func (h *Hub) closePushQueue() { h.pushMu.Lock() - if !h.pushClosed { - h.pushClosed = true - if h.pushCancel != nil { - h.pushCancel() - } - if h.pushCh != nil { - close(h.pushCh) - } + defer h.pushMu.Unlock() + if h.pushClosed { + return } - h.pushMu.Unlock() + h.pushClosed = true + if h.pushCh != nil { + close(h.pushCh) + } +} - if ctx == nil { - h.pushWG.Wait() - return nil +// cancelPushes aborts in-flight pushes and makes workers skip what is queued. +func (h *Hub) cancelPushes() { + h.pushMu.Lock() + defer h.pushMu.Unlock() + if h.pushCancel != nil { + h.pushCancel() } +} + +// pushWorkersDone is closed once every push worker has exited. +func (h *Hub) pushWorkersDone() <-chan struct{} { done := make(chan struct{}) go func() { h.pushWG.Wait() close(done) }() + return done +} + +// CloseContext shuts down the bounded Web Push worker pool, cancelling its +// push context so queued jobs are skipped and in-flight pushes abort promptly, +// and waits for workers to exit until ctx is cancelled. +func (h *Hub) CloseContext(ctx context.Context) error { + h.closePushQueue() + h.cancelPushes() + + if ctx == nil { + h.pushWG.Wait() + return nil + } select { - case <-done: + case <-h.pushWorkersDone(): return nil case <-ctx.Done(): return ctx.Err() } } +// DrainContext shuts down the bounded Web Push worker pool without losing +// work: it stops accepting jobs and lets the workers send what is queued and +// in flight, waiting for them until ctx is done. If ctx ends first it cancels +// what remains, as CloseContext does, and returns ctx's error. +func (h *Hub) DrainContext(ctx context.Context) error { + h.closePushQueue() + done := h.pushWorkersDone() + select { + case <-done: + h.cancelPushes() // nothing left to cancel; releases the push context + return nil + case <-ctx.Done(): + } + h.cancelPushes() + select { + case <-done: + case <-time.After(pushAbortGrace): + } + return ctx.Err() +} + func (h *Hub) enqueuePush(msgID int64, addr string) { h.pushMu.Lock() if h.pushClosed { diff --git a/internal/handlers/hub_test.go b/internal/handlers/hub_test.go index 888e98b..288bdd0 100644 --- a/internal/handlers/hub_test.go +++ b/internal/handlers/hub_test.go @@ -400,3 +400,74 @@ func TestHubCloseContext_RespectsDeadlineWhenWorkerBlocks(t *testing.T) { t.Fatalf("CloseContext err = %v, want context.DeadlineExceeded", err) } } + +func TestHubDrainContext_SendsQueuedPushes(t *testing.T) { + hub := newTestHub() + hub.pushWorkers = 2 + hub.pushQueueSize = 16 + + const total = 8 + var completed, cancelled syncatomic.Int32 + hub.SetPushNotifier(func(ctx context.Context, _ int64, _ string) { + time.Sleep(15 * time.Millisecond) + if ctx.Err() != nil { + cancelled.Add(1) + return + } + completed.Add(1) + }) + for i := int64(1); i <= total; i++ { + hub.route(context.Background(), "new_msg", i, "@offline@x") + } + + drainCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := hub.DrainContext(drainCtx); err != nil { + t.Fatalf("DrainContext returned error: %v", err) + } + if got := completed.Load(); got != total { + t.Fatalf("pushes sent = %d, want all %d queued at shutdown (cancelled: %d)", got, total, cancelled.Load()) + } + + // The pool is closed: a later notification is not queued. + hub.route(context.Background(), "new_msg", total+1, "@offline@x") + time.Sleep(30 * time.Millisecond) + if got := completed.Load(); got != total { + t.Fatalf("a push was sent after the drain: %d", got) + } +} + +func TestHubDrainContext_CancelsWhatIsLeftAtTheDeadline(t *testing.T) { + hub := newTestHub() + hub.pushWorkers = 1 + hub.pushQueueSize = 4 + + started := make(chan struct{}, 1) + var called, cancelled syncatomic.Int32 + hub.SetPushNotifier(func(ctx context.Context, _ int64, _ string) { + called.Add(1) + started <- struct{}{} + <-ctx.Done() + cancelled.Add(1) + }) + hub.route(context.Background(), "new_msg", 1, "@offline@x") + <-started + hub.route(context.Background(), "new_msg", 2, "@offline@x") + + drainCtx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + start := time.Now() + err := hub.DrainContext(drainCtx) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("DrainContext err = %v, want context.DeadlineExceeded", err) + } + if elapsed := time.Since(start); elapsed > pushAbortGrace { + t.Fatalf("DrainContext took %s; workers should exit promptly once cancelled", elapsed) + } + if got := cancelled.Load(); got != 1 { + t.Fatalf("in-flight pushes observing cancellation = %d, want 1", got) + } + if got := called.Load(); got != 1 { + t.Fatalf("notifyPush called %d times, want 1 (the queued job is skipped after cancel)", got) + } +} From de0cf0e3e83a66ffa59136576910a1be52a255b3 Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Thu, 26 Nov 2026 10:09:37 +0800 Subject: [PATCH 3/3] gofmt internal/handlers/transaction.go Co-Authored-By: Claude Fable 5.2 --- internal/handlers/transaction.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/handlers/transaction.go b/internal/handlers/transaction.go index 1b8833d..841e3aa 100644 --- a/internal/handlers/transaction.go +++ b/internal/handlers/transaction.go @@ -75,6 +75,7 @@ func afterCommit(c *gin.Context, f func()) { f() } } + // beginOrReuseTx returns q directly when it is already a pgx.Tx (inside Atomic), // avoiding a redundant SAVEPOINT round-trip. When reusing an outer transaction, // commit and rollback are no-ops because Atomic commits on <400 responses and