Files
sam 1026d5e3b6 feat(httpapi): the API is described by an OpenAPI document generated with Huma (#2028)
Every /api operation is registered with Huma behind one admin-token
middleware, served at /api/openapi.json with a docs page at /api/docs,
and committed as api/openapi.yaml, which task check keeps current.
2026-11-16 20:05:05 +11:00

66 lines
1.7 KiB
Go

// Package httpjson writes the JSON bodies of the routes outside the API, and
// stores and compares tokens as their hashes.
package httpjson
import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
json "encoding/json/v2"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
// maxBody bounds a request body the API reads.
const maxBody = 1 << 20
// Write encodes v as the response body with status.
func Write(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.MarshalWrite(w, v)
}
// Error writes {"error": msg} with status.
func Error(w http.ResponseWriter, status int, msg string) {
Write(w, status, map[string]string{"error": msg})
}
// Body reads a bounded raw request body.
func Body(r *http.Request) ([]byte, error) {
body, err := io.ReadAll(io.LimitReader(r.Body, maxBody+1))
if err != nil {
return nil, fmt.Errorf("read request body: %w", err)
}
if len(body) > maxBody {
return nil, errors.New("request body too large")
}
return body, nil
}
// Bearer returns the request's bearer token, or "".
func Bearer(r *http.Request) string {
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok {
return ""
}
return strings.TrimSpace(token)
}
// TokenHash is the hex SHA-256 of a token, the only form tokens are stored in.
func TokenHash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// TokenMatches compares a presented token with a stored hash in constant time.
func TokenMatches(token, hash string) bool {
if token == "" || hash == "" {
return false
}
return subtle.ConstantTimeCompare([]byte(TokenHash(token)), []byte(hash)) == 1
}