Extending hookinlet

The hookinlet program is a thin set of parts. Each part sits behind an interface in pkg/inbox. server.New takes the parts as options. An application can replace any part, or add behaviour around it, without forking. The hosted product is built this way too. It changes nothing here and supplies its own implementations. You can do the same.

The packages are pre-1.0. The interfaces can still change, and CHANGELOG.md lists every change. After 1.0.0, semantic versioning applies.

The parts#

Interface (pkg/inbox) What it does Default Conformance suite (pkg/inboxtest)
Store Persists inboxes and messages; assigns each message its per-inbox Seq. pkg/store/sqlite StoreSuite
Notifier Tells readers an inbox may have new messages. Carries no payload. pkg/notify/local (in process) NotifierSuite
Authenticator, Principal Says who a request is and what it may read or administer. pkg/auth/token AuthenticatorSuite
SecretBox Seals and opens verifier secrets, bound to a context. Seal a verifier secret with inbox.VerifierSecretContext(inbox.UID), or the server cannot open it. pkg/secretbox SecretBoxSuite
ContextSecretBox (optional, of SecretBox) SealContext and OpenContext: Seal and Open given the context of the work, so a box that asks a key service can stop when it is cancelled or past its deadline, read what the embedder put on it, and see the inbox's tenant (inbox.TenantFrom). The server calls them in place of Seal and Open. See Writing a SecretBox. pkg/secretbox (which ignores the context) SecretBoxSuite, and ContextSecretBoxSuite for a box that does I/O
Hooks Runs before and after ingest: reject a delivery, count it. inbox.NopHooks none: the default does nothing
Admitter (optional, of Hooks) Asked before every read, stream and MCP wait, with the caller, the inbox and an AccessKind; may refuse (ErrRateLimited 429, ErrQuotaExceeded 402, ErrForbidden 403) or return a release function, called when the access ends. none: without it everything is admitted AdmitterSuite
Backupper (optional) A consistent snapshot of the Store, for GET /v1/admin/backup; the size may be -1 if the Store streams it. A Store that holds several tenants refuses a tenant-scoped context. the SQLite store BackupperSuite
TokenUseRecorder (optional) TouchToken(ctx, id, at) records when a token was last used, shown as Token.LastUsedAt and in the admin API's last_used_at. The default Authenticator calls it at most once per token per interval (five minutes), in the background, with a context of its own, and ignores its failure, so it may be slow or refuse under load. The time only moves forward; an unknown token is ErrNotFound. the SQLite store StoreSuite (the TokenLastUsed case, skipped without the interface)
EpochRenewer (optional) RenewEpochs(ctx) gives every inbox a new epoch and changes nothing else, for a Store restored by means that are not part of the interface (a copied database file, a point-in-time recovery). The server does not call it; a restore procedure does. See A restore is a new epoch. the SQLite store (hookinlet renew-epochs runs it) EpochRenewerSuite
BodyScreener (optional, of Hooks) Shown the body of every delivery that is about to be stored, after it verified, and may refuse it (the errors BeforeIngest may return) or store something else in its place, for redaction or schema checks. A replaced message is marked modified. See Redacting or checking a body. none: bodies are stored as received BodyScreenerSuite (it returns at once, leaves the body it is given alone, and survives concurrent calls; what it refuses or replaces is your own tests, and the server's tests cover what is done with the answer)
UnverifiedLimiter (optional, of Hooks) Says, per inbox, how many unverified messages it may keep, in place of Options.MaxUnverified: a positive number is the cap, 0 the server's limit, a negative number no cap. For caps that depend on something the server does not know, such as a plan. Needs a Store with UnverifiedCounter. none: every inbox gets the server's limit UnverifiedLimiterSuite (it returns at once and leaves the inbox alone; the cap itself is the server's tests)
IngestObserver (optional, of Hooks) Told how every delivery to a known inbox ended (IngestEvent: the inbox, an IngestOutcome such as stored or verification_failed, the status, size, source address, the host it was addressed to, for a stored message its Seq and whether it is verified, and for a failed signature a VerifyFailure kind), including refused and failed ones that AfterIngest never sees. For counts, audit or logs per inbox or tenant. See Observing how deliveries end. none: nothing is observed IngestObserverSuite (it returns at once for every outcome and leaves the event alone; what the server reports is the server's tests)
UnverifiedCounter (optional) How many unverified messages an inbox holds (bounded by a limit), so the server can cap them (Options.MaxUnverified). Without it the server does not cap, and says so when it starts. the SQLite store UnverifiedCounterSuite
ReaderTracker (optional) Remembers how far each named reader of an inbox has read, so the lag can be shown (PUT, GET and DELETE on /v1/inboxes/{slug}/readers, see api): AckReader sets a position for (inbox, name) in the inbox's current epoch, within a cap given per call (Options.MaxReadersPerInbox), Readers lists them, ForgetReader deletes one. A position is set only by an explicit acknowledgement, never by a read, and belongs to one epoch: the Store drops every position when an inbox's epoch changes (RenewEpochs, and the epochs a Backupper snapshot is given) and deletes an inbox's with the inbox. Without it the three operations answer 400 unsupported. the SQLite store ReaderTrackerSuite
StatusReporter (optional) The schema version, the size of the data and the free space, for GET /v1/admin/status and the console. the SQLite store none
Challenger (optional, of the error Authenticate returns) WWWAuthenticate() string: the WWW-Authenticate value for the 401, in place of Bearer realm="hookinlet". See Choosing the 401 challenge. none: the server sends its own ChallengerSuite (the value is one the server sends; the rest is the server's tests)
Unrouted (optional, of the error Authenticate returns) UnroutedHost() bool: when true, the server answers 404 in place of 401, for a request for a host that serves no org. See Answering 404 for a host that serves no org. none: the server answers 401 AuthenticatorSuite (AuthFixture.UnroutedHost; the rest is the server's tests)
ScopedPrincipal (optional) A Principal that can read a known list of inboxes, so listing does not have to search. InboxIDs(ctx) may look the list up, and may fail. the agent principal checked by AuthenticatorSuite
TenantPrincipal (optional) A Principal that belongs to one tenant. After authenticating, the server scopes the request's context to it (inbox.WithTenant), so slugs are looked up in that tenant and nothing outside it is reachable. See Tenants. none: the shipped principals are not in a tenant StoreSuite (the Tenants case) for the Store, and servertest.ServerSuite for what the server scopes
verify.Registry Maps verifier names to signature checks. verify.Default() the package's own tests

The server finds the optional parts with a type assertion. It copes when they are missing:

The server's own limits (MaxConcurrentReads, MaxStreams, MaxStreamsPerInbox) apply after Admit, whatever it says.

/readyz opens a sample of the stored verifier secrets. This catches a master key that is not the one the data was sealed under. It answers 503 only if none of the secrets opens.

Suppose a SecretBox keeps a key per tenant, and one tenant's key is gone. The server logs it, with the tenant, how many of its secrets did not open, and a few slugs. The server stays in rotation for the other tenants, as long as another tenant has a secret among the inboxes the check looks at. With many tenants, the oldest inboxes get the places. If every inbox with a secret belongs to one tenant, the server cannot tell that tenant's lost key from a wrong master key. It answers 503 for both.

A SecretBox whose opens are expensive, such as one that asks a key service, can turn the check off with Options.SkipReadinessSecretCheck and report its own health. If the sample takes more than 20 seconds, /readyz answers 503 and says that checking the secrets timed out. It checks again after 5 seconds.

Server.CheckSecrets runs in the hookinlet program before it listens. It always opens every secret of every tenant, and it fails if any one does not open.

GET /metrics is part of the admin API and needs the admin token. To serve the same series elsewhere, for an operator's scraper and without the admin API on that address, mount Server.MetricsHandler() on a listener or a route of your own. It does no authentication. You must protect the place you mount it.

Tenants#

A Store may hold the inboxes of several independent parties. Each has its own tenant key (Inbox.Tenant, an opaque string, empty by default). A hosted service uses this to keep its customers' inboxes apart on one server. If you never use tenants, you have one tenant, the empty one, and see no difference.

Putting them together#

server.New takes an Options. Only Store is required (and Addr, if you call Run). The read API, the admin API, SSE and MCP are served only when there is an Authenticator, because there is no safe default for who may read.

store, err := sqlite.Open(ctx, "./data", sqlite.WithExclusiveLock()) // or your own inbox.Store; the lock also lets it migrate
box, err := secretbox.New(masterKey)            // 32 bytes

srv, err := server.New(server.Options{
	Addr:          ":8080",
	Store:         store,
	SecretBox:     box,
	Notifier:      local.New(),
	Authenticator: token.NewAuthenticator(store, adminToken),
	Hooks:         myHooks,                     // optional
})
err = srv.Run(ctx)                              // returns after a clean shutdown

examples/custom-hooks is a complete program built this way. It has a per-inbox rate limit as the hook. It has an IngestObserver that counts, per inbox, how deliveries ended. It has a BodyScreener that redacts chosen JSON keys. CI compiles and tests it. Copy it as a starting point. Options has the rest (limits, timeouts, TrustedProxies, PublicBaseURL, a Verifiers registry). Each field says what it does and what its default is.

srv.Handler() returns the whole http.Handler. Use it if you would rather mount it in a server of your own than call Run (no Addr is needed then). Run and Serve do two things the handler alone does not. They start the retention schedule. On shutdown, they end open streams and MCP waits first. If you serve the handler yourself, run srv.Maintain(ctx) in a goroutine for the schedule. It also finishes any delete that was cut short. Call srv.Shutdown(ctx) to end the streams.

Every numeric and duration option follows one rule. It is written in Options' comment and in Stability. Zero is the default. A negative number is an error, unless it turns a bound off (RetentionInterval, IngestMemoryBudget).

Writing hooks#

Hooks has two methods. Embed inbox.NopHooks to implement only one.

type limiter struct{ inbox.NopHooks }

func (limiter) BeforeIngest(ctx context.Context, req *inbox.IngestRequest) error {
	if tooMany(req.Inbox, req.SourceIP) {
		return fmt.Errorf("%w: slow down", inbox.ErrRateLimited) // 429
	}
	return nil
}

BeforeIngest gets an *inbox.IngestRequest. It holds the inbox, the body size, the source address (as recorded, honoring trusted proxies), the host the delivery was addressed to (see below), the method, the path after the inbox key, and the request headers (read-only). It runs after the server finds the inbox and reads the body, and before it checks the signature. A refusal is cheap. There is a cost to weigh. The hook also sees unverified requests. If a limit counts every request, anyone who knows an inbox's URL can use up its allowance with unsigned posts. The real sender, which may not retry, is then refused. You have three choices. Limit by something a stranger cannot spend, such as the source address of unverified traffic. Or meter what was accepted, in AfterIngest. Or accept the trade-off knowingly, as the example does to keep it short. To refuse, return an error that wraps ErrRateLimited (429), ErrQuotaExceeded (402), or ErrForbidden (403). Wrap ErrNotFound to answer 404 (see below). Any other error is a 500. So if a lookup of your own returns an error that wraps ErrNotFound, that is now a 404, not a 500. The server calls the hook concurrently, from every request.

Which host a delivery arrived on#

req.Host is the Host header of the request as the server received it. It is in lower case, with any trailing dot removed from the name. It has a port only if the header had one: hooks.example.com, hooks.example.com:8443, [::1]:8080. It is empty if the request sent no Host. The server never reads X-Forwarded-Host, Forwarded and the like, because anyone can send them. If a proxy in front of the server rewrites Host, req.Host is what the proxy sent. The embedder must have the proxy pass the original on. The sender chooses the value. Compare it with the hostnames you serve. Do not use it unchecked as a key, a label or a file name.

An embedder that serves several hostnames can use it to answer only for the right one. If an inbox exists but is not served on the host the delivery arrived on, return ErrNotFound:

func (h hosts) BeforeIngest(ctx context.Context, req *inbox.IngestRequest) error {
	if !h.serves(req.Inbox, req.Host) {
		return inbox.ErrNotFound // 404, the same as an unknown ingest key
	}
	return nil
}

The server then answers just as it does for an ingest key that names no inbox. The status, headers (apart from the request id) and body are the same. There is no Retry-After, and no log line above debug level. The hook runs after the server reads the body, so the sender sees the same answer but not in the same time. Also, IngestObserver is told about it as not_found, which an unknown key is not. AfterIngest has no host, because its arguments are fixed. IngestEvent.Host carries the host to an observer.

AfterIngest runs after the message is committed, or recognized as a duplicate (created == false, so a meter does not count it twice). It must not block. Its context may be cancelled as soon as the response is sent, so work that outlives the call needs context.WithoutCancel. The server logs a panic in it and swallows it. The delivery is already stored, and the sender must not be told it failed.

Admitting reads, streams and waits#

Hooks covers ingest. To limit what a caller may read, also implement inbox.Admitter on the same value. The server finds it with a type assertion, so Hooks itself does not change.

func (l *limiter) Admit(ctx context.Context, p inbox.Principal, in *inbox.Inbox, kind inbox.AccessKind) (func(), error) {
	if !l.take(p, kind) {
		return nil, fmt.Errorf("%w: too many %ss", inbox.ErrQuotaExceeded, kind) // 402
	}
	return func() { l.give(p, kind) }, nil
}

Admit runs once per access. It runs after the caller is authenticated and may read the inbox, and before the access takes a slot of the server's own, so a refusal costs nothing. kind is one of three values. AccessRead is a read that answers at once. This includes the MCP query, get and list tools and a wait with a timeout of zero. (in is nil for the list tool.) AccessStream is an SSE stream. AccessWait is an MCP wait. To refuse, return an error that wraps ErrRateLimited (429), ErrQuotaExceeded (402) or ErrForbidden (403). Over MCP the agent is told the same in words. Any other error is a 500. The release function may be nil. The server calls it once, when the access ends. For a read, that is when the answer has been written, or, for a read that is not held that long, when the handler returns. For a stream or wait, it is when the stream or wait ends. The server's own limits apply after Admit, whatever it answers. inboxtest.AdmitterSuite checks an implementation.

Saying when to retry#

A refusal from BeforeIngest or Admit can say when to come back: wrap it with inbox.RefuseAfter(err, d), or return your own error type with a RetryAfter() time.Duration method (inbox.RetryAfterer, found with errors.As).

return nil, inbox.RefuseAfter(fmt.Errorf("%w: plan limit", inbox.ErrRateLimited), 90*time.Second)

The 429, 402 or 403 then carries Retry-After in whole seconds, rounded up, at least 1 and at most 86400 (a day). A duration that is not positive sends no header. Neither does an error that is not one of the three refusals. Over MCP the tool error says it instead, as rate_limited: too many requests; retry after 90 s. Neither the HTTP answer nor the tool error carries your error's text.

Which request a hook is called for#

inbox.AccessFrom(ctx) tells Admit, BeforeIngest, AfterIngest, ObserveIngest and MaxUnverified which request they are called for. Use it for an audit trail. An Authenticator reads it from r.Context(), because the server attaches it before it calls Authenticate:

For Authenticate, Operation is empty for the 405 the server sends when a path does not take the method. It is mcp for the HTTP request that carries MCP tool calls, because the server checks the credential before it knows the tool. When the server rechecks a stream or an MCP wait, it sees that stream's operation, or mcp. and the tool's name.

AccessFrom reports false outside a request. inbox.WithAccess makes a context that carries one, for testing a hook.

Redacting or checking a body#

BeforeIngest runs before a delivery is verified, so it cannot trust what it sees. AfterIngest runs after the message is committed, so it cannot change it. To refuse a verified delivery for what is in it, or to store it with something removed, also implement inbox.BodyScreener on the same value:

func (r redactor) ScreenBody(ctx context.Context, req *inbox.BodyScreenRequest) (inbox.BodyDecision, error) {
	if !validAgainstSchema(req.Inbox, req.Body) {
		return inbox.BodyDecision{}, fmt.Errorf("%w: not a valid order", inbox.ErrForbidden) // 403
	}
	if clean, changed := redact(req.Body); changed {
		return inbox.BodyDecision{Replace: true, Body: clean}, nil
	}
	return inbox.BodyDecision{}, nil // keep it as received
}

It runs after verification and before the message is stored. It also runs after the handshake step, so a Slack url_verification is answered as before and never shown to it. The server asks it about a delivery that verified. It also asks about one that is kept unverified (on_verify_fail=store, or an inbox whose verifier is none). req.Verified says which. Three kinds of delivery never reach it: one refused for its signature, a handshake, and one that BeforeIngest refused. The server also asks it about a repeat of a delivery already stored, because only the Store can tell a repeat. So you pay for its work on redeliveries too. The server calls it concurrently, from every request.

It answers in one of three ways:

What a replacement changes. The signature covered the bytes that were received, so you cannot check it against the stored body. The stored message is marked modified (Message.Modified). It shows as modified: true in the read API, on the stream and in the MCP tools, and is absent otherwise. Its verified stays true, because the sender did send it and the signature did match. GET .../raw returns the stored, replaced bytes. Code that re-verifies stored messages, or replays them to a downstream service with the original signature headers, must skip messages with modified. If you use a BodyScreener, a Store you write must keep NewMessage.Modified and return it as Message.Modified. StoreSuite checks this, and skips the case for a Store that does not keep the field.

Which body each part uses.

Part Uses
Signature verification The body received.
MaxBodyBytes, enforced when the body is read The body received. The replacement is held to the same limit.
The ingest memory budget (IngestMemoryBudget) The bytes received, as they arrive. A replacement is held beside the original until the delivery ends, so its bytes are counted too; if the budget has no room, the sender gets the 503 it would for a body, and should retry.
The deduplication key The body received, so a repeat collapses into the earlier message whatever the screener makes of it, even a screener that gives a different replacement each time.
event_type_pointer The body that is stored, so an event type never holds something the screener took out.
The stored size (size), the stored bytes, raw The body that is stored.
IngestEvent.Size and the size in the delivery's log line The bytes received.

Time and failure. ScreenBody runs on the request's goroutine and must not block, just as BeforeIngest and AfterIngest must not. The sender waits for it, and senders give up on a slow endpoint. Give a call to a service of your own a short deadline. Decide what happens when it fails: an error is a 500, and the sender retries. The server logs a panic in it, naming only the type of the value because the value may hold the body. It answers 500 and stores nothing. This differs from a panic in ObserveIngest, which the server swallows because the outcome is already decided. A screener that redacts must not fail open and store the unredacted body. The server gives the screener the body without a copy. The screener must not modify it. If it edits the body in place and says to keep it, the server refuses with a 500, because what is stored would no longer be what verified. Return a replacement instead.

Wrapping hooks hides it. Suppose a wrapper embeds the inbox.Hooks interface. It hides every optional interface of the value inside, BodyScreener included. The server then stores every body as received, and nothing in the log says a screener was skipped. Embed the concrete type, or forward ScreenBody with a method of your own. Test through the wrapper that a body is redacted. examples/custom-hooks has a Redactor that does this (set EXAMPLE_REDACT_KEYS=card,email).

Refusing has a cost. Many senders retry a delivery that got a 4xx or 5xx. Some disable an endpoint after repeated failures. If you refuse on content, a payload that does not fit your schema can cause a retry storm, or a webhook that stops sending at all. A 5xx from a failing screener does the same for every delivery. Where you can, accept the delivery and replace what you cannot keep, or note it in your own records (from AfterIngest). Refuse only what you must never hold. A refusal with RefuseAfter tells a well-behaved sender when to come back.

Observing how deliveries end#

AfterIngest sees only deliveries that were stored or recognised as duplicates. /metrics counts outcomes only in total. To see every outcome per inbox (for your own metrics, an audit trail or logs), also implement inbox.IngestObserver on the same value:

func (c *counter) ObserveIngest(ctx context.Context, ev *inbox.IngestEvent) {
	c.add(ev.Inbox.Tenant, ev.Inbox.Slug, ev.Outcome) // take a lock, add one; nothing slow
}

The server calls it once per delivery to a known inbox. The call comes after the outcome is decided (and after AfterIngest, for a stored message or a duplicate) and before the response is written. It runs on the request's goroutine and must not block, because the sender waits for it. Its context may already be cancelled, so work that outlives the call needs context.WithoutCancel. The server logs a panic in it and swallows it. The response does not change.

ev.Outcome is one of the inbox.Ingest* constants: stored, duplicate, handshake, verification_failed, rate_limited, quota_exceeded and forbidden (refused by BeforeIngest), body_refused (refused by a BodyScreener, with the status it answered), unverified_limit, storage_full, overloaded, too_large, bad_request, not_found (the inbox is disabled, was deleted while the delivery was received, or BeforeIngest answered ErrNotFound; a BodyScreener that does is body_refused) and error. More may be added, so treat one you do not know as a refusal. The event carries the Host the delivery was addressed to, as in IngestRequest. It never carries headers, the body, or the reason text of a signature failure. The server logs that text. So nothing you do with the event can leak them.

When Outcome is verification_failed, ev.VerifyFailure says which kind of failure it was, so an observer can tell a sender that sends no signature from one whose signature is wrong:

VerifyFailure Meaning
missing A header the verifier needs was not sent.
malformed A header was sent but could not be read as what the verifier expects: wrong prefix or encoding, a bad timestamp, or the header sent more than once.
mismatch The signature or token was well formed and did not match.
stale The signature matched, but its timestamp was outside the tolerance window. The signature is checked first, so a forged delivery is mismatch, never stale.

The field is empty for every other outcome. It is also empty for a failure from a custom verifier that does not classify its failures (a verify.Failure with an empty Kind). The server does not pass on a kind that a custom verifier makes up.

The observer does not see a delivery whose ingest key names no inbox, or one with the wrong method. There is no inbox to count it against, and the observer would otherwise see every guess anyone makes at a key.

Checking a hook of your own#

The server's own tests cover what it does with a hook's answers. Four suites check, without a server, what holds for every implementation of a hook:

inboxtest.UnverifiedLimiterSuite(t, func(t *testing.T) inbox.UnverifiedLimiter { return newLimiter(t) })
inboxtest.IngestObserverSuite(t, func(t *testing.T) inbox.IngestObserver { return newObserver(t) })
inboxtest.AdmitterSuite(t, func(t *testing.T) inbox.Admitter { return newAdmitter(t) })
inboxtest.BodyScreenerSuite(t, func(t *testing.T) inbox.BodyScreener { return newScreener(t) })

UnverifiedLimiterSuite and IngestObserverSuite call the hook with an ordinary context, with one that carries inbox.AccessFrom, and with one that is already cancelled. They check three things. The hook returns at once, because the server calls both on the request's goroutine. It does not change the inbox or the event it is given. It survives being called from many requests together. The suite calls the observer with an event of every inbox.Ingest* outcome, and with one the package does not know yet. Your own tests must check which cap a limiter answers for which inbox, and what an observer counts. AdmitterSuite is described above. BodyScreenerSuite calls ScreenBody with bodies of every kind (empty, binary, large, JSON), for an inbox that verified and one that did not. It checks that the screener returns at once, does not change the body or the inbox it is given, does not answer with a replacement over the inbox's MaxBodyBytes, and survives concurrent calls. Your own tests must check what it refuses and what it replaces.

No suite can reach some contract points, because they are about what the server does. Check them in your own tests:

Checking what the server does with tenants#

Four behaviours belong to the server, not to one interface. They are part of the contract:

servertest.ServerSuite builds a real server over your Store and Authenticator and sends it requests, so you can check these where you embed it. It lives in the package github.com/hookinlet/hookinlet/pkg/server/servertest. That package is separate from inboxtest because the server's own tests import inboxtest.

func TestMyServer(t *testing.T) {
	servertest.ServerSuite(t, servertest.Harness{
		NewStore: func(t *testing.T, now func() time.Time) inbox.Store { return openMyStore(t, now) },
		PrepareTenant: func(t *testing.T, s inbox.Store, tenant string) { registerTenant(t, s, tenant) }, // or nil
		NewAuthenticator: func(t *testing.T, s inbox.Store) (inbox.Authenticator, servertest.Callers) {
			return myAuthenticator(s), servertest.Callers{
				ReaderA:  bearer(tokenFor(t, s, "org-a")), // a TenantPrincipal of org-a that reads its inboxes
				ReaderB:  bearer(tokenFor(t, s, "org-b")),
				AdminA:   bearer(adminTokenFor(t, s, "org-a")), // optional
				Operator: bearer(operatorToken(t, s)),          // an admin in no tenant
				NoTenant: bearer(carelessToken(t, s)),          // optional: reads everything, in no tenant, not an admin
			}
		},
	})
}

The suite makes inboxes in org-a, org-b and the default tenant. It calls PrepareTenant for the first two, as StoreSuite does. It then calls NewAuthenticator and starts the server. ReaderA and ReaderB must be TenantPrincipals of those tenants. They read every inbox in their tenant and cannot admin. The Operator is an admin that reads every inbox and is in no tenant. AdminA and NoTenant are optional, and the cases that need them are skipped without them. The groups are Tenants, RequireTenant, Readiness and Fallback. Readiness seals secrets with the SecretBox from Harness.NewSecretBox, or the secretbox package's, and makes one tenant's fail to open. The suite is a separate function, so an Authenticator or Store that passes its own suites does not start failing on upgrade.

Writing a Store#

The Store documentation in pkg/inbox/interfaces.go is the contract. The suite lets you test it. These points are easy to get wrong:

Run the suite from an ordinary test:

func TestMyStore(t *testing.T) {
	inboxtest.StoreSuite(t, func(t *testing.T, now func() time.Time) inbox.Store {
		return openMyStore(t, now) // must use now for every timestamp it assigns
	})
}

The suite closes each Store itself. Three things need something only your test can do. You give them as a StoreOptions after newStore (inboxtest.StoreSuite(t, newStore, inboxtest.StoreOptions{...}), or the same call as inboxtest.StoreSuiteWith):

Add the suites that match what your Store can do:

Token expiry and last use. An inbox.Token may have an ExpiresAt and a LastUsedAt. A Store that keeps ExpiresAt has three duties:

The default Authenticator checks the expiry again. So a Store that does not enforce it is still safe with that Authenticator, but a different one would be wrong. A Store that does not keep ExpiresAt at all returns the token without one, and the TokenExpiry case is skipped. The admin API still accepts an expires_at for it, but the value has no effect. If your Store cannot keep it, tell the people who run it. LastUsedAt is optional. It comes with inbox.TokenUseRecorder, whose case skips without it.

Wrapping a Store#

To add something around a Store (tenancy, a quota, a byte count per tenant), wrap it in a type of your own and give the server the wrapper. Besides the 19 methods of inbox.Store, the server looks for four optional interfaces on the Store it is given. It uses a type assertion, and does without each one it does not find. The default Authenticator finds inbox.TokenUseRecorder the same way. A sixth, inbox.EpochRenewer, is not looked for by the server. A restore procedure of your own looks for it:

Optional interface Without it
inbox.UnverifiedCounter Unverified messages are not capped: Options.MaxUnverified and an UnverifiedLimiter on your Hooks have no effect. Every delivery stored unverified (with on_verify_fail=store, or the verifier none) is accepted with 200. The only sign is a warning in the log when the server starts.
inbox.Backupper GET /v1/admin/backup answers 501 not_implemented, and hookinlet backup says the store does not support backups.
inbox.ReaderTracker The named-reader operations (GET, PUT and DELETE on /v1/inboxes/{slug}/readers) answer 400 unsupported, and no consumer lag is shown. Nothing is stored and nothing breaks: a reader still keeps its own cursor.
inbox.StatusReporter GET /v1/admin/status reports schema_version and database_bytes as 0 and leaves out free_bytes.
inbox.TokenUseRecorder No token's last use is recorded: Token.LastUsedAt stays unset and the admin API leaves out last_used_at. Nothing fails.
inbox.EpochRenewer Nothing in the server. Your restore procedure, which asserts the Store it holds to EpochRenewer, finds no way to renew the epochs and cannot tell readers holding old cursors to start again.

The core grows by adding optional interfaces like these (Stability), so a later release may add to this table.

There are two easy ways to get a wrapper wrong:

Embed the interface for the methods you do not change. Forward each optional interface explicitly, and apply the wrapper's own logic where it applies:

type metered struct {
	inbox.Store // the methods this wrapper does not change
	meter       *Meter
}

func (s *metered) Append(ctx context.Context, id inbox.ID, m *inbox.NewMessage) (*inbox.Message, bool, error) {
	msg, created, err := s.Store.Append(ctx, id, m)
	if err == nil && created {
		s.meter.Add(ctx, id, msg.Size) // best effort: see "Counting, copying and forwarding messages"
	}
	return msg, created, err
}

// The optional interfaces of the store inside, forwarded one by one.
func (s *metered) CountUnverified(ctx context.Context, id inbox.ID, limit int64) (int64, error) {
	return s.Store.(inbox.UnverifiedCounter).CountUnverified(ctx, id, limit)
}

func (s *metered) Backup(ctx context.Context) (io.ReadCloser, int64, error) {
	return s.Store.(inbox.Backupper).Backup(ctx)
}

func (s *metered) Status(ctx context.Context) (inbox.StoreStatus, error) {
	return s.Store.(inbox.StatusReporter).Status(ctx)
}

func (s *metered) RenewEpochs(ctx context.Context) error {
	return s.Store.(inbox.EpochRenewer).RenewEpochs(ctx)
}

func (s *metered) AckReader(ctx context.Context, id inbox.ID, name, epoch string, seq int64, maxReaders int) (inbox.ReaderPosition, error) {
	return s.Store.(inbox.ReaderTracker).AckReader(ctx, id, name, epoch, seq, maxReaders)
}

func (s *metered) Readers(ctx context.Context, id inbox.ID) ([]inbox.ReaderPosition, error) {
	return s.Store.(inbox.ReaderTracker).Readers(ctx, id)
}

func (s *metered) ForgetReader(ctx context.Context, id inbox.ID, name string) error {
	return s.Store.(inbox.ReaderTracker).ForgetReader(ctx, id, name)
}

Forward only the interfaces the inner store has. A method that exists but cannot work is worse than none, because the server would call it instead of doing without.

inboxtest.AssertStoreWrapperForwards(t, wrapper, inner) checks a wrapper. It fails if the wrapper lacks an optional interface that the inner store implements. The failure names each missing interface and what the server does without it. Call it in a test of the wrapper, with the store it wraps in production. It checks that the methods exist, not what they do. A wrapper that embeds the concrete type passes it.

Counting, copying and forwarding messages#

Writing a Notifier#

A notifier carries no data. It says "look again", and the reader asks the Store. So replay, reconnects, and slow readers share one code path. A missed signal costs delay, never data.

func TestMyNotifier(t *testing.T) {
	inboxtest.NotifierSuite(t, func(t *testing.T) inbox.Notifier { return newMyNotifier(t) })
}

An in-process notifier must not drop signals. One that crosses the network may drop them (delivery at most once). If yours does, run the server with a positive HOOKINLET_SSE_RECHECK_INTERVAL (Options.SSERecheckInterval). That makes every stream and MCP wait re-read the Store on that interval regardless. The server calls Publish with a context that may already be cancelled, and Publish must still deliver.

CancellingReleasesEverythingItHeld counts goroutines before and after a thousand subscriptions are made and cancelled. A notifier that opens its backend connection the first time it is used therefore looks like a leak. Open the connection before the check (in the function that makes the notifier), or close it when the notifier is closed.

Readers subscribe first and read the Store second. So a subscription has to be live when Subscribe returns: every Publish that begins after that must reach it. A notifier that crosses the network waits for its backend to confirm the subscription before returning, but only briefly, because Subscribe must not block the caller. (For example, it waits for the reply to a pub/sub SUBSCRIBE.) If it returns before the confirmation, a signal published in between can be lost. This is the at-most-once delivery that the recheck interval covers. The reader sees the message on its next re-read.

Signals coalesce (merge into one) when they arrive before the subscriber reads. A notifier that crosses the network delivers a burst of publishes spread over time. A subscriber that reads the first at once sees the later ones as new signals, as it should. Run such a notifier with inboxtest.NotifierSuiteWith(t, newNotifier, inboxtest.NotifierOptions{Settle: d}). Here d is how long a burst of a thousand publishes takes to arrive. The coalescing check then waits that long before it reads, and still requires one signal.

The suite runs one notifier. Take a notifier whose instances reach each other through a backend. It can lose a wake-up between instances and still pass a suite that has only one. Give NotifierOptions.Peer a function that returns a second notifier on the same backend as the first. The suite then also checks three things. A Publish on either instance wakes the subscribers of both. Another inbox's subscribers are not woken. Cancelling a subscription on one instance leaves the other's alone. Left nil, the suite runs as before. The in-process notifier has one instance, so its test passes the notifier itself as its own peer.

Writing a SecretBox#

A SecretBox seals a verifier secret when an inbox is created or its secret is set. It opens the secret on every delivery to an inbox that has one, on each /readyz sample and in Server.CheckSecrets. The server does not cache what it opens. If your box asks a key service for a data key, the box should cache the key itself, for as long as it judges safe.

inboxtest.SecretBoxSuite(t, func(t *testing.T) inbox.SecretBox { return newMyBox(t) })

A box that does I/O should also implement inbox.ContextSecretBox. Its SealContext and OpenContext get the context of the work. The server then calls them instead of Seal and Open. They must give the same results. They must give up with an error that wraps ctx.Err() once the context ends.

The server always gives the box a context scoped (inbox.WithTenant) to the tenant of the inbox whose secret it is. So inbox.TenantFrom reports that tenant and scoped true, and a box that keeps a key per tenant can pick the right key. An inbox in the default tenant is scoped to "". That is not the same as not scoped: a box can tell the default tenant from a context that says nothing. The scoping is for the box only. The Store calls of the same work keep their own context. A delivery's are not scoped at all, because the server finds the inbox by its ingest key. The context is:

Code of your own that seals or opens with a box should call inbox.SealWith(ctx, box, …) and inbox.OpenWith(ctx, box, …). They pass the context to a box that takes one. To check that a box honours the context:

inboxtest.ContextSecretBoxSuite(t, func(t *testing.T) inbox.SecretBox { return newMyBox(t) })

Writing an Authenticator#

Authenticate runs on every request, before the server knows whether the caller may see anything. It must not reveal why it refused. Every failure looks the same and wraps inbox.ErrUnauthenticated. The server reads any other error to mean it could not check the credential, and answers 500. A Principal decides by inbox ID, never by slug or name. A credential for one inbox must not reveal whether another exists (the server answers 404 for both). One refusal may be a 404: the one for a host that serves no org. See Answering 404 for a host that serves no org.

inboxtest.AuthenticatorSuite(t, func(t *testing.T) inboxtest.AuthFixture { … })

If your credentials can expire, set AuthFixture.Expire. It makes one of the fixture's tokens expire. The suite then checks that the next call refuses it with the same error text as a token that never existed. A caller must not be able to tell the two apart. Left nil, that case is skipped.

Choosing the 401 challenge#

A 401 carries WWW-Authenticate: Bearer realm="hookinlet". Suppose the error your Authenticate returns (or any error it wraps, found with errors.As) also has a WWWAuthenticate() string method (inbox.Challenger). The server then sends that string instead. This applies to every 401 the server writes: the read API, the admin API, a stream, the MCP endpoint, and the 405 that checks the credential first.

A self-hoster who puts an OAuth server in front can use this to point clients to the discovery document:

type needsLogin struct{}

func (needsLogin) Error() string { return "unauthenticated" }
func (needsLogin) Unwrap() error { return inbox.ErrUnauthenticated }
func (needsLogin) WWWAuthenticate() string {
	return `Bearer resource_metadata="https://hooks.example.com/.well-known/oauth-protected-resource"`
}

(Serve that document with Options.Fallback.)

The server sends the string only if all of these hold:

The server does not parse the parameters. If the string fails any rule, the server sends Bearer realm="hookinlet" and logs a warning, once. The same string goes to every caller who is refused, so do not build it from the request's credentials. An error that does not wrap ErrUnauthenticated is still a server error, whatever else it has.

inboxtest.ChallengerSuite(t, func(t *testing.T) inbox.Challenger { return yourError }) checks the value against these rules. A mistake that would send the server's own challenge then shows up in your tests, not in a warning in the log. The suite also checks that the value is the same on every call, and that the error wraps ErrUnauthenticated.

Answering 404 for a host that serves no org#

An embedder may serve many parties from one process and tell them apart by the request's host. Some requests then arrive for hosts that serve nobody. A 401 is the wrong answer for those. It invites the caller to authenticate to something that does not exist. Suppose the error your Authenticate returns (or any error it wraps) also has an UnroutedHost() bool method (inbox.Unrouted) that returns true. The server then answers 404 instead. The body is the same as its other 404s ({"error":{"code":"not_found","message":"not found"}}), with no WWW-Authenticate header. This applies wherever the server would write a 401: the read API, the admin API, a stream, the MCP endpoint, and the 405 that checks the credential first.

type noSuchHost struct{}

func (noSuchHost) Error() string      { return "unauthenticated" }
func (noSuchHost) Unwrap() error      { return inbox.ErrUnauthenticated }
func (noSuchHost) UnroutedHost() bool { return true }

inboxtest.AuthenticatorSuite checks this when the fixture sets UnroutedHost (a host that serves no org). Every caller of that host, valid token included, gets no principal, ErrUnauthenticated, the same error text, and the same answer to Unrouted. The suite also checks, with or without that field, that a bad credential on any other host never asks for a 404. It checks that those refusals stay identical to each other.

Serving other paths next to the API#

Options.Fallback is an http.Handler that answers requests for paths the server has no route for, in place of the fixed 404. Use it when a self-hosted server also serves a file under /.well-known/, or a small static site, at the same address:

mux := http.NewServeMux()
mux.Handle("/.well-known/oauth-protected-resource", metadataDocument)
mux.Handle("/", http.FileServer(http.Dir("./public")))

srv, err := server.New(server.Options{ /* … */ Fallback: mux })

Adding a verifier#

reg := verify.Default()
err := reg.Register("acme-v2", func(config json.RawMessage) (verify.Verifier, error) { … })
srv, _ := server.New(server.Options{ /* … */ Verifiers: reg })

See verifiers for what a Verifier must do. It must check the exact bytes received. It must compare in constant time (the comparison takes the same time whatever the input). It must say which headers carry its credential, so the server does not store them.

Rules the server keeps, and expects of you#

From docs/extending.md at v0.11.1. Markdown · View on GitHub · Back to top