hush/vendor/github.com/orchard9/go-chassis/chassis/idempotency.go
jx12n 4d9a26498e hush: one-time secret links the server cannot read
Paste a secret, get a link, send it. The first person to open it and press
Reveal sees the secret; the link dies at that moment. The recipient needs a
browser and nothing else — no account, no client, no installed tooling.

The server cannot read what it stores. AES-256-GCM happens in the browser and
the key lives in the URL fragment, which browsers never transmit, so hushd
holds ciphertext and no key material. That is a property of where the key sits
rather than a promise about our conduct, which is why there is deliberately no
endpoint accepting a plaintext secret and no server-side-encryption fallback:
two guarantees behind one URL would be worse than one honest guarantee.

Three decisions carry the design:

  * GET /s/{id} touches NO storage, not even to check existence. Slack, Teams,
    WhatsApp, iMessage and Outlook Safe Links all fetch a URL before a human
    sees it, so destroying on GET would destroy most secrets in transit and the
    recipient's "already used" would be indistinguishable from interception.
    Only POST /reveal consumes. Bot user-agent detection is an arms race;
    removing the side effect from GET is not. Pinned by
    TestGettingTheRevealPageNeverConsumesTheSecret.
  * Destruction is one Redis GETDEL, which is atomic. GET-then-DEL has a window
    where two simultaneous readers both win, and for a one-time secret that
    window is the product. The store contract demands atomicity and the same
    concurrency test runs against both implementations.
  * Missing, already-revealed, expired and evicted are ONE indistinguishable
    410. Separating them would confirm to a prober that a given link was real.

The secret id IS the capability, so secret.ID is a struct whose every
accidental path — %v, %s, String(), slog, json.Marshal — emits a redacted
handle or refuses, and the raw value needs an explicit Value(). The first
version tried to prevent leaks by implementing no String() at all; its own test
caught that Go's fmt prints unexported fields anyway, so forbidding the method
had removed the control rather than the leak.

Operationally: structured JSON on stdout in the fleet's wire format, which
Vector already collects with no annotation; six hush_* metrics on the chassis
registry with no id, IP or path in any label; five alert rules wired into
vmalert. The public Ingress enumerates /, /s/ and /api/ so /metrics, /healthz
and /readyz share the port but are unreachable from the internet — no
basic-auth middleware to maintain and get wrong.

Dependencies are vendored because go-chassis is private: the Woodpecker test
step and the in-cluster Kaniko build both run -mod=vendor with GOPROXY=off and
hold no git credential.

cmd/hush-mcp is a stdio MCP server doing the same client-side crypto locally,
so using hush from an agent preserves the same guarantee as using it from a
browser.
2026-09-03 00:08:38 -06:00

120 lines
3.6 KiB
Go

package chassis
import (
"bytes"
"context"
"net/http"
"time"
)
// StoredResponse is a cached successful response, replayed verbatim (status +
// headers + body) on a duplicate Idempotency-Key.
type StoredResponse struct {
Status int
Header http.Header
Body []byte
}
// IdempotencyStore persists and replays responses keyed by Idempotency-Key.
// Back it with Redis (TTL'd) in shared/adapters/redis. Lookup returns found=false
// when the key is new; Save records a successful response.
type IdempotencyStore interface {
Lookup(ctx context.Context, key string) (StoredResponse, bool, error)
Save(ctx context.Context, key string, resp StoredResponse, ttl time.Duration) error
}
// Idempotent dedups mutating requests by the Idempotency-Key header: a duplicate
// returns the original response without re-running the handler. Apply it to
// POST/PUT route groups. Requests without the header pass straight through. The
// key is scoped by the caller's org so keys can't collide across tenants. The
// store is best-effort: a backend error fails open (the request proceeds) rather
// than blocking writes.
func Idempotent(store IdempotencyStore, ttl time.Duration) Middleware {
return func(next HandlerFunc) HandlerFunc {
return func(c *Context) error {
key := c.r.Header.Get("Idempotency-Key")
if key == "" {
return next(c)
}
// Scope by tenant. With no resolved org we refuse to cache rather than
// share a global (cross-tenant) key — pair this with RequireOrg.
org := c.OrgID()
if org == "" {
c.Log().Warn("idempotency.skipped_no_org", "category", "idempotency")
return next(c)
}
scoped := org + ":" + key
ctx := c.r.Context()
if sr, found, err := store.Lookup(ctx, scoped); err != nil {
c.Log().Warn("idempotency.lookup_failed", "category", "idempotency", "error_msg", err.Error())
} else if found {
h := c.w.Header()
for k, vs := range sr.Header { // replay the original headers verbatim
for _, v := range vs {
h.Add(k, v)
}
}
h.Set("Idempotency-Replayed", "true")
c.w.WriteHeader(sr.Status)
_, werr := c.w.Write(sr.Body)
return werr
}
// Capture the handler's response so we can persist + flush it. Restore
// the writer via defer so a panic in next() can't leave c.w dangling.
rec := &captureWriter{header: http.Header{}, status: http.StatusOK}
orig := c.w
c.w = rec
defer func() { c.w = orig }()
if err := next(c); err != nil {
return err // errors aren't cached; the framework writes the envelope to orig
}
for k, vs := range rec.header {
for _, v := range vs {
orig.Header().Add(k, v)
}
}
orig.WriteHeader(rec.status)
if _, werr := orig.Write(rec.buf.Bytes()); werr != nil {
return werr
}
if rec.status >= 200 && rec.status < 300 {
body := append([]byte(nil), rec.buf.Bytes()...)
stored := StoredResponse{Status: rec.status, Header: rec.header.Clone(), Body: body}
if serr := store.Save(ctx, scoped, stored, ttl); serr != nil {
c.Log().Warn("idempotency.save_failed", "category", "idempotency", "error_msg", serr.Error())
}
}
return nil
}
}
}
// captureWriter buffers a handler's response so the idempotency middleware can
// persist and replay it. It implements http.ResponseWriter.
type captureWriter struct {
header http.Header
buf bytes.Buffer
status int
wrote bool
}
func (c *captureWriter) Header() http.Header { return c.header }
func (c *captureWriter) WriteHeader(code int) {
if c.wrote {
return
}
c.status = code
c.wrote = true
}
func (c *captureWriter) Write(b []byte) (int, error) {
if !c.wrote {
c.WriteHeader(http.StatusOK)
}
return c.buf.Write(b)
}