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.
140 lines
4.9 KiB
Go
140 lines
4.9 KiB
Go
package chassis
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/orchard9/go-chassis/logging"
|
|
)
|
|
|
|
// HandlerFunc is the chassis handler signature: return an error and the
|
|
// framework maps it to the JSON error envelope. See patterns/go-chassis.md.
|
|
type HandlerFunc func(*Context) error
|
|
|
|
// Middleware decorates a HandlerFunc (route/group scope: auth, rate-limit).
|
|
// Cross-cutting infra (recover, request-id, logging, metrics) is applied once
|
|
// at the server edge as http.Handler middleware, not here.
|
|
type Middleware func(HandlerFunc) HandlerFunc
|
|
|
|
// Context carries the request/response for one call plus typed helpers.
|
|
type Context struct {
|
|
w http.ResponseWriter
|
|
r *http.Request
|
|
maxBytes int64
|
|
validate func(any) error // optional; set from Config.Validator
|
|
// closing fires when the app begins draining, so a Stream ends with the
|
|
// pod instead of holding Shutdown open.
|
|
closing <-chan struct{}
|
|
}
|
|
|
|
// Context returns the request context (deadline + request-scoped logger).
|
|
func (c *Context) Context() context.Context { return c.r.Context() }
|
|
|
|
// Request exposes the raw request for the rare case a helper does not cover.
|
|
func (c *Context) Request() *http.Request { return c.r }
|
|
|
|
// Writer exposes the raw ResponseWriter for the three responses the JSON
|
|
// envelope cannot carry: the Scalar docs page (HTML), the OpenAPI document
|
|
// (pre-rendered bytes), and a streamed artifact (video/mp4).
|
|
func (c *Context) Writer() http.ResponseWriter { return c.w }
|
|
|
|
// Log returns the request-scoped logger (carries request_id).
|
|
func (c *Context) Log() *slog.Logger { return logging.From(c.r.Context()) }
|
|
|
|
// PathValue returns a ServeMux wildcard value, e.g. {id} from "/v1/x/{id}".
|
|
func (c *Context) PathValue(key string) string { return c.r.PathValue(key) }
|
|
|
|
// Identity returns the authenticated principal, or false when the route was not
|
|
// behind RequireAuth.
|
|
func (c *Context) Identity() (*Identity, bool) { return IdentityFrom(c.r.Context()) }
|
|
|
|
// OrgID returns the active tenant for the caller ("" when unauthenticated or the
|
|
// identity carries no org). Repos MUST filter every tenant query by it.
|
|
func (c *Context) OrgID() string {
|
|
if id, ok := c.Identity(); ok {
|
|
return id.OrgID
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// TraceID returns the request's trace id (W3C traceparent or generated).
|
|
func (c *Context) TraceID() string {
|
|
id, _ := TraceIDFrom(c.r.Context())
|
|
return id
|
|
}
|
|
|
|
// Bind enforces the body-size limit, then JSON-decodes into v rejecting unknown
|
|
// fields. An oversized body becomes 413; a malformed body becomes 400 — neither
|
|
// leaks internals to the client.
|
|
func (c *Context) Bind(v any) error {
|
|
c.r.Body = http.MaxBytesReader(c.w, c.r.Body, c.maxBytes)
|
|
dec := json.NewDecoder(c.r.Body)
|
|
dec.DisallowUnknownFields()
|
|
if err := dec.Decode(v); err != nil {
|
|
var maxErr *http.MaxBytesError
|
|
if errors.As(err, &maxErr) {
|
|
return PayloadTooLarge("request body too large").WithCause(err)
|
|
}
|
|
if f, ok := unknownField(err); ok {
|
|
return BadRequest(fmt.Sprintf("unknown field %q", f)).WithCause(err)
|
|
}
|
|
return BadRequest("invalid JSON body").WithCause(err)
|
|
}
|
|
if c.validate != nil {
|
|
if err := c.validate(v); err != nil {
|
|
return Unprocessable("request failed validation").WithCause(err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// unknownFieldPrefix is what encoding/json returns under
|
|
// DisallowUnknownFields. The stdlib gives no typed error for it, so matching the
|
|
// text is the only way to tell "you sent a field we do not accept" from "your
|
|
// JSON is broken" — and they are different bugs on the caller's side.
|
|
const unknownFieldPrefix = `json: unknown field `
|
|
|
|
// unknownField extracts the rejected field name, if that is why decoding failed.
|
|
//
|
|
// The name is echoed to the client because the alternative is what this cost us:
|
|
// a worker POSTing a well-formed body with one extra key is told "invalid JSON
|
|
// body", which is false, and has nothing to act on. Echoing a key the caller
|
|
// just sent leaks nothing. The rest of the decoder's errors stay generic — an
|
|
// UnmarshalTypeError names Go struct fields and types, which is internal detail.
|
|
func unknownField(err error) (string, bool) {
|
|
msg := err.Error()
|
|
if !strings.HasPrefix(msg, unknownFieldPrefix) {
|
|
return "", false
|
|
}
|
|
name, uerr := strconv.Unquote(strings.TrimPrefix(msg, unknownFieldPrefix))
|
|
if uerr != nil {
|
|
return "", false
|
|
}
|
|
return name, true
|
|
}
|
|
|
|
// OK writes 200 + JSON. Created writes 201. NoContent writes 204.
|
|
func (c *Context) OK(v any) error { return c.JSON(http.StatusOK, v) }
|
|
func (c *Context) Created(v any) error { return c.JSON(http.StatusCreated, v) }
|
|
|
|
func (c *Context) NoContent() error {
|
|
c.w.WriteHeader(http.StatusNoContent)
|
|
return nil
|
|
}
|
|
|
|
// JSON writes the status code and JSON-encodes v.
|
|
func (c *Context) JSON(code int, v any) error {
|
|
c.w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
c.w.WriteHeader(code)
|
|
if v == nil {
|
|
return nil
|
|
}
|
|
return json.NewEncoder(c.w).Encode(v)
|
|
}
|