hush/vendor/github.com/orchard9/go-chassis/chassis/auth.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

105 lines
3.5 KiB
Go

package chassis
import (
"context"
"crypto/subtle"
"net/http"
"strings"
)
// Identity is the authenticated principal attached to the request context by an
// auth Middleware. Subject is the stable principal id; OrgID is the tenant the
// principal is acting in (the multi-tenant scoping key — every tenant row
// filters by it); Scopes are the granted permissions; Claims carries any extra
// verified attributes without coupling chassis to a domain type.
type Identity struct {
Subject string
OrgID string
Scopes []string
Claims map[string]string
}
// HasScope reports whether the identity holds the required scope. A held scope
// ending in ":*" dominates any required scope sharing its prefix, so "admin:*"
// satisfies "admin:read". An exact match always passes.
func (id *Identity) HasScope(required string) bool {
if id == nil {
return false
}
for _, s := range id.Scopes {
if s == required {
return true
}
if prefix, ok := strings.CutSuffix(s, ":*"); ok {
if reqPrefix, _, found := strings.Cut(required, ":"); found && reqPrefix == prefix {
return true
}
}
}
return false
}
// Authenticator verifies a request and returns its Identity, or an *Error
// (Unauthorized/Forbidden) when verification fails. Implementations:
// - NoAuth — local default, everyone is anonymous (documented seam).
// - StaticToken — shared bearer token, constant-time compared (local/CI).
// - (later) OIDC — coreos/go-oidc verifier, JWKS cache, refresh-on-kid-miss.
// - (later) APIKey — hashed key behind a Secrets port, constant-time compare.
type Authenticator interface {
Authenticate(r *http.Request) (*Identity, error)
}
type identityKey struct{}
// IdentityFrom returns the authenticated identity, or false when the route was
// not behind RequireAuth.
func IdentityFrom(ctx context.Context) (*Identity, bool) {
id, ok := ctx.Value(identityKey{}).(*Identity)
return id, ok
}
// RequireAuth is route/group middleware that runs the Authenticator, rejecting
// the request (deny-by-default) when it fails and otherwise stashing the
// Identity in the context for handlers.
func RequireAuth(a Authenticator) Middleware {
return func(next HandlerFunc) HandlerFunc {
return func(c *Context) error {
id, err := a.Authenticate(c.r)
if err != nil {
return err // already an *Error (Unauthorized/Forbidden)
}
c.r = c.r.WithContext(context.WithValue(c.r.Context(), identityKey{}, id))
return next(c)
}
}
}
// NoAuth treats every caller as anonymous. The explicit local default — never
// select it for a protected environment.
type NoAuth struct{}
func (NoAuth) Authenticate(*http.Request) (*Identity, error) {
return &Identity{Subject: "anonymous"}, nil
}
// StaticToken authenticates a single shared bearer token in constant time
// (crypto/subtle) to avoid leaking the token via response timing. For local/CI
// and internal service-to-service; real principals use OIDC/API-key later.
type StaticToken struct{ token string }
// NewStaticToken builds a StaticToken; an empty token rejects every request.
func NewStaticToken(token string) StaticToken { return StaticToken{token: token} }
func (s StaticToken) Authenticate(r *http.Request) (*Identity, error) {
const prefix = "Bearer "
h := r.Header.Get("Authorization")
if s.token == "" || !strings.HasPrefix(h, prefix) {
return nil, Unauthorized("missing or malformed bearer token")
}
got := strings.TrimPrefix(h, prefix)
if subtle.ConstantTimeCompare([]byte(got), []byte(s.token)) != 1 {
return nil, Unauthorized("invalid token")
}
return &Identity{Subject: "static-token"}, nil
}