Batch A: blob storage layer, MCIAS auth, OCI token endpoint
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>
This commit is contained in:
59
internal/server/middleware.go
Normal file
59
internal/server/middleware.go
Normal file
@@ -0,0 +1,59 @@
|
||||
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):])
|
||||
}
|
||||
112
internal/server/middleware_test.go
Normal file
112
internal/server/middleware_test.go
Normal file
@@ -0,0 +1,112 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.wntrmute.dev/kyle/mcr/internal/auth"
|
||||
)
|
||||
|
||||
type fakeValidator struct {
|
||||
claims *auth.Claims
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeValidator) ValidateToken(_ string) (*auth.Claims, error) {
|
||||
return f.claims, f.err
|
||||
}
|
||||
|
||||
func TestRequireAuthValid(t *testing.T) {
|
||||
t.Helper()
|
||||
claims := &auth.Claims{Subject: "alice", AccountType: "user", Roles: []string{"reader"}}
|
||||
validator := &fakeValidator{claims: claims}
|
||||
|
||||
var gotClaims *auth.Claims
|
||||
inner := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
gotClaims = auth.ClaimsFromContext(r.Context())
|
||||
})
|
||||
|
||||
handler := RequireAuth(validator, "mcr-test")(inner)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v2/", nil)
|
||||
req.Header.Set("Authorization", "Bearer valid-token")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
if gotClaims == nil {
|
||||
t.Fatal("expected claims in context, got nil")
|
||||
}
|
||||
if gotClaims.Subject != "alice" {
|
||||
t.Fatalf("subject: got %q, want %q", gotClaims.Subject, "alice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireAuthMissing(t *testing.T) {
|
||||
t.Helper()
|
||||
validator := &fakeValidator{claims: nil, err: auth.ErrUnauthorized}
|
||||
|
||||
inner := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
t.Fatal("inner handler should not be called")
|
||||
})
|
||||
|
||||
handler := RequireAuth(validator, "mcr-test")(inner)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v2/", nil)
|
||||
// No Authorization header.
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
wwwAuth := rec.Header().Get("WWW-Authenticate")
|
||||
want := `Bearer realm="/v2/token",service="mcr-test"`
|
||||
if wwwAuth != want {
|
||||
t.Fatalf("WWW-Authenticate: got %q, want %q", wwwAuth, want)
|
||||
}
|
||||
|
||||
var ociErr ociErrorResponse
|
||||
if err := json.NewDecoder(rec.Body).Decode(&ociErr); err != nil {
|
||||
t.Fatalf("decode OCI error: %v", err)
|
||||
}
|
||||
if len(ociErr.Errors) != 1 || ociErr.Errors[0].Code != "UNAUTHORIZED" {
|
||||
t.Fatalf("OCI error: got %+v, want UNAUTHORIZED", ociErr.Errors)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireAuthInvalid(t *testing.T) {
|
||||
t.Helper()
|
||||
validator := &fakeValidator{claims: nil, err: auth.ErrUnauthorized}
|
||||
|
||||
inner := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
t.Fatal("inner handler should not be called")
|
||||
})
|
||||
|
||||
handler := RequireAuth(validator, "mcr-test")(inner)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v2/", nil)
|
||||
req.Header.Set("Authorization", "Bearer bad-token")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
var ociErr ociErrorResponse
|
||||
if err := json.NewDecoder(rec.Body).Decode(&ociErr); err != nil {
|
||||
t.Fatalf("decode OCI error: %v", err)
|
||||
}
|
||||
if len(ociErr.Errors) != 1 || ociErr.Errors[0].Code != "UNAUTHORIZED" {
|
||||
t.Fatalf("OCI error: got %+v, want UNAUTHORIZED", ociErr.Errors)
|
||||
}
|
||||
}
|
||||
23
internal/server/ocierror.go
Normal file
23
internal/server/ocierror.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type ociErrorEntry struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type ociErrorResponse struct {
|
||||
Errors []ociErrorEntry `json:"errors"`
|
||||
}
|
||||
|
||||
func writeOCIError(w http.ResponseWriter, code string, status int, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(ociErrorResponse{
|
||||
Errors: []ociErrorEntry{{Code: code, Message: message}},
|
||||
})
|
||||
}
|
||||
21
internal/server/routes.go
Normal file
21
internal/server/routes.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package server
|
||||
|
||||
import "github.com/go-chi/chi/v5"
|
||||
|
||||
// NewRouter builds the chi router with all OCI Distribution Spec
|
||||
// endpoints and auth middleware wired up.
|
||||
func NewRouter(validator TokenValidator, loginClient LoginClient, serviceName string) *chi.Mux {
|
||||
r := chi.NewRouter()
|
||||
|
||||
// Token endpoint is NOT behind RequireAuth — clients use Basic auth
|
||||
// here to obtain a bearer token.
|
||||
r.Get("/v2/token", TokenHandler(loginClient))
|
||||
|
||||
// All other /v2 endpoints require a valid bearer token.
|
||||
r.Route("/v2", func(v2 chi.Router) {
|
||||
v2.Use(RequireAuth(validator, serviceName))
|
||||
v2.Get("/", V2Handler())
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
94
internal/server/routes_test.go
Normal file
94
internal/server/routes_test.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.wntrmute.dev/kyle/mcr/internal/auth"
|
||||
)
|
||||
|
||||
func TestRoutesV2Authenticated(t *testing.T) {
|
||||
t.Helper()
|
||||
validator := &fakeValidator{
|
||||
claims: &auth.Claims{Subject: "alice", AccountType: "user", Roles: []string{"reader"}},
|
||||
}
|
||||
loginClient := &fakeLoginClient{token: "tok-abc", expiresIn: 3600}
|
||||
router := NewRouter(validator, loginClient, "mcr-test")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v2/", nil)
|
||||
req.Header.Set("Authorization", "Bearer valid-token")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
ct := rec.Header().Get("Content-Type")
|
||||
if ct != "application/json" {
|
||||
t.Fatalf("Content-Type: got %q, want %q", ct, "application/json")
|
||||
}
|
||||
|
||||
body := rec.Body.String()
|
||||
if body != "{}" {
|
||||
t.Fatalf("body: got %q, want %q", body, "{}")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutesV2Unauthenticated(t *testing.T) {
|
||||
t.Helper()
|
||||
validator := &fakeValidator{claims: nil, err: auth.ErrUnauthorized}
|
||||
loginClient := &fakeLoginClient{}
|
||||
router := NewRouter(validator, loginClient, "mcr-test")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v2/", nil)
|
||||
// No Authorization header.
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
wwwAuth := rec.Header().Get("WWW-Authenticate")
|
||||
want := `Bearer realm="/v2/token",service="mcr-test"`
|
||||
if wwwAuth != want {
|
||||
t.Fatalf("WWW-Authenticate: got %q, want %q", wwwAuth, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutesTokenEndpoint(t *testing.T) {
|
||||
t.Helper()
|
||||
// The validator should never be called for /v2/token.
|
||||
validator := &fakeValidator{claims: nil, err: auth.ErrUnauthorized}
|
||||
loginClient := &fakeLoginClient{token: "tok-from-login", expiresIn: 1800}
|
||||
router := NewRouter(validator, loginClient, "mcr-test")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v2/token", nil)
|
||||
req.SetBasicAuth("bob", "password")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
var resp tokenResponse
|
||||
if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp.Token != "tok-from-login" {
|
||||
t.Fatalf("token: got %q, want %q", resp.Token, "tok-from-login")
|
||||
}
|
||||
if resp.ExpiresIn != 1800 {
|
||||
t.Fatalf("expires_in: got %d, want %d", resp.ExpiresIn, 1800)
|
||||
}
|
||||
if resp.IssuedAt == "" {
|
||||
t.Fatal("issued_at: expected non-empty RFC 3339 timestamp")
|
||||
}
|
||||
}
|
||||
45
internal/server/token.go
Normal file
45
internal/server/token.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LoginClient abstracts the MCIAS login call so the handler can work
|
||||
// with the real client or a test fake.
|
||||
type LoginClient interface {
|
||||
Login(username, password string) (token string, expiresIn int, err error)
|
||||
}
|
||||
|
||||
// tokenResponse is the JSON body returned by the token endpoint.
|
||||
type tokenResponse struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
IssuedAt string `json:"issued_at"`
|
||||
}
|
||||
|
||||
// TokenHandler returns an http.HandlerFunc that exchanges Basic
|
||||
// credentials for a bearer token via the given LoginClient.
|
||||
func TokenHandler(loginClient LoginClient) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || username == "" {
|
||||
writeOCIError(w, "UNAUTHORIZED", http.StatusUnauthorized, "basic authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
token, expiresIn, err := loginClient.Login(username, password)
|
||||
if err != nil {
|
||||
writeOCIError(w, "UNAUTHORIZED", http.StatusUnauthorized, "authentication failed")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(tokenResponse{
|
||||
Token: token,
|
||||
ExpiresIn: expiresIn,
|
||||
IssuedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
}
|
||||
98
internal/server/token_test.go
Normal file
98
internal/server/token_test.go
Normal file
@@ -0,0 +1,98 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.wntrmute.dev/kyle/mcr/internal/auth"
|
||||
)
|
||||
|
||||
type fakeLoginClient struct {
|
||||
token string
|
||||
expiresIn int
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeLoginClient) Login(_, _ string) (string, int, error) {
|
||||
return f.token, f.expiresIn, f.err
|
||||
}
|
||||
|
||||
func TestTokenHandlerSuccess(t *testing.T) {
|
||||
t.Helper()
|
||||
lc := &fakeLoginClient{token: "tok-xyz", expiresIn: 7200}
|
||||
handler := TokenHandler(lc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v2/token", nil)
|
||||
req.SetBasicAuth("alice", "secret")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
|
||||
var resp tokenResponse
|
||||
if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp.Token != "tok-xyz" {
|
||||
t.Fatalf("token: got %q, want %q", resp.Token, "tok-xyz")
|
||||
}
|
||||
if resp.ExpiresIn != 7200 {
|
||||
t.Fatalf("expires_in: got %d, want %d", resp.ExpiresIn, 7200)
|
||||
}
|
||||
if resp.IssuedAt == "" {
|
||||
t.Fatal("issued_at: expected non-empty RFC 3339 timestamp")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenHandlerInvalidCreds(t *testing.T) {
|
||||
t.Helper()
|
||||
lc := &fakeLoginClient{err: auth.ErrUnauthorized}
|
||||
handler := TokenHandler(lc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v2/token", nil)
|
||||
req.SetBasicAuth("alice", "wrong")
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
var ociErr ociErrorResponse
|
||||
if err := json.NewDecoder(rec.Body).Decode(&ociErr); err != nil {
|
||||
t.Fatalf("decode OCI error: %v", err)
|
||||
}
|
||||
if len(ociErr.Errors) != 1 || ociErr.Errors[0].Code != "UNAUTHORIZED" {
|
||||
t.Fatalf("OCI error: got %+v, want UNAUTHORIZED", ociErr.Errors)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenHandlerMissingAuth(t *testing.T) {
|
||||
t.Helper()
|
||||
lc := &fakeLoginClient{token: "should-not-matter"}
|
||||
handler := TokenHandler(lc)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/v2/token", nil)
|
||||
// No Authorization header.
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
var ociErr ociErrorResponse
|
||||
if err := json.NewDecoder(rec.Body).Decode(&ociErr); err != nil {
|
||||
t.Fatalf("decode OCI error: %v", err)
|
||||
}
|
||||
if len(ociErr.Errors) != 1 || ociErr.Errors[0].Code != "UNAUTHORIZED" {
|
||||
t.Fatalf("OCI error: got %+v, want UNAUTHORIZED", ociErr.Errors)
|
||||
}
|
||||
}
|
||||
13
internal/server/v2.go
Normal file
13
internal/server/v2.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package server
|
||||
|
||||
import "net/http"
|
||||
|
||||
// V2Handler returns an http.HandlerFunc that responds with 200 OK and
|
||||
// an empty JSON object, per the OCI Distribution Spec version check.
|
||||
func V2Handler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte("{}"))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user