package server import ( "bytes" "crypto/sha256" "crypto/subtle" "encoding/hex" "encoding/json" "errors" "fmt" "net/http" "strings" ) // Consumer is one sibling allowed to call this app's suite routes: memoria, // today. Doctrine ยง6.2: one bearer token per consumer, minted by the // operator, delivered as platform config, and held here only as its SHA-256. // Up to two tokens at once, each with an epoch, so a token can be rotated in // three steps (accept both, switch the sender, drop the old) without a gap. type Consumer struct { ID string `json:"consumer_id"` Tokens []Token `json:"tokens"` } // Token is one accepted token, as the hex SHA-256 of its bytes. type Token struct { Epoch int `json:"epoch"` SHA256 string `json:"sha256"` } // MaxTokensPerConsumer is two: the old token and the new one, for the length // of a rotation, and never more. const MaxTokensPerConsumer = 2 // EnvSuffix names the variable an app reads its consumers from: // _SUITE_CONSUMERS, e.g. DOCS_SUITE_CONSUMERS. const EnvSuffix = "_SUITE_CONSUMERS" // ConsumersFromEnv reads _SUITE_CONSUMERS. Unset or empty is no // consumers โ€” the routes are not served โ€” and anything malformed is an // error, so a typo refuses boot rather than silently serving nobody. func ConsumersFromEnv(getenv func(string) string, app string) ([]Consumer, error) { return ParseConsumers(getenv(strings.ToUpper(app) + EnvSuffix)) } // ParseConsumers reads the strict JSON list: // // [{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<64 hex>"}]}] func ParseConsumers(raw string) ([]Consumer, error) { if strings.TrimSpace(raw) == "" { return nil, nil } // A list and nothing but a list: "null" decodes into a nil slice // without error, and would have read as "no consumers" โ€” the routes // switched off by a typo rather than boot refused (Astra, 2026-11-01). if !strings.HasPrefix(strings.TrimSpace(raw), "[") { return nil, errors.New("suite consumers: not the agreed JSON list") } dec := json.NewDecoder(bytes.NewReader([]byte(raw))) dec.DisallowUnknownFields() var cs []Consumer if err := dec.Decode(&cs); err != nil || !atEOF(dec) || len(cs) == 0 { return nil, errors.New("suite consumers: not the agreed JSON list") } seen := map[string]bool{} for _, c := range cs { if c.ID == "" || seen[c.ID] { return nil, errors.New("suite consumers: a consumer_id is empty or repeated") } seen[c.ID] = true if len(c.Tokens) == 0 || len(c.Tokens) > MaxTokensPerConsumer { return nil, fmt.Errorf("suite consumers: %s must have one or two tokens", c.ID) } for _, t := range c.Tokens { b, err := hex.DecodeString(t.SHA256) if err != nil || len(b) != sha256.Size { return nil, fmt.Errorf("suite consumers: %s has a token that is not a hex SHA-256", c.ID) } } } return cs, nil } // TokenHash is what an operator puts in the consumers list for a token. func TokenHash(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) } // Authenticate admits a request carrying a configured consumer's token and // answers every other one with the same empty 401: no token, a malformed // header, an unknown token and a retired one are indistinguishable. Every // configured hash is compared, in constant time, whatever matched first. // // Its 401 carries the same Cache-Control and Vary as every other response // of this package (noStore). func Authenticate(consumers []Consumer, next http.Handler) http.Handler { return noStore(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tok, ok := bearer(r) if !ok || tok == "" { w.WriteHeader(http.StatusUnauthorized) return } sum := sha256.Sum256([]byte(tok)) var match Consumer found := 0 for _, c := range consumers { for _, t := range c.Tokens { want, _ := hex.DecodeString(t.SHA256) if subtle.ConstantTimeCompare(sum[:], want) == 1 { match = c found = 1 } } } if found == 0 { w.WriteHeader(http.StatusUnauthorized) return } next.ServeHTTP(w, r.WithContext(contextWithConsumer(r.Context(), match))) })) }