Phase 2 — internal/storage/: Content-addressed blob storage with atomic writes via rename. BlobWriter stages data in uploads dir with running SHA-256 hash, commits by verifying digest then renaming to layers/sha256/<prefix>/<hex>. Reader provides Open, Stat, Delete, Exists with digest validation. Phase 3 — internal/auth/ + internal/server/: MCIAS client with Login and ValidateToken, 30s SHA-256-keyed cache with lazy eviction and injectable clock for testing. TLS 1.3 minimum with optional custom CA cert. Chi router with RequireAuth middleware (Bearer token extraction, WWW-Authenticate header, OCI error format), token endpoint (Basic auth → bearer exchange via MCIAS), and /v2/ version check handler. 52 tests passing (14 storage + 9 auth + 9 server + 20 existing). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
60 lines
1.8 KiB
Go
60 lines
1.8 KiB
Go
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"git.wntrmute.dev/kyle/mcr/internal/auth"
|
|
)
|
|
|
|
// TokenValidator abstracts token validation so the middleware can work
|
|
// with the real MCIAS client or a test fake.
|
|
type TokenValidator interface {
|
|
ValidateToken(token string) (*auth.Claims, error)
|
|
}
|
|
|
|
// RequireAuth returns middleware that validates Bearer tokens via the
|
|
// given TokenValidator. On success the authenticated Claims are injected
|
|
// into the request context. On failure a 401 with an OCI-format error
|
|
// body and a WWW-Authenticate header is returned.
|
|
func RequireAuth(validator TokenValidator, serviceName string) func(http.Handler) http.Handler {
|
|
wwwAuth := fmt.Sprintf(`Bearer realm="/v2/token",service="%s"`, serviceName)
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
token := extractBearerToken(r)
|
|
if token == "" {
|
|
w.Header().Set("WWW-Authenticate", wwwAuth)
|
|
writeOCIError(w, "UNAUTHORIZED", http.StatusUnauthorized, "authentication required")
|
|
return
|
|
}
|
|
|
|
claims, err := validator.ValidateToken(token)
|
|
if err != nil {
|
|
w.Header().Set("WWW-Authenticate", wwwAuth)
|
|
writeOCIError(w, "UNAUTHORIZED", http.StatusUnauthorized, "authentication required")
|
|
return
|
|
}
|
|
|
|
ctx := auth.ContextWithClaims(r.Context(), claims)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|
|
|
|
// extractBearerToken parses a "Bearer <token>" value from the
|
|
// Authorization header. It returns an empty string if the header is
|
|
// missing or malformed.
|
|
func extractBearerToken(r *http.Request) string {
|
|
h := r.Header.Get("Authorization")
|
|
if h == "" {
|
|
return ""
|
|
}
|
|
const prefix = "Bearer "
|
|
if !strings.HasPrefix(h, prefix) {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(h[len(prefix):])
|
|
}
|