Skip to content
Merged
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
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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`
Expand Down
8 changes: 6 additions & 2 deletions internal/handlers/subaccounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"})
Expand Down
41 changes: 40 additions & 1 deletion internal/handlers/subaccounts_lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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) {
Expand Down
8 changes: 7 additions & 1 deletion internal/middleware/fmsgid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package middleware

import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -83,13 +84,15 @@ 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}`},
{name: "reinstated", status: http.StatusOK, body: `{"created":false,"reinstated":true}`, wantReinstated: true},
{name: "fmsgid without accepting_new", status: http.StatusOK, body: ""},
{name: "malformed", status: http.StatusOK, body: "<html>", 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) {
Expand All @@ -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)
}
})
}
}
Expand Down
24 changes: 19 additions & 5 deletions internal/middleware/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down Expand Up @@ -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)
}
Expand Down
Loading