hush/cmd/hushd/handlers.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

184 lines
6.2 KiB
Go

package main
import (
"errors"
"net/http"
"time"
"github.com/orchard9/go-chassis/chassis"
"github.com/orchard9/hush/internal/secret"
"github.com/orchard9/hush/internal/store"
"github.com/orchard9/hush/internal/web"
)
// Server holds the handler dependencies.
type Server struct {
cfg Config
store store.Store
pages *web.Pages
metrics *Metrics
}
// pageData is the same for every render: the limits, so the browser enforces
// what the server enforces. It carries nothing request-specific, which is why
// both pages are safely static.
func (s *Server) pageData() web.Data {
return web.Data{
MaxCiphertextBytes: secret.MaxCiphertextBytes,
DefaultTTLSeconds: int(secret.DefaultTTL.Seconds()),
MinTTLSeconds: int(secret.MinTTL.Seconds()),
MaxTTLSeconds: int(secret.MaxTTL.Seconds()),
}
}
// handleCreatePage serves GET /.
func (s *Server) handleCreatePage(c *chassis.Context) error {
return s.pages.Create(c.Writer(), s.pageData())
}
// handleRevealPage serves GET /s/{id}.
//
// It touches NO storage — not even to check whether the id exists. That is the
// design's load-bearing property: Slack, Teams, WhatsApp, iMessage and Outlook
// Safe Links all fetch URLs before a human sees them, so any read here would
// destroy most secrets in transit. It also means this response cannot leak
// whether an id exists.
//
// The id is not even parsed: a malformed one gets the same page, and the POST
// is what answers. Validating here would make this endpoint an id oracle.
func (s *Server) handleRevealPage(c *chassis.Context) error {
return s.pages.Reveal(c.Writer(), s.pageData())
}
type createRequest struct {
Ciphertext string `json:"ciphertext"`
TTLSeconds int64 `json:"ttl_seconds"`
}
type createResponse struct {
ID string `json:"id"`
ExpiresAt string `json:"expires_at"`
TTLSeconds int64 `json:"ttl_seconds"`
}
// handleCreate serves POST /api/secrets.
//
// It accepts ciphertext only. There is deliberately no endpoint taking a
// plaintext secret: one would make the server able to read secrets, and then
// nobody could tell from a link which guarantee they had.
func (s *Server) handleCreate(c *chassis.Context) error {
var req createRequest
if err := c.Bind(&req); err != nil {
s.metrics.Rejected.WithLabelValues(reasonMalformed).Inc()
return err
}
if err := secret.ValidateCiphertext(req.Ciphertext); err != nil {
reason, code := classifyCiphertextError(err)
s.metrics.Rejected.WithLabelValues(reason).Inc()
// err carries sizes, never content: ValidateCiphertext never puts the
// ciphertext in its message.
return &chassis.Error{Status: http.StatusUnprocessableEntity, Code: code, Msg: err.Error()}
}
ttl, err := secret.ResolveTTL(time.Duration(req.TTLSeconds) * time.Second)
if err != nil {
s.metrics.Rejected.WithLabelValues(reasonTTL).Inc()
return &chassis.Error{Status: http.StatusUnprocessableEntity, Code: reasonTTL, Msg: err.Error()}
}
id, err := secret.NewID()
if err != nil {
// No entropy means no safe id. Refuse rather than mint a guessable one.
return chassis.Internal(err)
}
if err := s.store.Put(c.Context(), id, req.Ciphertext, ttl); err != nil {
if errors.Is(err, store.ErrIDCollision) {
// Impossible at 256 bits, so it means an id-generation bug. Surfaced
// rather than retried, because a retry loop would hide it.
c.Log().Error("secret.id_collision", "category", "secret",
"error_type", "id_collision", "sid", id.LogHandle())
return chassis.Internal(err)
}
return chassis.Internal(err)
}
s.metrics.Created.Inc()
s.metrics.Bytes.Observe(float64(len(req.Ciphertext)))
// sid, not id: the id is the capability and never reaches a log.
c.Log().Info("secret.created", "category", "secret",
"sid", id.LogHandle(), "ttl_seconds", int64(ttl.Seconds()),
"ciphertext_bytes", len(req.Ciphertext))
return c.Created(createResponse{
ID: id.Value(),
ExpiresAt: time.Now().UTC().Add(ttl).Format(time.RFC3339),
TTLSeconds: int64(ttl.Seconds()),
})
}
type revealResponse struct {
Ciphertext string `json:"ciphertext"`
}
// gone is the single response for every unavailable secret: never existed,
// already revealed, expired, or evicted early by Redis.
//
// One response for four causes is deliberate. A caller able to tell "already
// revealed" from "never existed" learns that a particular link was real, which
// is information about someone else's secret.
func gone() *chassis.Error {
return &chassis.Error{
Status: http.StatusGone,
Code: "gone",
Msg: "this secret is not available: it was already revealed, expired, or never existed",
}
}
// handleReveal serves POST /api/secrets/{id}/reveal — the only destructive
// route, and the reason GET is inert.
func (s *Server) handleReveal(c *chassis.Context) error {
id, err := secret.ParseID(c.PathValue("id"))
if err != nil {
// A malformed id gets the SAME 410 as a missing one. A 400 here would
// separate "not an id we could have minted" from "an id that is gone",
// which is a free oracle for anyone probing the id space.
s.metrics.Revealed.WithLabelValues("gone").Inc()
return gone()
}
ciphertext, err := s.store.Take(c.Context(), id)
switch {
case errors.Is(err, store.ErrGone):
s.metrics.Revealed.WithLabelValues("gone").Inc()
c.Log().Info("secret.gone", "category", "secret", "sid", id.LogHandle())
return gone()
case err != nil:
// A store error is NOT reported as gone. The secret may still exist,
// and telling the recipient it is gone would send them to rotate a
// credential that was never delivered.
return chassis.Internal(err)
}
s.metrics.Revealed.WithLabelValues("ok").Inc()
c.Log().Info("secret.revealed", "category", "secret", "sid", id.LogHandle())
return c.OK(revealResponse{Ciphertext: ciphertext})
}
// classifyCiphertextError maps a validation failure to its metric reason and
// API error code, which are the same vocabulary on purpose.
func classifyCiphertextError(err error) (reason, code string) {
switch {
case errors.Is(err, secret.ErrCiphertextTooLarge):
return reasonTooLarge, reasonTooLarge
case errors.Is(err, secret.ErrCiphertextInvalid):
return reasonInvalid, reasonInvalid
case errors.Is(err, secret.ErrCiphertextEmpty):
return reasonEmpty, reasonEmpty
default:
return reasonMalformed, reasonMalformed
}
}