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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
33 changes: 33 additions & 0 deletions src/fmsgid.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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"`
Expand Down Expand Up @@ -196,13 +208,22 @@ 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
if errors.As(err, &qpErr) {
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
Expand Down Expand Up @@ -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(&current); 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 {
Expand Down
50 changes: 50 additions & 0 deletions src/pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions src/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -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);`

Expand Down
Loading