From 15ac939d64ba80de4f322b6a96bcc24a6698c158 Mon Sep 17 00:00:00 2001 From: pitercoding Date: Tue, 24 Nov 2026 12:45:35 +0100 Subject: [PATCH 1/4] feat(platform): add problem details errors and strict JSON decoding --- backend/internal/platform/health.go | 6 +- backend/internal/platform/json.go | 108 ++++++++++++++++++++++ backend/internal/platform/json_test.go | 84 +++++++++++++++++ backend/internal/platform/problem.go | 41 ++++++++ backend/internal/platform/problem_test.go | 80 ++++++++++++++++ backend/internal/platform/response.go | 16 +++- 6 files changed, 329 insertions(+), 6 deletions(-) create mode 100644 backend/internal/platform/json.go create mode 100644 backend/internal/platform/json_test.go create mode 100644 backend/internal/platform/problem.go create mode 100644 backend/internal/platform/problem_test.go diff --git a/backend/internal/platform/health.go b/backend/internal/platform/health.go index 21def42..9cedf0c 100644 --- a/backend/internal/platform/health.go +++ b/backend/internal/platform/health.go @@ -34,7 +34,7 @@ type healthzResponse struct { // database outage would make the platform restart a healthy API. func NewHealthzHandler(version string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, healthzResponse{Status: "ok", Version: version}) + WriteJSON(w, http.StatusOK, healthzResponse{Status: "ok", Version: version}) } } @@ -49,12 +49,12 @@ func NewReadyzHandler(db Pinger) http.HandlerFunc { if err := db.Ping(ctx); err != nil { log.Printf("readyz: database ping failed: %v", err) - writeJSON(w, http.StatusServiceUnavailable, healthResponse{ + WriteJSON(w, http.StatusServiceUnavailable, healthResponse{ Status: "unavailable", }) return } - writeJSON(w, http.StatusOK, healthResponse{Status: "ok"}) + WriteJSON(w, http.StatusOK, healthResponse{Status: "ok"}) } } diff --git a/backend/internal/platform/json.go b/backend/internal/platform/json.go new file mode 100644 index 0000000..0c359f5 --- /dev/null +++ b/backend/internal/platform/json.go @@ -0,0 +1,108 @@ +package platform + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "mime" + "net/http" + "strings" +) + +// maxJSONBodyBytes limits request bodies (1 MiB). Auth and question bodies +// are a few hundred bytes, so this is generous and still safe. +const maxJSONBodyBytes = 1 << 20 + +var errTrailingData = errors.New("trailing data after the JSON value") + +// DecodeJSON reads the request body into dst, strictly. On any problem it +// writes the error response itself and returns false, so a handler only needs: +// +// if !platform.DecodeJSON(w, r, &req) { return } +// +// Rules: Content-Type must be application/json, at most maxJSONBodyBytes, +// no unknown fields, and exactly one JSON value. +func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool { + if !isJSONContentType(r.Header.Get("Content-Type")) { + WriteProblem(w, http.StatusUnsupportedMediaType, "Content-Type must be application/json") + + return false + } + + // Passing w lets MaxBytesReader close the connection when the limit is hit. + r.Body = http.MaxBytesReader(w, r.Body, maxJSONBodyBytes) + + dec := json.NewDecoder(r.Body) + // An unexpected field is an error, not something to ignore silently. + // This blocks "mass assignment" (for example, a client sending "role"). + dec.DisallowUnknownFields() + + err := dec.Decode(dst) + if err == nil { + // Decode reads only the first value. Anything after it must be an + // end of file, otherwise the client sent more than one value. + // + // RawMessage accepts any JSON. A struct here would also be checked + // by DisallowUnknownFields and fail with "unknown field" instead. + var extra json.RawMessage + + switch err = dec.Decode(&extra); { + case errors.Is(err, io.EOF): + return true + case err == nil: + err = errTrailingData + } + } + + writeDecodeProblem(w, err) + + return false +} + +func isJSONContentType(header string) bool { + // ParseMediaType ignores parameters like "; charset=utf-8". + mediaType, _, err := mime.ParseMediaType(header) + + return err == nil && mediaType == "application/json" +} + +// writeDecodeProblem turns a decoding error into a client-friendly problem. +// Messages are written by us, so parser internals never reach the client. +func writeDecodeProblem(w http.ResponseWriter, err error) { + var ( + syntaxErr *json.SyntaxError + typeErr *json.UnmarshalTypeError + tooBigErr *http.MaxBytesError + ) + + switch { + case errors.As(err, &tooBigErr): + WriteProblem(w, http.StatusRequestEntityTooLarge, + fmt.Sprintf("request body must not exceed %d bytes", tooBigErr.Limit)) + + case errors.Is(err, io.EOF): + WriteProblem(w, http.StatusBadRequest, "request body must not be empty") + + case errors.As(err, &syntaxErr), errors.Is(err, io.ErrUnexpectedEOF): + WriteProblem(w, http.StatusBadRequest, "request body is not valid JSON") + + case errors.As(err, &typeErr): + if typeErr.Field != "" { + WriteProblem(w, http.StatusBadRequest, + fmt.Sprintf("field %q has the wrong type", typeErr.Field)) + } else { + WriteProblem(w, http.StatusBadRequest, "request body has the wrong type") + } + + case errors.Is(err, errTrailingData): + WriteProblem(w, http.StatusBadRequest, "request body must contain a single JSON value") + + // encoding/json has no typed error for unknown fields, only this text. + case strings.HasPrefix(err.Error(), "json: unknown field "): + WriteProblem(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), "json: ")) + + default: + WriteProblem(w, http.StatusBadRequest, "request body is not valid") + } +} diff --git a/backend/internal/platform/json_test.go b/backend/internal/platform/json_test.go new file mode 100644 index 0000000..e63238d --- /dev/null +++ b/backend/internal/platform/json_test.go @@ -0,0 +1,84 @@ +package platform + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestDecodeJSON(t *testing.T) { + type payload struct { + Email string `json:"email"` + } + + // One byte over the limit: must be rejected without reading it all. + tooBig := `{"email":"` + strings.Repeat("a", maxJSONBodyBytes) + `"}` + + cases := []struct { + name string + contentType string + body string + wantStatus int // 0 means the decode must succeed + wantDetail string // substring expected in the problem detail + }{ + {"valid body", "application/json", `{"email":"a@b.c"}`, 0, ""}, + {"content type with charset", "application/json; charset=utf-8", `{"email":"a@b.c"}`, 0, ""}, + + {"missing content type", "", `{"email":"a@b.c"}`, http.StatusUnsupportedMediaType, "application/json"}, + {"text/plain", "text/plain", `{"email":"a@b.c"}`, http.StatusUnsupportedMediaType, "application/json"}, + {"html form", "application/x-www-form-urlencoded", "email=a%40b.c", http.StatusUnsupportedMediaType, "application/json"}, + + {"truncated JSON", "application/json", `{"email":`, http.StatusBadRequest, "not valid JSON"}, + {"not JSON at all", "application/json", `hello`, http.StatusBadRequest, "not valid JSON"}, + {"empty body", "application/json", ``, http.StatusBadRequest, "must not be empty"}, + {"unknown field", "application/json", `{"email":"a@b.c","admin":true}`, http.StatusBadRequest, "admin"}, + {"wrong field type", "application/json", `{"email":123}`, http.StatusBadRequest, "email"}, + {"two JSON values", "application/json", `{"email":"a"}{"email":"b"}`, http.StatusBadRequest, "single JSON value"}, + {"garbage after the value", "application/json", `{"email":"a"} xyz`, http.StatusBadRequest, "not valid JSON"}, + + {"body over the limit", "application/json", tooBig, http.StatusRequestEntityTooLarge, "must not exceed"}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(tc.body)) + if tc.contentType != "" { + req.Header.Set("Content-Type", tc.contentType) + } + + var got payload + ok := DecodeJSON(rec, req, &got) + + if tc.wantStatus == 0 { + if !ok { + t.Fatalf("expected success, got %d %s", rec.Code, rec.Body.String()) + } + if got.Email != "a@b.c" { + t.Fatalf("expected email a@b.c, got %q", got.Email) + } + if rec.Body.Len() != 0 { + t.Fatal("nothing may be written to the response on success") + } + + return + } + + if ok { + t.Fatal("expected the decode to fail") + } + if rec.Code != tc.wantStatus { + t.Fatalf("expected status %d, got %d", tc.wantStatus, rec.Code) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/problem+json" { + t.Fatalf("unexpected content type %q", ct) + } + + detail, _ := decodeBody(t, rec)["detail"].(string) + if !strings.Contains(detail, tc.wantDetail) { + t.Fatalf("expected detail to contain %q, got %q", tc.wantDetail, detail) + } + }) + } +} diff --git a/backend/internal/platform/problem.go b/backend/internal/platform/problem.go new file mode 100644 index 0000000..c94d8e0 --- /dev/null +++ b/backend/internal/platform/problem.go @@ -0,0 +1,41 @@ +package platform + +import "net/http" + +// problemContentType is the media type defined by RFC 9457. +const problemContentType = "application/problem+json" + +// problem is the RFC 9457 document. Errors is an extension member (the RFC +// allows them) that lists invalid fields: field name -> message. +type problem struct { + Type string `json:"type"` + Title string `json:"title"` + Status int `json:"status"` + Detail string `json:"detail,omitempty"` + Errors map[string]string `json:"errors,omitempty"` +} + +// WriteProblem answers with an RFC 9457 error. detail must be safe to show to +// the client: never put internal errors (SQL, stack traces) in it. Log those. +func WriteProblem(w http.ResponseWriter, status int, detail string) { + writeBody(w, status, problemContentType, problem{ + // "about:blank" means "no special meaning beyond the HTTP status". + Type: "about:blank", + Title: http.StatusText(status), + Status: status, + Detail: detail, + }) +} + +// WriteValidationProblem answers 422 with one message per invalid field. +// 400 is for requests we cannot even parse; 422 is for well-formed requests +// whose data breaks the rules. +func WriteValidationProblem(w http.ResponseWriter, fields map[string]string) { + writeBody(w, http.StatusUnprocessableEntity, problemContentType, problem{ + Type: "about:blank", + Title: http.StatusText(http.StatusUnprocessableEntity), + Status: http.StatusUnprocessableEntity, + Detail: "one or more fields are invalid", + Errors: fields, + }) +} diff --git a/backend/internal/platform/problem_test.go b/backend/internal/platform/problem_test.go new file mode 100644 index 0000000..ad7ad64 --- /dev/null +++ b/backend/internal/platform/problem_test.go @@ -0,0 +1,80 @@ +package platform + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "testing" +) + +// decodeBody parses a JSON response body into a generic map. +func decodeBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { + t.Helper() + + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("response body is not JSON: %v (%q)", err, rec.Body.String()) + } + + return body +} + +func TestWriteProblem(t *testing.T) { + t.Run("writes an RFC 9457 problem document", func(t *testing.T) { + rec := httptest.NewRecorder() + + WriteProblem(rec, http.StatusNotFound, "document not found") + + if rec.Code != http.StatusNotFound { + t.Fatalf("expected status 404, got %d", rec.Code) + } + if got := rec.Header().Get("Content-Type"); got != "application/problem+json" { + t.Fatalf("unexpected content type %q", got) + } + + want := map[string]any{ + "type": "about:blank", + "title": "Not Found", + "status": float64(404), // JSON numbers decode as float64 + "detail": "document not found", + } + if got := decodeBody(t, rec); !reflect.DeepEqual(got, want) { + t.Fatalf("expected %v, got %v", want, got) + } + }) + + t.Run("omits detail when it is empty", func(t *testing.T) { + rec := httptest.NewRecorder() + + WriteProblem(rec, http.StatusUnauthorized, "") + + if _, found := decodeBody(t, rec)["detail"]; found { + t.Fatal("expected no detail field") + } + }) +} + +func TestWriteValidationProblem(t *testing.T) { + rec := httptest.NewRecorder() + fields := map[string]string{"email": "is not a valid e-mail address"} + + WriteValidationProblem(rec, fields) + + if rec.Code != http.StatusUnprocessableEntity { + t.Fatalf("expected status 422, got %d", rec.Code) + } + if got := rec.Header().Get("Content-Type"); got != "application/problem+json" { + t.Fatalf("unexpected content type %q", got) + } + + body := decodeBody(t, rec) + if body["title"] != http.StatusText(http.StatusUnprocessableEntity) { + t.Fatalf("unexpected title %v", body["title"]) + } + + want := map[string]any{"email": "is not a valid e-mail address"} + if !reflect.DeepEqual(body["errors"], want) { + t.Fatalf("expected errors %v, got %v", want, body["errors"]) + } +} diff --git a/backend/internal/platform/response.go b/backend/internal/platform/response.go index 5b5e062..7cf0871 100644 --- a/backend/internal/platform/response.go +++ b/backend/internal/platform/response.go @@ -6,14 +6,24 @@ import ( "net/http" ) -// writeJSON writes body as JSON with the given status code. Headers are +// WriteJSON writes body as JSON with the given status code. +func WriteJSON( + w http.ResponseWriter, + status int, + body any, +) { + writeBody(w, status, "application/json", body) +} + +// writeBody is shared by WriteJSON and the problem writers. Headers are // already sent when encoding fails, so the error can only be logged. -func writeJSON( +func writeBody( w http.ResponseWriter, status int, + contentType string, body any, ) { - w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Type", contentType) w.WriteHeader(status) if err := json.NewEncoder(w).Encode(body); err != nil { From 36b939786e71e8e4ff69d6a4a1e481de4930838c Mon Sep 17 00:00:00 2001 From: pitercoding Date: Tue, 24 Nov 2026 13:40:45 +0100 Subject: [PATCH 2/4] feat(auth): add register, login and logout endpoints --- backend/internal/auth/handler.go | 166 +++++++++++++ backend/internal/auth/handler_test.go | 337 ++++++++++++++++++++++++++ 2 files changed, 503 insertions(+) create mode 100644 backend/internal/auth/handler.go create mode 100644 backend/internal/auth/handler_test.go diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.go new file mode 100644 index 0000000..f64346e --- /dev/null +++ b/backend/internal/auth/handler.go @@ -0,0 +1,166 @@ +package auth + +import ( + "context" + "errors" + "log" + "net/http" + + "github.com/google/uuid" + + "github.com/pitercoding/aktenlens/backend/internal/platform" +) + +// SessionCookieName is the cookie that carries the session token. The auth +// middleware (next step) reads it too. +const SessionCookieName = "aktenlens_session" + +// authService is the part of Service the handlers need. Declaring it here +// (the consumer) lets tests plug in a service that fails on purpose. +type authService interface { + Register(ctx context.Context, in RegisterInput) (Account, error) + Login(ctx context.Context, in LoginInput) (Session, error) + Logout(ctx context.Context, token string) error +} + +// Handler exposes the auth use cases over HTTP. +type Handler struct { + svc authService + secureCookies bool +} + +// NewHandler returns the auth handlers. secureCookies must be true in +// production (HTTPS). Only local HTTP development needs false. +func NewHandler(svc authService, secureCookies bool) *Handler { + return &Handler{svc: svc, secureCookies: secureCookies} +} + +// RegisterRoutes attaches the auth routes to mux. +func (h *Handler) RegisterRoutes(mux *http.ServeMux) { + mux.HandleFunc("POST /api/v1/auth/register", h.register) + mux.HandleFunc("POST /api/v1/auth/login", h.login) + mux.HandleFunc("POST /api/v1/auth/logout", h.logout) +} + +// Request and response bodies live here, not in Service: the service knows +// nothing about JSON, and no internal field reaches the API by accident. +type registerRequest struct { + TenantName string `json:"tenant_name"` + Email string `json:"email"` + Password string `json:"password"` +} + +type loginRequest struct { + Email string `json:"email"` + Password string `json:"password"` +} + +type accountResponse struct { + UserID uuid.UUID `json:"user_id"` + TenantID uuid.UUID `json:"tenant_id"` + Email string `json:"email"` + Role string `json:"role"` +} + +func (h *Handler) register(w http.ResponseWriter, r *http.Request) { + var req registerRequest + if !platform.DecodeJSON(w, r, &req) { + return + } + + account, err := h.svc.Register(r.Context(), RegisterInput{ + TenantName: req.TenantName, + Email: req.Email, + Password: req.Password, + }) + + var validationErr *ValidationError + + switch { + case errors.As(err, &validationErr): + platform.WriteValidationProblem(w, validationErr.Fields) + + case errors.Is(err, ErrEmailTaken): + platform.WriteProblem(w, http.StatusConflict, "an account with this e-mail already exists") + + case err != nil: + writeInternalError(w, "register", err) + + default: + w.Header().Set("Cache-Control", "no-store") + platform.WriteJSON(w, http.StatusCreated, accountResponse{ + UserID: account.UserID, + TenantID: account.TenantID, + Email: account.Email, + Role: account.Role, + }) + } +} + +func (h *Handler) login(w http.ResponseWriter, r *http.Request) { + var req loginRequest + if !platform.DecodeJSON(w, r, &req) { + return + } + + session, err := h.svc.Login(r.Context(), LoginInput{ + Email: req.Email, + Password: req.Password, + }) + + switch { + case errors.Is(err, ErrInvalidCredentials): + platform.WriteProblem(w, http.StatusUnauthorized, "invalid e-mail or password") + + case err != nil: + writeInternalError(w, "login", err) + + default: + cookie := h.newCookie(session.Token) + cookie.Expires = session.ExpiresAt + + http.SetCookie(w, cookie) + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(http.StatusNoContent) + } +} + +func (h *Handler) logout(w http.ResponseWriter, r *http.Request) { + // No cookie is fine: logging out twice is not an error. + if cookie, err := r.Cookie(SessionCookieName); err == nil { + if err := h.svc.Logout(r.Context(), cookie.Value); err != nil { + writeInternalError(w, "logout", err) + + return + } + } + + // MaxAge < 0 tells the browser to delete the cookie right away. + cleared := h.newCookie("") + cleared.MaxAge = -1 + + http.SetCookie(w, cleared) + w.WriteHeader(http.StatusNoContent) +} + +// newCookie builds the session cookie with every protection on: +// - HttpOnly: JavaScript cannot read it, so an XSS cannot steal the session. +// - Secure: only sent over HTTPS (off only for local HTTP development). +// - SameSite=Lax: not sent on cross-site POSTs, the base of CSRF protection. +func (h *Handler) newCookie(value string) *http.Cookie { + return &http.Cookie{ + Name: SessionCookieName, + Value: value, + Path: "/", + HttpOnly: true, + Secure: h.secureCookies, + SameSite: http.SameSiteLaxMode, + } +} + +// writeInternalError logs the real error and tells the client nothing about it. +func writeInternalError(w http.ResponseWriter, action string, err error) { + log.Printf("auth: %s failed: %v", action, err) + + platform.WriteProblem(w, http.StatusInternalServerError, "an unexpected error occurred") +} diff --git a/backend/internal/auth/handler_test.go b/backend/internal/auth/handler_test.go new file mode 100644 index 0000000..6c14eb3 --- /dev/null +++ b/backend/internal/auth/handler_test.go @@ -0,0 +1,337 @@ +package auth_test + +import ( + "context" + "encoding/json" + "errors" + "io" + "log" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/pitercoding/aktenlens/backend/internal/auth" +) + +const ( + registerBody = `{"tenant_name":"Acme GmbH","email":"alice@example.com","password":"correct-horse-battery"}` + loginBody = `{"email":"alice@example.com","password":"correct-horse-battery"}` +) + +// env bundles everything an endpoint test needs. +type env struct { + mux http.Handler + svc *auth.Service + clock *fakeClock + pool *pgxpool.Pool +} + +// newEnv wires the real service (fresh database, fake clock) to the handlers. +func newEnv(t *testing.T, secureCookies bool) env { + t.Helper() + + svc, clock, pool := newTestService(t) + + mux := http.NewServeMux() + auth.NewHandler(svc, secureCookies).RegisterRoutes(mux) + + return env{mux: mux, svc: svc, clock: clock, pool: pool} +} + +func postJSON( + h http.Handler, + path, body string, + cookies ...*http.Cookie, +) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + for _, c := range cookies { + req.AddCookie(c) + } + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + return rec +} + +func sessionCookie(rec *httptest.ResponseRecorder) *http.Cookie { + for _, c := range rec.Result().Cookies() { + if c.Name == auth.SessionCookieName { + return c + } + } + + return nil +} + +func decodeMap(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { + t.Helper() + + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("body is not JSON: %v (%q)", err, rec.Body.String()) + } + + return body +} + +func TestRegisterEndpoint(t *testing.T) { + const path = "/api/v1/auth/register" + + t.Run("creates the account and returns it without secrets", func(t *testing.T) { + e := newEnv(t, true) + + rec := postJSON(e.mux, path, registerBody) + + if rec.Code != http.StatusCreated { + t.Fatalf("expected 201, got %d: %s", rec.Code, rec.Body.String()) + } + + body := decodeMap(t, rec) + for _, key := range []string{"user_id", "tenant_id"} { + id, _ := body[key].(string) + if _, err := uuid.Parse(id); err != nil { + t.Fatalf("%s is not a UUID: %v", key, body[key]) + } + } + if body["email"] != "alice@example.com" || body["role"] != "owner" { + t.Fatalf("unexpected body: %v", body) + } + // Exactly these four fields: no password, no hash, nothing else. + if len(body) != 4 { + t.Fatalf("expected 4 fields, got %v", body) + } + // Registering does not log the user in. + if sessionCookie(rec) != nil { + t.Fatal("register must not set a session cookie") + } + }) + + t.Run("invalid data answers 422 with the invalid fields", func(t *testing.T) { + e := newEnv(t, true) + + rec := postJSON(e.mux, path, `{"tenant_name":"","email":"nope","password":"short"}`) + + if rec.Code != http.StatusUnprocessableEntity { + t.Fatalf("expected 422, got %d", rec.Code) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/problem+json" { + t.Fatalf("unexpected content type %q", ct) + } + + fields, _ := decodeMap(t, rec)["errors"].(map[string]any) + for _, field := range []string{"email", "password", "tenant_name"} { + if _, ok := fields[field]; !ok { + t.Fatalf("expected an error for %q, got %v", field, fields) + } + } + }) + + t.Run("duplicate e-mail answers 409", func(t *testing.T) { + e := newEnv(t, true) + postJSON(e.mux, path, registerBody) + + rec := postJSON(e.mux, path, registerBody) + + if rec.Code != http.StatusConflict { + t.Fatalf("expected 409, got %d", rec.Code) + } + }) + + // A client must not be able to choose its own role. + t.Run("an unknown field such as role is rejected", func(t *testing.T) { + e := newEnv(t, true) + + rec := postJSON(e.mux, path, + `{"tenant_name":"Acme","email":"alice@example.com","password":"correct-horse-battery","role":"admin"}`) + + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", rec.Code) + } + if n := countRows(t, e.pool, "users"); n != 0 { + t.Fatalf("a rejected request created %d users", n) + } + }) + + t.Run("a non-JSON content type answers 415", func(t *testing.T) { + e := newEnv(t, true) + + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(registerBody)) + req.Header.Set("Content-Type", "text/plain") + rec := httptest.NewRecorder() + e.mux.ServeHTTP(rec, req) + + if rec.Code != http.StatusUnsupportedMediaType { + t.Fatalf("expected 415, got %d", rec.Code) + } + }) +} + +func TestLoginEndpoint(t *testing.T) { + const path = "/api/v1/auth/login" + + t.Run("sets a hardened session cookie and answers 204", func(t *testing.T) { + e := newEnv(t, true) + postJSON(e.mux, "/api/v1/auth/register", registerBody) + + rec := postJSON(e.mux, path, loginBody) + + if rec.Code != http.StatusNoContent || rec.Body.Len() != 0 { + t.Fatalf("expected an empty 204, got %d %q", rec.Code, rec.Body.String()) + } + if got := rec.Header().Get("Cache-Control"); got != "no-store" { + t.Fatalf("expected Cache-Control no-store, got %q", got) + } + + cookie := sessionCookie(rec) + if cookie == nil || cookie.Value == "" { + t.Fatal("expected a session cookie with a value") + } + if !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteLaxMode || cookie.Path != "/" { + t.Fatalf("cookie is not hardened: %+v", cookie) + } + if want := e.clock.now.Add(sessionTTL); !cookie.Expires.Equal(want) { + t.Fatalf("expected cookie expiry %v, got %v", want, cookie.Expires) + } + + // The cookie value is a working session. + account, err := e.svc.Authenticate(context.Background(), cookie.Value) + if err != nil || account.Email != "alice@example.com" { + t.Fatalf("cookie is not a valid session: %+v, %v", account, err) + } + }) + + t.Run("the Secure flag can be off for local HTTP development", func(t *testing.T) { + e := newEnv(t, false) + postJSON(e.mux, "/api/v1/auth/register", registerBody) + + cookie := sessionCookie(postJSON(e.mux, path, loginBody)) + + if cookie == nil || cookie.Secure || !cookie.HttpOnly { + t.Fatalf("expected HttpOnly without Secure, got %+v", cookie) + } + }) + + t.Run("wrong password and unknown e-mail look exactly the same", func(t *testing.T) { + e := newEnv(t, true) + postJSON(e.mux, "/api/v1/auth/register", registerBody) + + wrongPassword := postJSON(e.mux, path, + `{"email":"alice@example.com","password":"definitely-not-it-123"}`) + unknownEmail := postJSON(e.mux, path, + `{"email":"nobody@example.com","password":"correct-horse-battery"}`) + + for name, rec := range map[string]*httptest.ResponseRecorder{ + "wrong password": wrongPassword, + "unknown e-mail": unknownEmail, + } { + if rec.Code != http.StatusUnauthorized { + t.Fatalf("%s: expected 401, got %d", name, rec.Code) + } + if sessionCookie(rec) != nil { + t.Fatalf("%s: a failed login must not set a cookie", name) + } + } + if wrongPassword.Body.String() != unknownEmail.Body.String() { + t.Fatalf("bodies differ:\n%s\n%s", wrongPassword.Body, unknownEmail.Body) + } + }) +} + +func TestLogoutEndpoint(t *testing.T) { + const path = "/api/v1/auth/logout" + + t.Run("ends the session and clears the cookie", func(t *testing.T) { + e := newEnv(t, true) + postJSON(e.mux, "/api/v1/auth/register", registerBody) + login := sessionCookie(postJSON(e.mux, "/api/v1/auth/login", loginBody)) + + rec := postJSON(e.mux, path, "", login) + + if rec.Code != http.StatusNoContent { + t.Fatalf("expected 204, got %d", rec.Code) + } + + cleared := sessionCookie(rec) + if cleared == nil || cleared.Value != "" || cleared.MaxAge >= 0 { + t.Fatalf("expected the cookie to be cleared, got %+v", cleared) + } + + // The important part: the token is dead on the server too. + _, err := e.svc.Authenticate(context.Background(), login.Value) + if !errors.Is(err, auth.ErrUnauthenticated) { + t.Fatalf("expected ErrUnauthenticated after logout, got %v", err) + } + }) + + t.Run("without a cookie it still answers 204", func(t *testing.T) { + e := newEnv(t, true) + + rec := postJSON(e.mux, path, "") + + if rec.Code != http.StatusNoContent { + t.Fatalf("expected 204, got %d", rec.Code) + } + }) +} + +// failingService simulates a broken database: every call fails with an error +// that contains details that must never reach the client. +type failingService struct{} + +const secretDetail = "pq: password authentication failed for user app at 10.0.0.5" + +func (failingService) Register(context.Context, auth.RegisterInput) (auth.Account, error) { + return auth.Account{}, errors.New(secretDetail) +} + +func (failingService) Login(context.Context, auth.LoginInput) (auth.Session, error) { + return auth.Session{}, errors.New(secretDetail) +} + +func (failingService) Logout(context.Context, string) error { + return errors.New(secretDetail) +} + +func TestHandlersHideInternalErrors(t *testing.T) { + // The handlers log the real error; keep the test output clean. + log.SetOutput(io.Discard) + t.Cleanup(func() { log.SetOutput(os.Stderr) }) + + mux := http.NewServeMux() + auth.NewHandler(failingService{}, true).RegisterRoutes(mux) + + cases := []struct { + path string + body string + cookies []*http.Cookie + }{ + {"/api/v1/auth/register", registerBody, nil}, + {"/api/v1/auth/login", loginBody, nil}, + {"/api/v1/auth/logout", "", []*http.Cookie{{Name: auth.SessionCookieName, Value: "some-token"}}}, + } + + for _, tc := range cases { + t.Run(tc.path, func(t *testing.T) { + rec := postJSON(mux, tc.path, tc.body, tc.cookies...) + + if rec.Code != http.StatusInternalServerError { + t.Fatalf("expected 500, got %d", rec.Code) + } + if strings.Contains(rec.Body.String(), "10.0.0.5") || + strings.Contains(rec.Body.String(), "password authentication") { + t.Fatalf("internal error leaked to the client: %s", rec.Body.String()) + } + }) + } +} + +// keep the time import used even if sessionTTL moves elsewhere. +var _ = time.Second From f1c56e219623822084791357c81137a8a88de59b Mon Sep 17 00:00:00 2001 From: pitercoding Date: Tue, 24 Nov 2026 14:22:47 +0100 Subject: [PATCH 3/4] refactor(auth): build the session cookie in one place and satisfy linters --- backend/internal/auth/handler.go | 47 ++++++++++++--------------- backend/internal/auth/handler_test.go | 9 +++-- 2 files changed, 24 insertions(+), 32 deletions(-) diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.go index f64346e..1cc45d4 100644 --- a/backend/internal/auth/handler.go +++ b/backend/internal/auth/handler.go @@ -5,6 +5,7 @@ import ( "errors" "log" "net/http" + "time" "github.com/google/uuid" @@ -68,11 +69,9 @@ func (h *Handler) register(w http.ResponseWriter, r *http.Request) { return } - account, err := h.svc.Register(r.Context(), RegisterInput{ - TenantName: req.TenantName, - Email: req.Email, - Password: req.Password, - }) + // Converting (instead of copying field by field) makes the compiler check + // that both structs keep exactly the same fields. JSON tags are ignored. + account, err := h.svc.Register(r.Context(), RegisterInput(req)) var validationErr *ValidationError @@ -88,12 +87,9 @@ func (h *Handler) register(w http.ResponseWriter, r *http.Request) { default: w.Header().Set("Cache-Control", "no-store") - platform.WriteJSON(w, http.StatusCreated, accountResponse{ - UserID: account.UserID, - TenantID: account.TenantID, - Email: account.Email, - Role: account.Role, - }) + // Same idea: if Account ever gains a field (say, a password hash), + // this line stops compiling instead of leaking it through the API. + platform.WriteJSON(w, http.StatusCreated, accountResponse(account)) } } @@ -103,10 +99,7 @@ func (h *Handler) login(w http.ResponseWriter, r *http.Request) { return } - session, err := h.svc.Login(r.Context(), LoginInput{ - Email: req.Email, - Password: req.Password, - }) + session, err := h.svc.Login(r.Context(), LoginInput(req)) switch { case errors.Is(err, ErrInvalidCredentials): @@ -116,10 +109,7 @@ func (h *Handler) login(w http.ResponseWriter, r *http.Request) { writeInternalError(w, "login", err) default: - cookie := h.newCookie(session.Token) - cookie.Expires = session.ExpiresAt - - http.SetCookie(w, cookie) + h.setSessionCookie(w, session.Token, session.ExpiresAt, 0) w.Header().Set("Cache-Control", "no-store") w.WriteHeader(http.StatusNoContent) } @@ -136,26 +126,29 @@ func (h *Handler) logout(w http.ResponseWriter, r *http.Request) { } // MaxAge < 0 tells the browser to delete the cookie right away. - cleared := h.newCookie("") - cleared.MaxAge = -1 - - http.SetCookie(w, cleared) + h.setSessionCookie(w, "", time.Time{}, -1) w.WriteHeader(http.StatusNoContent) } -// newCookie builds the session cookie with every protection on: +// setSessionCookie is the only place that builds the session cookie, so its +// protections cannot be forgotten in one of the handlers: // - HttpOnly: JavaScript cannot read it, so an XSS cannot steal the session. // - Secure: only sent over HTTPS (off only for local HTTP development). // - SameSite=Lax: not sent on cross-site POSTs, the base of CSRF protection. -func (h *Handler) newCookie(value string) *http.Cookie { - return &http.Cookie{ +// +// A zero expires and zero maxAge make a session cookie; maxAge < 0 deletes it. +func (h *Handler) setSessionCookie(w http.ResponseWriter, value string, expires time.Time, maxAge int) { + //nolint:gosec // G124: Secure is configurable, false only for local HTTP development. + http.SetCookie(w, &http.Cookie{ Name: SessionCookieName, Value: value, Path: "/", + Expires: expires, + MaxAge: maxAge, HttpOnly: true, Secure: h.secureCookies, SameSite: http.SameSiteLaxMode, - } + }) } // writeInternalError logs the real error and tells the client nothing about it. diff --git a/backend/internal/auth/handler_test.go b/backend/internal/auth/handler_test.go index 6c14eb3..812eccf 100644 --- a/backend/internal/auth/handler_test.go +++ b/backend/internal/auth/handler_test.go @@ -11,7 +11,6 @@ import ( "os" "strings" "testing" - "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" @@ -308,6 +307,9 @@ func TestHandlersHideInternalErrors(t *testing.T) { mux := http.NewServeMux() auth.NewHandler(failingService{}, true).RegisterRoutes(mux) + // A cookie sent BY the client: Secure and HttpOnly only matter in responses. + clientCookie := &http.Cookie{Name: auth.SessionCookieName, Value: "some-token"} //nolint:gosec // G124: request cookie + cases := []struct { path string body string @@ -315,7 +317,7 @@ func TestHandlersHideInternalErrors(t *testing.T) { }{ {"/api/v1/auth/register", registerBody, nil}, {"/api/v1/auth/login", loginBody, nil}, - {"/api/v1/auth/logout", "", []*http.Cookie{{Name: auth.SessionCookieName, Value: "some-token"}}}, + {"/api/v1/auth/logout", "", []*http.Cookie{clientCookie}}, } for _, tc := range cases { @@ -332,6 +334,3 @@ func TestHandlersHideInternalErrors(t *testing.T) { }) } } - -// keep the time import used even if sessionTTL moves elsewhere. -var _ = time.Second From 95e9f745191a4c2e94d527536c17cb969810ba7a Mon Sep 17 00:00:00 2001 From: pitercoding Date: Tue, 24 Nov 2026 14:33:24 +0100 Subject: [PATCH 4/4] feat(auth): add authentication middleware and GET /me --- backend/internal/auth/handler.go | 18 +++ backend/internal/auth/handler_test.go | 104 +++++++++++++++++ backend/internal/auth/middleware.go | 67 +++++++++++ backend/internal/auth/middleware_test.go | 139 +++++++++++++++++++++++ 4 files changed, 328 insertions(+) create mode 100644 backend/internal/auth/middleware.go create mode 100644 backend/internal/auth/middleware_test.go diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.go index 1cc45d4..394564e 100644 --- a/backend/internal/auth/handler.go +++ b/backend/internal/auth/handler.go @@ -22,6 +22,7 @@ type authService interface { Register(ctx context.Context, in RegisterInput) (Account, error) Login(ctx context.Context, in LoginInput) (Session, error) Logout(ctx context.Context, token string) error + Authenticate(ctx context.Context, token string) (Account, error) } // Handler exposes the auth use cases over HTTP. @@ -41,6 +42,9 @@ func (h *Handler) RegisterRoutes(mux *http.ServeMux) { mux.HandleFunc("POST /api/v1/auth/register", h.register) mux.HandleFunc("POST /api/v1/auth/login", h.login) mux.HandleFunc("POST /api/v1/auth/logout", h.logout) + + // The only route here that needs a session. + mux.Handle("GET /api/v1/me", RequireAuth(h.svc)(http.HandlerFunc(h.me))) } // Request and response bodies live here, not in Service: the service knows @@ -130,6 +134,20 @@ func (h *Handler) logout(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } +// me returns the account of the logged-in user. +func (h *Handler) me(w http.ResponseWriter, r *http.Request) { + account, ok := AccountFrom(r.Context()) + if !ok { + // Cannot happen behind RequireAuth. If someone ever registers this + // route without it, failing closed beats a zero-value account. + writeUnauthorized(w) + + return + } + + platform.WriteJSON(w, http.StatusOK, accountResponse(account)) +} + // setSessionCookie is the only place that builds the session cookie, so its // protections cannot be forgotten in one of the handlers: // - HttpOnly: JavaScript cannot read it, so an XSS cannot steal the session. diff --git a/backend/internal/auth/handler_test.go b/backend/internal/auth/handler_test.go index 812eccf..f03558c 100644 --- a/backend/internal/auth/handler_test.go +++ b/backend/internal/auth/handler_test.go @@ -9,6 +9,7 @@ import ( "net/http" "net/http/httptest" "os" + "reflect" "strings" "testing" @@ -299,6 +300,10 @@ func (failingService) Logout(context.Context, string) error { return errors.New(secretDetail) } +func (failingService) Authenticate(context.Context, string) (auth.Account, error) { + return auth.Account{}, errors.New(secretDetail) +} + func TestHandlersHideInternalErrors(t *testing.T) { // The handlers log the real error; keep the test output clean. log.SetOutput(io.Discard) @@ -334,3 +339,102 @@ func TestHandlersHideInternalErrors(t *testing.T) { }) } } + +// getMe calls GET /api/v1/me. An empty token means no cookie at all. +func getMe(h http.Handler, token string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/api/v1/me", nil) + if token != "" { + req.Header.Set("Cookie", auth.SessionCookieName+"="+token) + } + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + return rec +} + +func TestMeEndpoint(t *testing.T) { + t.Run("returns the logged-in account", func(t *testing.T) { + e := newEnv(t, true) + registered := decodeMap(t, postJSON(e.mux, "/api/v1/auth/register", registerBody)) + token := sessionCookie(postJSON(e.mux, "/api/v1/auth/login", loginBody)).Value + + rec := getMe(e.mux, token) + + if rec.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String()) + } + // Same four fields the signup returned: user, tenant, e-mail, role. + if got := decodeMap(t, rec); !reflect.DeepEqual(got, registered) { + t.Fatalf("expected %v, got %v", registered, got) + } + if cc := rec.Header().Get("Cache-Control"); cc != "no-store" { + t.Fatalf("expected Cache-Control no-store, got %q", cc) + } + }) + + t.Run("without a cookie answers 401", func(t *testing.T) { + e := newEnv(t, true) + + if rec := getMe(e.mux, ""); rec.Code != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", rec.Code) + } + }) + + t.Run("an unknown cookie answers 401", func(t *testing.T) { + e := newEnv(t, true) + + if rec := getMe(e.mux, "not-a-real-token"); rec.Code != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", rec.Code) + } + }) + + t.Run("after logout the same cookie answers 401", func(t *testing.T) { + e := newEnv(t, true) + postJSON(e.mux, "/api/v1/auth/register", registerBody) + login := sessionCookie(postJSON(e.mux, "/api/v1/auth/login", loginBody)) + + postJSON(e.mux, "/api/v1/auth/logout", "", login) + + if rec := getMe(e.mux, login.Value); rec.Code != http.StatusUnauthorized { + t.Fatalf("expected 401 after logout, got %d", rec.Code) + } + }) + + t.Run("an expired session answers 401", func(t *testing.T) { + e := newEnv(t, true) + postJSON(e.mux, "/api/v1/auth/register", registerBody) + token := sessionCookie(postJSON(e.mux, "/api/v1/auth/login", loginBody)).Value + + e.clock.Advance(sessionTTL) + + if rec := getMe(e.mux, token); rec.Code != http.StatusUnauthorized { + t.Fatalf("expected 401 after expiry, got %d", rec.Code) + } + }) + + // The tenant comes from the database through the session, never from the + // request, so two users can never see each other's data. + t.Run("each user sees only their own account and tenant", func(t *testing.T) { + e := newEnv(t, true) + const ( + bobRegister = `{"tenant_name":"Bob GmbH","email":"bob@example.com","password":"correct-horse-battery"}` + bobLogin = `{"email":"bob@example.com","password":"correct-horse-battery"}` + ) + + alice := decodeMap(t, postJSON(e.mux, "/api/v1/auth/register", registerBody)) + bob := decodeMap(t, postJSON(e.mux, "/api/v1/auth/register", bobRegister)) + aliceToken := sessionCookie(postJSON(e.mux, "/api/v1/auth/login", loginBody)).Value + bobToken := sessionCookie(postJSON(e.mux, "/api/v1/auth/login", bobLogin)).Value + + gotAlice := decodeMap(t, getMe(e.mux, aliceToken)) + gotBob := decodeMap(t, getMe(e.mux, bobToken)) + + if !reflect.DeepEqual(gotAlice, alice) || !reflect.DeepEqual(gotBob, bob) { + t.Fatalf("accounts mixed up:\nalice: %v\nbob: %v", gotAlice, gotBob) + } + if gotAlice["tenant_id"] == gotBob["tenant_id"] { + t.Fatal("alice and bob must be in different tenants") + } + }) +} diff --git a/backend/internal/auth/middleware.go b/backend/internal/auth/middleware.go new file mode 100644 index 0000000..b1166b2 --- /dev/null +++ b/backend/internal/auth/middleware.go @@ -0,0 +1,67 @@ +package auth + +import ( + "context" + "errors" + "net/http" + + "github.com/pitercoding/aktenlens/backend/internal/platform" +) + +// authenticator is the part of Service the middleware needs. +type authenticator interface { + Authenticate(ctx context.Context, token string) (Account, error) +} + +// accountKey is the context key. It is an unexported type, so no other +// package can read or overwrite the value by accident. +type accountKey struct{} + +// AccountFrom returns the account that RequireAuth stored in the context. +// The second result is false when the request did not go through RequireAuth. +func AccountFrom(ctx context.Context) (Account, bool) { + account, ok := ctx.Value(accountKey{}).(Account) + + return account, ok +} + +// RequireAuth protects a handler: without a valid session cookie the request +// is answered with 401 and the handler never runs. With one, the handler can +// call AccountFrom(r.Context()) to know who is calling and for which tenant. +// +// The tenant comes from the database (through the session), never from the +// request, so a client cannot choose someone else's tenant. +func RequireAuth(svc authenticator) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie(SessionCookieName) + if err != nil { + writeUnauthorized(w) + + return + } + + account, err := svc.Authenticate(r.Context(), cookie.Value) + + switch { + case errors.Is(err, ErrUnauthenticated): + // Missing, unknown, expired and logged-out sessions all look the same. + writeUnauthorized(w) + + case err != nil: + writeInternalError(w, "authenticate", err) + + default: + // Private data: no shared cache may keep this response. + w.Header().Set("Cache-Control", "no-store") + + ctx := context.WithValue(r.Context(), accountKey{}, account) + next.ServeHTTP(w, r.WithContext(ctx)) + } + }) + } +} + +func writeUnauthorized(w http.ResponseWriter) { + platform.WriteProblem(w, http.StatusUnauthorized, "authentication required") +} diff --git a/backend/internal/auth/middleware_test.go b/backend/internal/auth/middleware_test.go new file mode 100644 index 0000000..4020b23 --- /dev/null +++ b/backend/internal/auth/middleware_test.go @@ -0,0 +1,139 @@ +package auth_test + +import ( + "context" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/google/uuid" + + "github.com/pitercoding/aktenlens/backend/internal/auth" +) + +// stubAuthenticator replaces the real service: it returns what the test wants +// and remembers how it was called. +type stubAuthenticator struct { + account auth.Account + err error + calls int + token string +} + +func (s *stubAuthenticator) Authenticate(_ context.Context, token string) (auth.Account, error) { + s.calls++ + s.token = token + + return s.account, s.err +} + +func TestRequireAuth(t *testing.T) { + // The middleware logs unexpected errors; keep the test output clean. + log.SetOutput(io.Discard) + t.Cleanup(func() { log.SetOutput(os.Stderr) }) + + want := auth.Account{ + UserID: uuid.New(), + TenantID: uuid.New(), + Email: "alice@example.com", + Role: "admin", + } + + // run sends one request through the middleware. cookieValue "" means no + // cookie. It reports the response, what the next handler saw, and whether + // the next handler ran at all. + run := func(stub *stubAuthenticator, cookieValue string) ( + rec *httptest.ResponseRecorder, got auth.Account, reached bool, + ) { + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reached = true + got, _ = auth.AccountFrom(r.Context()) + w.WriteHeader(http.StatusOK) + }) + + req := httptest.NewRequest(http.MethodGet, "/", nil) + if cookieValue != "" { + req.Header.Set("Cookie", auth.SessionCookieName+"="+cookieValue) + } + + rec = httptest.NewRecorder() + auth.RequireAuth(stub)(next).ServeHTTP(rec, req) + + return rec, got, reached + } + + t.Run("a valid session reaches the handler with the account", func(t *testing.T) { + stub := &stubAuthenticator{account: want} + + rec, got, reached := run(stub, "tok-123") + + if !reached || rec.Code != http.StatusOK { + t.Fatalf("expected the handler to run, got %d (reached=%v)", rec.Code, reached) + } + if got != want { + t.Fatalf("expected account %+v, got %+v", want, got) + } + if stub.token != "tok-123" { + t.Fatalf("expected the cookie value to be authenticated, got %q", stub.token) + } + if cc := rec.Header().Get("Cache-Control"); cc != "no-store" { + t.Fatalf("expected Cache-Control no-store, got %q", cc) + } + }) + + t.Run("no cookie answers 401 without asking the service", func(t *testing.T) { + stub := &stubAuthenticator{account: want} + + rec, _, reached := run(stub, "") + + if reached || rec.Code != http.StatusUnauthorized { + t.Fatalf("expected 401 and no handler, got %d (reached=%v)", rec.Code, reached) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/problem+json" { + t.Fatalf("unexpected content type %q", ct) + } + if stub.calls != 0 { + t.Fatalf("the service must not be called without a cookie, got %d calls", stub.calls) + } + }) + + t.Run("an unauthenticated session answers 401", func(t *testing.T) { + for name, err := range map[string]error{ + "plain": auth.ErrUnauthenticated, + "wrapped": fmt.Errorf("lookup: %w", auth.ErrUnauthenticated), + } { + stub := &stubAuthenticator{err: err} + + rec, _, reached := run(stub, "expired-token") + + if reached || rec.Code != http.StatusUnauthorized { + t.Fatalf("%s: expected 401 and no handler, got %d (reached=%v)", name, rec.Code, reached) + } + } + }) + + t.Run("an unexpected error answers 500 and hides the details", func(t *testing.T) { + stub := &stubAuthenticator{err: errors.New(secretDetail)} + + rec, _, reached := run(stub, "tok-123") + + if reached || rec.Code != http.StatusInternalServerError { + t.Fatalf("expected 500 and no handler, got %d (reached=%v)", rec.Code, reached) + } + if strings.Contains(rec.Body.String(), "10.0.0.5") { + t.Fatalf("internal error leaked to the client: %s", rec.Body.String()) + } + }) +} + +func TestAccountFromWithoutMiddleware(t *testing.T) { + if _, ok := auth.AccountFrom(context.Background()); ok { + t.Fatal("a plain context must not contain an account") + } +}