diff --git a/README.md b/README.md index d5913fd..ec0e8d3 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ All routes are served over HTTPS under the `/fmsgid` path. | Method | Route | Description | |--------|-------|-------------| | `GET` | `/fmsgid/:address` | Lookup an fmsg address and return its details including display name, quotas, and usage. The address must be in fmsg format (`@user@example.com`). Returns `AddressDetail` JSON on success, `400` if the address is invalid, `404` if not found. For an address in a [quota pool](#quota-pools) the limits are the pool owner's, the usage is the whole pool's and `quotaPool` is the pool owner's address; `quotaPool` is omitted otherwise. `acceptingNew` is always the address's own. | -| `POST` | `/fmsgid` | Register an address, idempotently. Accepts a JSON body with `address` and optional `display_name`, `accepting_new` (bool) and `quota_pool` (an fmsg address, see [Quota pools](#quota-pools)). A new address takes the `address` table's column defaults in `dd.sql` except for `accepting_new` and `quota_pool` when given. An existing address is left as it is except for `accepting_new` and `quota_pool` when given (`display_name` and quotas are never changed — use CSV sync for those). Setting `accepting_new` `false` stops the address accepting new messages; setting it `true` again reinstates it. `quota_pool` `""` or the address itself takes the address out of any pool. Returns `201` if the address was created, `200` if it already existed, both with `{"created":bool,"reinstated":bool}` where `reinstated` is `true` when the address existed, wasn't accepting new messages and now is. Returns `400` if the body or an address is invalid, `422` with `{"error":"..."}` if `quota_pool` names an address that doesn't exist or is in another pool, or the address owns a pool itself. | +| `POST` | `/fmsgid` | Register an address, idempotently. Accepts a JSON body with `address` and optional `display_name`, `accepting_new` (bool) and `quota_pool` (an fmsg address, see [Quota pools](#quota-pools)). A new address takes the `address` table's column defaults in `dd.sql` except for `accepting_new` and `quota_pool` when given. An existing address is left as it is except for `accepting_new` and `quota_pool` when given (`display_name` and quotas are never changed — use CSV sync for those). Setting `accepting_new` `false` stops the address accepting new messages; setting it `true` again reinstates it. `quota_pool` `""` or the address itself takes the address out of any pool. With `claim` `true` (which needs `quota_pool`), the address is registered for that pool only: it is created in the pool, or used if it already exists in that pool; an existing address anywhere else is refused with `409` and left unchanged. A service that derives addresses from an owner's name, such as `@alice_bot@example.com` from `@alice@example.com`, should claim them, so it can't take over an address someone else already holds. Returns `201` if the address was created, `200` if it already existed, both with `{"created":bool,"reinstated":bool}` where `reinstated` is `true` when the address existed, wasn't accepting new messages and now is. Returns `400` if the body or an address is invalid, `422` with `{"error":"..."}` if `quota_pool` names an address that doesn't exist or is in another pool, or the address owns a pool itself, and `409` with `{"error":"..."}` when a claimed address exists outside that pool. | | `POST` | `/fmsgid/send` | Record a send transaction. Accepts an `AddressTx` JSON body with `address`, `ts` (timestamp), and `size`. The address is case folded, and every call is recorded, including several with the same timestamp. Returns `200`, or `400` if the body or address is invalid. | | `POST` | `/fmsgid/recv` | Record a receive transaction. Accepts an `AddressTx` JSON body with `address`, `ts` (timestamp), and `size`. The address is case folded, and every call is recorded, including several with the same timestamp. Returns `200`, or `400` if the body or address is invalid. | | `POST` | `/fmsgid/send/release` | Release a sent message's storage, when it is deleted for good. Same body and responses as `/fmsgid/send`. The size comes off `sendSizeTotal` (never below 0) but not off the daily send usage, so deleting messages doesn't raise a daily limit. | diff --git a/src/fmsgid.go b/src/fmsgid.go index 059b82c..e0be767 100644 --- a/src/fmsgid.go +++ b/src/fmsgid.go @@ -56,6 +56,12 @@ type CreateAddressReq struct { // address is new or already exists. "" or the address itself takes the // address out of any pool. When omitted quota_pool is left as it is. QuotaPool *string `json:"quota_pool"` + // Claim, with QuotaPool, registers the address for that pool only: it is + // created in the pool, or, when it already exists, used only if it is + // already in that pool. An existing address anywhere else is refused with + // claimError and nothing is changed, so a caller deriving an address from + // its owner's name can't take over an address someone else holds. + Claim bool `json:"claim"` } // CreateAddressResp is the result of POST /fmsgid. @@ -73,6 +79,12 @@ type quotaPoolError string func (e quotaPoolError) Error() string { return string(e) } +// claimError is a claim (CreateAddressReq.Claim) of an address that already +// exists outside the claimed pool. +type claimError string + +func (e claimError) Error() string { return string(e) } + type AddressDetail struct { Address string `json:"address"` DisplayName string `json:"displayName"` @@ -196,6 +208,10 @@ func postCreateAddress(c *gin.Context) { c.AbortWithStatus(http.StatusBadRequest) return } + if req.Claim && req.QuotaPool == nil { + c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "claim needs quota_pool"}) + return + } resp, err := registerAddress(ctx, req) var qpErr quotaPoolError @@ -203,6 +219,11 @@ func postCreateAddress(c *gin.Context) { c.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{"error": qpErr.Error()}) return } + var clErr claimError + if errors.As(err, &clErr) { + c.AbortWithStatusJSON(http.StatusConflict, gin.H{"error": clErr.Error()}) + return + } if err != nil { c.AbortWithError(500, err) return @@ -275,6 +296,18 @@ func registerAddress(ctx context.Context, req CreateAddressReq) (CreateAddressRe } resp.Created = tag.RowsAffected() == 1 + // a claimed address that already existed must already be in the pool + // (nil: its own pool) + if !resp.Created && req.Claim { + var current *string + if err := tx.QueryRow(ctx, sqlSelectQuotaPoolForUpdate, addrLower).Scan(¤t); err != nil { + return resp, err + } + if (current == nil) != (quotaPool == nil) || (current != nil && *current != *quotaPool) { + return resp, claimError("address already exists outside that quota pool") + } + } + if !resp.Created && (req.AcceptingNew != nil || req.QuotaPool != nil) { var wasAccepting bool if err := tx.QueryRow(ctx, sqlSelectAcceptingNewForUpdate, addrLower).Scan(&wasAccepting); err != nil { diff --git a/src/pool_test.go b/src/pool_test.go index fe24b2d..839227b 100644 --- a/src/pool_test.go +++ b/src/pool_test.go @@ -291,6 +291,56 @@ func TestPostCreateAddress_QuotaPool(t *testing.T) { http.StatusOK, CreateAddressResp{}) } +// TestPostCreateAddress_Claim checks that a claim registers an address only +// for its pool: new, or already in that pool. An address someone else holds, +// in no pool or another one, is refused and left unchanged. +func TestPostCreateAddress_Claim(t *testing.T) { + poolTestDB(t) + + postAddress(t, `{"address":"@alice@pooltest.example"}`, http.StatusCreated, CreateAddressResp{Created: true}) + postAddress(t, `{"address":"@carol@pooltest.example"}`, http.StatusCreated, CreateAddressResp{Created: true}) + + // a new address is created in the pool + postAddress(t, `{"address":"@alice_bot@pooltest.example","quota_pool":"@alice@pooltest.example","claim":true}`, + http.StatusCreated, CreateAddressResp{Created: true}) + if qp := quotaPoolOf(t, "@alice_bot@pooltest.example"); qp == nil || *qp != "@alice@pooltest.example" { + t.Fatalf("quota_pool %v, want @alice@pooltest.example", qp) + } + + // one already in the pool is used, and may be reinstated + postAddress(t, `{"address":"@alice_bot@pooltest.example","accepting_new":false}`, http.StatusOK, CreateAddressResp{}) + postAddress(t, `{"address":"@ALICE_BOT@pooltest.example","accepting_new":true,"quota_pool":"@Alice@pooltest.example","claim":true}`, + http.StatusOK, CreateAddressResp{Reinstated: true}) + + // someone else's address, in no pool: refused and unchanged + postAddress(t, `{"address":"@carol_bot@pooltest.example","accepting_new":false}`, http.StatusCreated, CreateAddressResp{Created: true}) + postAddress(t, `{"address":"@carol_bot@pooltest.example","accepting_new":true,"quota_pool":"@carol@pooltest.example","claim":true}`, + http.StatusConflict, CreateAddressResp{}) + if qp := quotaPoolOf(t, "@carol_bot@pooltest.example"); qp != nil { + t.Fatalf("refused claim set quota_pool %q", *qp) + } + if acceptingNewOf(t, "@carol_bot@pooltest.example") { + t.Fatal("refused claim reinstated the address") + } + + // an address in another pool: refused and unchanged + postAddress(t, `{"address":"@alice_bot@pooltest.example","quota_pool":"@carol@pooltest.example","claim":true}`, + http.StatusConflict, CreateAddressResp{}) + if qp := quotaPoolOf(t, "@alice_bot@pooltest.example"); qp == nil || *qp != "@alice@pooltest.example" { + t.Fatalf("refused claim moved the address to %v", qp) + } + + // claiming an address for its own pool (the address itself) needs it to + // be in no pool + postAddress(t, `{"address":"@carol@pooltest.example","quota_pool":"@carol@pooltest.example","claim":true}`, + http.StatusOK, CreateAddressResp{}) + postAddress(t, `{"address":"@alice_bot@pooltest.example","quota_pool":"","claim":true}`, + http.StatusConflict, CreateAddressResp{}) + + // a claim names a pool + postAddress(t, `{"address":"@dave@pooltest.example","claim":true}`, http.StatusBadRequest, CreateAddressResp{}) +} + // TestPostCreateAddress_AcceptingNew checks disabling and reinstating an // address through POST /fmsgid, and that the response says when an address // was reinstated. diff --git a/src/sql.go b/src/sql.go index 7ef907e..aa60e8d 100644 --- a/src/sql.go +++ b/src/sql.go @@ -56,6 +56,10 @@ const sqlSelectAcceptingNewForUpdate string = `select accepting_new from address // locking the row so it can't join another pool until the transaction ends. const sqlSelectQuotaPoolForShare string = `select quota_pool from address where address_lower = $1 for share;` +// sqlSelectQuotaPoolForUpdate reads an existing address's quota_pool, locking +// the row for the rest of the transaction. +const sqlSelectQuotaPoolForUpdate string = `select quota_pool from address where address_lower = $1 for update;` + // sqlIsPoolOwner reports whether any address is in the given address's pool. const sqlIsPoolOwner string = `select exists (select 1 from address where quota_pool = $1 and address_lower <> $1);`