From 1059b10def5b429255440297c580f7bc148dad97 Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Thu, 29 Oct 2026 18:12:01 +0800 Subject: [PATCH] Sub-accounts: never take over an address someone else holds A derived address (@alice_bot from @alice) may already be someone else's: an identity provider can let anyone sign up as alice_bot. Registration now claims the address in fmsgid, so one outside the owner's quota pool gets 409 instead of being moved into the pool, reinstated, and handed to the owner with an API key. The owner's own deleted sub-accounts are still reinstated. Needs fmsgid with claim (markmnl/fmsgid#9). Co-Authored-By: Claude Opus 5.5 --- README.md | 13 ++++-- internal/handlers/subaccounts.go | 8 +++- .../handlers/subaccounts_lifecycle_test.go | 41 ++++++++++++++++++- internal/middleware/fmsgid_test.go | 8 +++- internal/middleware/jwt.go | 24 ++++++++--- 5 files changed, 81 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 65c0ae8..2983ffd 100644 --- a/README.md +++ b/README.md @@ -446,10 +446,13 @@ dots, and hyphens, but not underscores. The derived address is automatically registered with fmsgid, in the owner's quota pool so it shares the owner's quota — no manual fmsgid step is needed for derived sub-accounts. -Only the owner can derive `@user_bot@domain`, so if the address already exists -in fmsgid it is the owner's from before — a sub-account they deleted — and is +The name alone doesn't make `@user_bot@domain` the owner's: an identity +provider may let someone else sign up as `user_bot`. So the address is claimed +in fmsgid (`claim` on `POST /fmsgid`). If it already exists in the owner's +quota pool it is the owner's from before — a sub-account they deleted — and is reinstated: it accepts new messages again and its earlier messages are still -there. The response is the new grant, as from `GET /fmsg/sub-accounts/:agent`, +there. If it exists anywhere else, someone else holds it: the request fails +with `409` and nothing changes. The response is the new grant, as from `GET /fmsg/sub-accounts/:agent`, plus `api_key` (shown once) and `reinstated`, `true` for a reinstated address and `false` for a new one: @@ -469,7 +472,9 @@ and `false` for a new one: If the grant can't be created (e.g. `409` or the sub-account limit), a reinstated address is stopped accepting new messages again. Reinstating and pooling need an fmsgid that supports `accepting_new` and `quota_pool` on -`POST /fmsgid`; with an older one `reinstated` is always `false`. +`POST /fmsgid`; with an older one `reinstated` is always `false`. Refusing +someone else's address needs an fmsgid that supports `claim`: deploy that +fmsgid first, since an older one ignores `claim`. Delegated identities such as `@sales@example.com` are not created by this self-service route. They are operator-created with `api-key create-delegation` diff --git a/internal/handlers/subaccounts.go b/internal/handlers/subaccounts.go index ccf713c..2b25d2e 100644 --- a/internal/handlers/subaccounts.go +++ b/internal/handlers/subaccounts.go @@ -135,9 +135,13 @@ func (h *SubAccountHandler) Create(c *gin.Context) { } // Derived sub-accounts belong to an already-verified owner, so register // them in fmsgid automatically, in the owner's quota pool, rather than - // requiring a manual step. Only this owner can derive subAddr, so if it - // already exists there it was theirs before and is reinstated. + // requiring a manual step. One already in the owner's pool was theirs + // before and is reinstated; one held by anyone else is refused. reinstated, err := middleware.RegisterLinkedFmsgID(h.idURL, subAddr, owner) + if errors.Is(err, middleware.ErrLinkedAddressTaken) { + c.JSON(http.StatusConflict, gin.H{"error": "that name is already taken; choose another"}) + return + } if err != nil { log.Printf("sub-account create: fmsgid registration: addr=%s: %v", subAddr, err) c.JSON(http.StatusServiceUnavailable, gin.H{"error": "identity service unavailable"}) diff --git a/internal/handlers/subaccounts_lifecycle_test.go b/internal/handlers/subaccounts_lifecycle_test.go index e328fcb..edf3973 100644 --- a/internal/handlers/subaccounts_lifecycle_test.go +++ b/internal/handlers/subaccounts_lifecycle_test.go @@ -21,7 +21,7 @@ import ( ) // fakeFmsgID is an in-memory fmsgid serving GET /fmsgid/:address and -// POST /fmsgid with accepting_new and quota_pool. +// POST /fmsgid with accepting_new, quota_pool and claim. type fakeFmsgID struct { mu sync.Mutex accepting map[string]bool @@ -69,6 +69,13 @@ func (f *fakeFmsgID) ServeHTTP(w http.ResponseWriter, r *http.Request) { } addr := strings.ToLower(body["address"].(string)) was, existed := f.accepting[addr] + // a claim of an existing address outside the pool changes nothing + if claim, _ := body["claim"].(bool); claim && existed && !f.legacy { + if p, _ := body["quota_pool"].(string); f.pool[addr] != strings.ToLower(p) { + w.WriteHeader(http.StatusConflict) + return + } + } if !existed { f.accepting[addr] = true } @@ -331,6 +338,38 @@ func TestSubAccountCreateFailureUndoesReinstatement(t *testing.T) { } } +// 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. +func TestSubAccountCreateRefusesSomeoneElsesAddress(t *testing.T) { + store := newSubAccountTestStore(t) + id, server := newFakeFmsgID(t, lifecycleOwner, "@alice_bot@example.com", "@alice_closed@example.com") + id.accepting["@alice_closed@example.com"] = false + r := subAccountRouter(NewSubAccountHandler(store, server.URL)) + + for _, agent := range []string{"bot", "closed"} { + createSubAccount(t, r, agent, http.StatusConflict) + } + if accepting, _ := id.isAccepting("@alice_closed@example.com"); accepting { + t.Fatal("refused claim reinstated a closed address") + } + if len(id.pool) != 0 { + t.Fatalf("refused claims pooled %v", id.pool) + } + if _, grants, err := store.List(context.Background(), lifecycleOwner); err != nil || len(grants) != 0 { + t.Fatalf("grants after refused creates: %v, err=%v", grants, err) + } + + // the owner's own deleted sub-account is still reinstated + createSubAccount(t, r, "mine", http.StatusCreated) + if w := serveSubAccount(r, http.MethodDelete, "/fmsg/sub-accounts/mine", ""); w.Code != http.StatusNoContent { + t.Fatalf("delete: status %d", w.Code) + } + if out := createSubAccount(t, r, "mine", http.StatusCreated); out["reinstated"] != true { + t.Fatalf("re-create own sub-account: %v, want reinstated", out) + } +} + // TestSubAccountCreateLegacyFmsgID creates a sub-account with an fmsgid that // answers registration without a body: it is simply not reinstated. func TestSubAccountCreateLegacyFmsgID(t *testing.T) { diff --git a/internal/middleware/fmsgid_test.go b/internal/middleware/fmsgid_test.go index 5abf046..a81ec34 100644 --- a/internal/middleware/fmsgid_test.go +++ b/internal/middleware/fmsgid_test.go @@ -2,6 +2,7 @@ package middleware import ( "encoding/json" + "errors" "net/http" "net/http/httptest" "sync/atomic" @@ -47,7 +48,7 @@ func TestRegisterLinkedFmsgIDRefreshesExistingAddress(t *testing.T) { case r.Method == http.MethodPost && r.URL.Path == "/fmsgid": var body map[string]any if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body["address"] != addr || - body["accepting_new"] != true || body["quota_pool"] != "@alice@example.com" { + body["accepting_new"] != true || body["quota_pool"] != "@alice@example.com" || body["claim"] != true { t.Errorf("registration payload: %v, err=%v", body, err) w.WriteHeader(http.StatusBadRequest) return @@ -83,6 +84,7 @@ func TestRegisterLinkedFmsgIDResponses(t *testing.T) { body string wantReinstated bool wantErr bool + wantTaken bool }{ {name: "created", status: http.StatusCreated, body: `{"created":true,"reinstated":false}`}, {name: "existing", status: http.StatusOK, body: `{"created":false,"reinstated":false}`}, @@ -90,6 +92,7 @@ func TestRegisterLinkedFmsgIDResponses(t *testing.T) { {name: "fmsgid without accepting_new", status: http.StatusOK, body: ""}, {name: "malformed", status: http.StatusOK, body: "", wantErr: true}, {name: "quota pool refused", status: http.StatusUnprocessableEntity, body: `{"error":"quota_pool address not found"}`, wantErr: true}, + {name: "someone else's address", status: http.StatusConflict, body: `{"error":"address already exists outside that quota pool"}`, wantErr: true, wantTaken: true}, {name: "unavailable", status: http.StatusServiceUnavailable, wantErr: true}, } { t.Run(tc.name, func(t *testing.T) { @@ -102,6 +105,9 @@ func TestRegisterLinkedFmsgIDResponses(t *testing.T) { if (err != nil) != tc.wantErr || reinstated != tc.wantReinstated { t.Fatalf("reinstated=%v, err=%v; want reinstated=%v, error=%v", reinstated, err, tc.wantReinstated, tc.wantErr) } + if errors.Is(err, ErrLinkedAddressTaken) != tc.wantTaken { + t.Fatalf("err=%v, want ErrLinkedAddressTaken %v", err, tc.wantTaken) + } }) } } diff --git a/internal/middleware/jwt.go b/internal/middleware/jwt.go index c7d08f1..467d55c 100644 --- a/internal/middleware/jwt.go +++ b/internal/middleware/jwt.go @@ -524,6 +524,9 @@ type fmsgIDAddressReq struct { Address string `json:"address"` AcceptingNew *bool `json:"accepting_new,omitempty"` QuotaPool string `json:"quota_pool,omitempty"` + // Claim asks fmsgid to register the address only when it is new or + // already in QuotaPool, and to answer 409 otherwise. + Claim bool `json:"claim,omitempty"` } // fmsgIDAddressResp is fmsgid's answer to POST /fmsgid. fmsgid versions that @@ -533,19 +536,27 @@ type fmsgIDAddressResp struct { Reinstated bool `json:"reinstated"` } +// ErrLinkedAddressTaken is returned by RegisterLinkedFmsgID when the derived +// address already exists in fmsgid outside the owner's quota pool: someone +// else holds it. +var ErrLinkedAddressTaken = errors.New("derived address is already someone else's") + // errFmsgIDNoAcceptingNew is returned when fmsgid answers POST /fmsgid without // a body, i.e. it is a version that ignores accepting_new. var errFmsgIDNoAcceptingNew = errors.New("fmsgid does not support accepting_new on POST /fmsgid; upgrade fmsgid") // RegisterLinkedFmsgID registers a linked address — a derived sub-account // address such as @alice_bot@example.com — with fmsgid, idempotently, in its -// owner's quota pool and accepting new messages. Only its owner can derive a -// linked address, so one that already exists there was this owner's before: -// it is reinstated, with its earlier messages, and reinstated reports whether -// it had stopped accepting new messages (e.g. its grant was deleted). +// owner's quota pool and accepting new messages. The name alone doesn't prove +// the address is the owner's: an identity provider may let someone else hold +// @alice_bot@example.com. So it is claimed (fmsgid's claim): a new address is +// created in the pool, one already in the owner's pool is reinstated, with +// its earlier messages, and any other existing address is refused with +// ErrLinkedAddressTaken. reinstated reports whether it had stopped accepting +// new messages (e.g. its grant was deleted). func RegisterLinkedFmsgID(idURL, addr, owner string) (reinstated bool, err error) { accepting := true - resp, err := postFmsgIDAddress(idURL, fmsgIDAddressReq{Address: addr, AcceptingNew: &accepting, QuotaPool: owner}) + resp, err := postFmsgIDAddress(idURL, fmsgIDAddressReq{Address: addr, AcceptingNew: &accepting, QuotaPool: owner, Claim: true}) if err != nil { return false, err } @@ -585,6 +596,9 @@ func postFmsgIDAddress(idURL string, req fmsgIDAddressReq) (*fmsgIDAddressResp, // whatever fmsgid did, the cached lookup may now be stale fmsgIDCache.Delete(fmsgIDAddressURL(idURL, req.Address)) + if resp.StatusCode == http.StatusConflict && req.Claim { + return nil, ErrLinkedAddressTaken + } if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { return nil, fmt.Errorf("fmsgid registration failed: status %d", resp.StatusCode) }