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

155 lines
5.2 KiB
Go

package chassis
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// untimedKey carries the pre-deadline request context so Stream can shed the
// per-request budget. See instrument.
type untimedKey struct{}
// heartbeatEvery bounds how long a stream stays silent. Any proxy between the
// board and a browser will drop an idle connection eventually — Traefik's
// default is 0 (never) but Cloudflare's is 100s and a corporate egress proxy's
// is anyone's guess — so a comment frame goes out on every tick even when the
// board state has not moved. It is two bytes and it is the difference between
// a live dashboard and one that silently stopped updating an hour ago.
const heartbeatEvery = 20 * time.Second
// Stream is an open server-sent-events response.
//
// SSE rather than a websocket because the traffic is strictly one-way (the
// board pushes state, the browser never talks back), it survives every proxy
// that speaks HTTP/1.1, and EventSource reconnects on its own — so a board
// restart costs the dashboard a few seconds rather than a page reload.
type Stream struct {
w http.ResponseWriter
rc *http.ResponseController
ctx context.Context
closing <-chan struct{}
}
// Stream converts the response into an event stream and returns a handle.
//
// It clears this connection's write deadline (the server sets one from
// RequestTimeout for every other route) and detaches from the per-request
// context deadline, leaving the stream bound to exactly two things: the client
// hanging up, and the server beginning to drain.
//
// The handler MUST NOT write to the Context afterwards — the response is
// committed the moment this returns.
func (c *Context) Stream() (*Stream, error) {
w := c.w
rc := http.NewResponseController(w)
// A stream lives past any per-request deadline by definition. This is the
// call that needs statusRecorder.Unwrap; without it the connection is cut
// mid-stream at RequestTimeout+socketHeadroom.
if err := rc.SetWriteDeadline(time.Time{}); err != nil {
return nil, fmt.Errorf("chassis: stream needs a deadline-capable writer: %w", err)
}
// Tell the edge not to time this response. How long a stream stays open is
// how long an operator left a tab open; in the latency histogram it fires
// HighRequestLatency and drags every percentile for the whole service.
if rec, ok := w.(*statusRecorder); ok {
rec.streamed = true
}
ctx := c.r.Context()
if untimed, ok := ctx.Value(untimedKey{}).(context.Context); ok {
ctx = untimed
}
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-cache, no-transform")
h.Set("Connection", "keep-alive")
// Traefik does not buffer, but this response passes through whatever the
// operator puts in front of it and an accumulating proxy turns a live
// stream into a batch delivered at close.
h.Set("X-Accel-Buffering", "no")
w.WriteHeader(http.StatusOK)
// Past this point the response is committed, so a flush failure must not
// become a returned error — the chassis would write a JSON envelope on top
// of a 200 event stream. The first Send surfaces a dead connection.
_ = rc.Flush()
return &Stream{w: w, rc: rc, ctx: ctx, closing: c.closing}, nil
}
// Context is the stream's lifetime: cancelled when the client disconnects.
func (s *Stream) Context() context.Context { return s.ctx }
// Send JSON-encodes v as one named event and flushes it. A write error means
// the client is gone; the caller returns and the handler ends.
func (s *Stream) Send(event string, v any) error {
body, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("chassis: stream encode %s: %w", event, err)
}
// The payload is compact JSON from encoding/json, so it contains no raw
// newline and needs no multi-line data: continuation.
if _, err := fmt.Fprintf(s.w, "event: %s\ndata: %s\n\n", event, body); err != nil {
return err
}
return s.rc.Flush()
}
// Run pushes an initial frame, then one per tick, until the client disconnects
// or the server drains. It returns nil on every ordinary end — a browser
// closing a tab is not a server error and must not be logged as one.
func (s *Stream) Run(every time.Duration, frame func(context.Context) (any, error)) error {
send := func() error {
v, err := frame(s.ctx)
if err != nil {
return err
}
return s.Send("state", v)
}
if err := send(); err != nil {
return s.classify(err)
}
tick := time.NewTicker(every)
defer tick.Stop()
beat := time.NewTicker(heartbeatEvery)
defer beat.Stop()
for {
select {
case <-s.ctx.Done():
return nil
case <-s.closing:
// Tell the browser to come back rather than letting it infer a
// dead board from a closed socket.
_ = s.Send("bye", map[string]string{"reason": "draining"})
return nil
case <-beat.C:
if _, err := fmt.Fprint(s.w, ": ping\n\n"); err != nil {
return nil
}
if err := s.rc.Flush(); err != nil {
return nil
}
case <-tick.C:
if err := send(); err != nil {
return s.classify(err)
}
}
}
}
// classify swallows the errors that mean "the client left". A disconnect races
// every write, so treating it as a failure would fill the log with 500s every
// time somebody closes a dashboard tab.
func (s *Stream) classify(err error) error {
if s.ctx.Err() != nil {
return nil
}
return err
}