| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/sha256" |
| 6 | "crypto/subtle" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "net/http" |
| 12 | "strings" |
| 13 | ) |
| 14 | |
| 15 | // Consumer is one sibling allowed to call this app's suite routes: memoria, |
| 16 | // today. Doctrine §6.2: one bearer token per consumer, minted by the |
| 17 | // operator, delivered as platform config, and held here only as its SHA-256. |
| 18 | // Up to two tokens at once, each with an epoch, so a token can be rotated in |
| 19 | // three steps (accept both, switch the sender, drop the old) without a gap. |
| 20 | type Consumer struct { |
| 21 | ID string `json:"consumer_id"` |
| 22 | Tokens []Token `json:"tokens"` |
| 23 | } |
| 24 | |
| 25 | // Token is one accepted token, as the hex SHA-256 of its bytes. |
| 26 | type Token struct { |
| 27 | Epoch int `json:"epoch"` |
| 28 | SHA256 string `json:"sha256"` |
| 29 | } |
| 30 | |
| 31 | // MaxTokensPerConsumer is two: the old token and the new one, for the length |
| 32 | // of a rotation, and never more. |
| 33 | const MaxTokensPerConsumer = 2 |
| 34 | |
| 35 | // EnvSuffix names the variable an app reads its consumers from: |
| 36 | // <APP>_SUITE_CONSUMERS, e.g. DOCS_SUITE_CONSUMERS. |
| 37 | const EnvSuffix = "_SUITE_CONSUMERS" |
| 38 | |
| 39 | // ConsumersFromEnv reads <app>_SUITE_CONSUMERS. Unset or empty is no |
| 40 | // consumers — the routes are not served — and anything malformed is an |
| 41 | // error, so a typo refuses boot rather than silently serving nobody. |
| 42 | func ConsumersFromEnv(getenv func(string) string, app string) ([]Consumer, error) { |
| 43 | return ParseConsumers(getenv(strings.ToUpper(app) + EnvSuffix)) |
| 44 | } |
| 45 | |
| 46 | // ParseConsumers reads the strict JSON list: |
| 47 | // |
| 48 | // [{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":"<64 hex>"}]}] |
| 49 | func ParseConsumers(raw string) ([]Consumer, error) { |
| 50 | if strings.TrimSpace(raw) == "" { |
| 51 | return nil, nil |
| 52 | } |
| 53 | // A list and nothing but a list: "null" decodes into a nil slice |
| 54 | // without error, and would have read as "no consumers" — the routes |
| 55 | // switched off by a typo rather than boot refused (Astra, 2026-11-01). |
| 56 | if !strings.HasPrefix(strings.TrimSpace(raw), "[") { |
| 57 | return nil, errors.New("suite consumers: not the agreed JSON list") |
| 58 | } |
| 59 | dec := json.NewDecoder(bytes.NewReader([]byte(raw))) |
| 60 | dec.DisallowUnknownFields() |
| 61 | var cs []Consumer |
| 62 | if err := dec.Decode(&cs); err != nil || !atEOF(dec) || len(cs) == 0 { |
| 63 | return nil, errors.New("suite consumers: not the agreed JSON list") |
| 64 | } |
| 65 | seen := map[string]bool{} |
| 66 | for _, c := range cs { |
| 67 | if c.ID == "" || seen[c.ID] { |
| 68 | return nil, errors.New("suite consumers: a consumer_id is empty or repeated") |
| 69 | } |
| 70 | seen[c.ID] = true |
| 71 | if len(c.Tokens) == 0 || len(c.Tokens) > MaxTokensPerConsumer { |
| 72 | return nil, fmt.Errorf("suite consumers: %s must have one or two tokens", c.ID) |
| 73 | } |
| 74 | for _, t := range c.Tokens { |
| 75 | b, err := hex.DecodeString(t.SHA256) |
| 76 | if err != nil || len(b) != sha256.Size { |
| 77 | return nil, fmt.Errorf("suite consumers: %s has a token that is not a hex SHA-256", c.ID) |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | return cs, nil |
| 82 | } |
| 83 | |
| 84 | // TokenHash is what an operator puts in the consumers list for a token. |
| 85 | func TokenHash(token string) string { |
| 86 | sum := sha256.Sum256([]byte(token)) |
| 87 | return hex.EncodeToString(sum[:]) |
| 88 | } |
| 89 | |
| 90 | // Authenticate admits a request carrying a configured consumer's token and |
| 91 | // answers every other one with the same empty 401: no token, a malformed |
| 92 | // header, an unknown token and a retired one are indistinguishable. Every |
| 93 | // configured hash is compared, in constant time, whatever matched first. |
| 94 | // |
| 95 | // Its 401 carries the same Cache-Control and Vary as every other response |
| 96 | // of this package (noStore). |
| 97 | func Authenticate(consumers []Consumer, next http.Handler) http.Handler { |
| 98 | return noStore(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 99 | tok, ok := bearer(r) |
| 100 | if !ok || tok == "" { |
| 101 | w.WriteHeader(http.StatusUnauthorized) |
| 102 | return |
| 103 | } |
| 104 | sum := sha256.Sum256([]byte(tok)) |
| 105 | var match Consumer |
| 106 | found := 0 |
| 107 | for _, c := range consumers { |
| 108 | for _, t := range c.Tokens { |
| 109 | want, _ := hex.DecodeString(t.SHA256) |
| 110 | if subtle.ConstantTimeCompare(sum[:], want) == 1 { |
| 111 | match = c |
| 112 | found = 1 |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | if found == 0 { |
| 117 | w.WriteHeader(http.StatusUnauthorized) |
| 118 | return |
| 119 | } |
| 120 | next.ServeHTTP(w, r.WithContext(contextWithConsumer(r.Context(), match))) |
| 121 | })) |
| 122 | } |
| 123 | |