feat(api): declare identity contract for registration, verification, and sessions
This commit is contained in:
1 parent
197661145e
commit
653f3775f8
86 files changed
+11826
-148
No files matched your search
@@ -106,6 +106,311 @@ func TestPublicUnimplementedOperationReturnsNotImplementedProblem(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
// Identity request fixtures shared by the router tests.
|
||||
const (
|
||||
testSessionCookie = "__Host-lincodex_session=opaque-session-value"
|
||||
testCSRFToken = "Xk4pR9tV2mQ7wL1sN8bC5dF0gH3jZ6yA9eU2iO7rT4c"
|
||||
testIdempotencyKey = "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11"
|
||||
registrationPath = "/api/v1/identity/registrations"
|
||||
currentSessionPath = "/api/v1/identity/sessions/current"
|
||||
)
|
||||
|
||||
// registrationBody returns a valid RegisterAccount body with replaced parts.
|
||||
func registrationBody(password, consent string) string {
|
||||
return `{"email":"candidate@example.com","password":"` + password + `","scenario":"candidate","consent_c1":` + consent + `}`
|
||||
}
|
||||
|
||||
const (
|
||||
validPassword = "correct horse battery staple"
|
||||
validConsent = `{"text_version":"c1-2026-10-01","accepted":true}`
|
||||
)
|
||||
|
||||
type identityRequest struct {
|
||||
method string
|
||||
path string
|
||||
body string
|
||||
headers map[string]string
|
||||
}
|
||||
|
||||
func serveIdentityRequest(t *testing.T, router http.Handler, request identityRequest) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
httpRequest := httptest.NewRequest(request.method, request.path, strings.NewReader(request.body))
|
||||
if request.body != "" {
|
||||
httpRequest.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for name, value := range request.headers {
|
||||
httpRequest.Header.Set(name, value)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httpRequest)
|
||||
return response
|
||||
}
|
||||
|
||||
// Identity operations are in the contract before their business logic. Public
|
||||
// ones must answer 501 only after request validation, and session-protected
|
||||
// ones must stay closed: DenyAllSecurity grants no session, with or without a
|
||||
// cookie and a CSRF token.
|
||||
func TestIdentityOperationsBeforeImplementation(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
request identityRequest
|
||||
statusCode int
|
||||
code api.ProblemCode
|
||||
}{
|
||||
{
|
||||
name: "public registration",
|
||||
request: identityRequest{
|
||||
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
|
||||
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
|
||||
},
|
||||
statusCode: http.StatusNotImplemented,
|
||||
code: api.ProblemCodeNotImplemented,
|
||||
},
|
||||
{
|
||||
name: "public email verification resend",
|
||||
request: identityRequest{
|
||||
method: http.MethodPost, path: "/api/v1/identity/email-verification-requests",
|
||||
body: `{"email":"candidate@example.com"}`,
|
||||
},
|
||||
statusCode: http.StatusNotImplemented,
|
||||
code: api.ProblemCodeNotImplemented,
|
||||
},
|
||||
{
|
||||
name: "public email confirmation",
|
||||
request: identityRequest{
|
||||
method: http.MethodPost, path: "/api/v1/identity/email-verifications",
|
||||
body: `{"token":"q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE"}`,
|
||||
},
|
||||
statusCode: http.StatusNotImplemented,
|
||||
code: api.ProblemCodeNotImplemented,
|
||||
},
|
||||
{
|
||||
name: "public login",
|
||||
request: identityRequest{
|
||||
method: http.MethodPost, path: "/api/v1/identity/sessions",
|
||||
body: `{"email":"candidate@example.com","password":"correct horse battery staple"}`,
|
||||
},
|
||||
statusCode: http.StatusNotImplemented,
|
||||
code: api.ProblemCodeNotImplemented,
|
||||
},
|
||||
{
|
||||
name: "public consent text",
|
||||
request: identityRequest{method: http.MethodGet, path: "/api/v1/identity/consent-texts/c1"},
|
||||
statusCode: http.StatusNotImplemented,
|
||||
code: api.ProblemCodeNotImplemented,
|
||||
},
|
||||
{
|
||||
name: "current account without a session cookie",
|
||||
request: identityRequest{method: http.MethodGet, path: "/api/v1/identity/me"},
|
||||
statusCode: http.StatusUnauthorized,
|
||||
code: api.ProblemCodeUnauthenticated,
|
||||
},
|
||||
{
|
||||
name: "current account with a session cookie",
|
||||
request: identityRequest{
|
||||
method: http.MethodGet, path: "/api/v1/identity/me",
|
||||
headers: map[string]string{"Cookie": testSessionCookie},
|
||||
},
|
||||
statusCode: http.StatusUnauthorized,
|
||||
code: api.ProblemCodeUnauthenticated,
|
||||
},
|
||||
{
|
||||
name: "current session without a session cookie",
|
||||
request: identityRequest{method: http.MethodGet, path: currentSessionPath},
|
||||
statusCode: http.StatusUnauthorized,
|
||||
code: api.ProblemCodeUnauthenticated,
|
||||
},
|
||||
{
|
||||
name: "logout with a session cookie and a CSRF token",
|
||||
request: identityRequest{
|
||||
method: http.MethodDelete, path: currentSessionPath,
|
||||
headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken},
|
||||
},
|
||||
statusCode: http.StatusUnauthorized,
|
||||
code: api.ProblemCodeUnauthenticated,
|
||||
},
|
||||
{
|
||||
name: "logout with only a CSRF token",
|
||||
request: identityRequest{
|
||||
method: http.MethodDelete, path: currentSessionPath,
|
||||
headers: map[string]string{"X-CSRF-Token": testCSRFToken},
|
||||
},
|
||||
statusCode: http.StatusUnauthorized,
|
||||
code: api.ProblemCodeUnauthenticated,
|
||||
},
|
||||
{
|
||||
name: "logout with only a session cookie",
|
||||
request: identityRequest{
|
||||
method: http.MethodDelete, path: currentSessionPath,
|
||||
headers: map[string]string{"Cookie": testSessionCookie},
|
||||
},
|
||||
statusCode: http.StatusUnauthorized,
|
||||
code: api.ProblemCodeUnauthenticated,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
router := newTestRouter(t, func(context.Context) error { return nil })
|
||||
response := serveIdentityRequest(t, router, test.request)
|
||||
|
||||
requireProblem(t, response, test.statusCode, test.code)
|
||||
if cookie := response.Header().Get("Set-Cookie"); test.statusCode == http.StatusNotImplemented && cookie != "" {
|
||||
t.Fatalf("Set-Cookie = %q, want none from an unimplemented operation", cookie)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The security handler does not affect operations without security.
|
||||
router := newTestRouter(t, func(context.Context) error { return nil })
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("healthz status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Registration rejects invalid requests with 400 before the 501 of the
|
||||
// missing business logic, with pointers to the failing fields.
|
||||
func TestRegistrationValidationPrecedesImplementation(t *testing.T) {
|
||||
const fourteenCharacters = "fourteen-chars"
|
||||
withKey := map[string]string{"Idempotency-Key": testIdempotencyKey}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
body string
|
||||
headers map[string]string
|
||||
location api.ProblemFieldLocation
|
||||
pointer string
|
||||
code string
|
||||
}{
|
||||
{
|
||||
// Unknown fields are rejected, so no other consent, such as C4,
|
||||
// can be given at registration.
|
||||
name: "consent C4 at registration",
|
||||
body: `{"email":"candidate@example.com","password":"` + validPassword + `","scenario":"candidate","consent_c1":` + validConsent + `,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true}}`,
|
||||
headers: withKey,
|
||||
location: api.ProblemFieldLocationBody,
|
||||
pointer: "",
|
||||
code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "consent C1 not accepted",
|
||||
body: registrationBody(validPassword, `{"text_version":"c1-2026-10-01","accepted":false}`),
|
||||
headers: withKey,
|
||||
location: api.ProblemFieldLocationBody,
|
||||
pointer: "/consent_c1/accepted",
|
||||
code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "password shorter than 15 characters",
|
||||
body: registrationBody(fourteenCharacters, validConsent),
|
||||
headers: withKey,
|
||||
location: api.ProblemFieldLocationBody,
|
||||
pointer: "/password",
|
||||
code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "missing Idempotency-Key",
|
||||
body: registrationBody(validPassword, validConsent),
|
||||
location: api.ProblemFieldLocationHeader,
|
||||
pointer: "/Idempotency-Key",
|
||||
code: "required",
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
router := newTestRouter(t, func(context.Context) error { return nil })
|
||||
response := serveIdentityRequest(t, router, identityRequest{
|
||||
method: http.MethodPost, path: registrationPath, body: test.body, headers: test.headers,
|
||||
})
|
||||
|
||||
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
|
||||
want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code}
|
||||
for _, field := range body.Errors {
|
||||
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// sessionPrincipalKey marks the context returned by HandleSessionCookie.
|
||||
type sessionPrincipalKey struct{}
|
||||
|
||||
// recordingSecurity accepts every scheme value and records the order of the
|
||||
// calls and whether HandleSessionCsrf saw the context of HandleSessionCookie.
|
||||
type recordingSecurity struct {
|
||||
calls []string
|
||||
csrfSawPrincipal bool
|
||||
}
|
||||
|
||||
func (security *recordingSecurity) HandleSessionCookie(ctx context.Context, _ api.OperationName, _ api.SessionCookie) (context.Context, error) {
|
||||
security.calls = append(security.calls, "SessionCookie")
|
||||
return context.WithValue(ctx, sessionPrincipalKey{}, "principal"), nil
|
||||
}
|
||||
|
||||
func (security *recordingSecurity) HandleSessionCsrf(ctx context.Context, _ api.OperationName, _ api.SessionCsrf) (context.Context, error) {
|
||||
security.calls = append(security.calls, "SessionCsrf")
|
||||
security.csrfSawPrincipal = ctx.Value(sessionPrincipalKey{}) != nil
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// The session-bound CSRF check of TASK-056 relies on the generated server
|
||||
// calling HandleSessionCookie before HandleSessionCsrf and passing the
|
||||
// returned context on. ogen orders the calls by scheme name, so renaming a
|
||||
// scheme or upgrading ogen must keep this test green.
|
||||
func TestGeneratedServerSecurityOrder(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
headers map[string]string
|
||||
calls []string
|
||||
csrfSawPrincipal bool
|
||||
statusCode int
|
||||
}{
|
||||
{
|
||||
name: "cookie and CSRF token",
|
||||
headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken},
|
||||
calls: []string{"SessionCookie", "SessionCsrf"},
|
||||
csrfSawPrincipal: true,
|
||||
statusCode: http.StatusNotImplemented,
|
||||
},
|
||||
{
|
||||
// Without a cookie HandleSessionCsrf still runs, with the
|
||||
// original context, and the unsatisfied requirement answers 401.
|
||||
name: "CSRF token without a cookie",
|
||||
headers: map[string]string{"X-CSRF-Token": testCSRFToken},
|
||||
calls: []string{"SessionCsrf"},
|
||||
statusCode: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "cookie without a CSRF token",
|
||||
headers: map[string]string{"Cookie": testSessionCookie},
|
||||
calls: []string{"SessionCookie"},
|
||||
statusCode: http.StatusUnauthorized,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
security := &recordingSecurity{}
|
||||
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
response := serveIdentityRequest(t, router, identityRequest{method: http.MethodDelete, path: currentSessionPath, headers: test.headers})
|
||||
|
||||
if response.Code != test.statusCode {
|
||||
t.Fatalf("status code = %d, want %d: %s", response.Code, test.statusCode, response.Body.String())
|
||||
}
|
||||
if fmt.Sprint(security.calls) != fmt.Sprint(test.calls) {
|
||||
t.Fatalf("security calls = %v, want %v", security.calls, test.calls)
|
||||
}
|
||||
if security.csrfSawPrincipal != test.csrfSawPrincipal {
|
||||
t.Fatalf("HandleSessionCsrf saw the session context = %t, want %t", security.csrfSawPrincipal, test.csrfSawPrincipal)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&logs, nil))
|
||||
@@ -154,7 +459,7 @@ func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) {
|
||||
getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) },
|
||||
}
|
||||
recorder := &requestRecorder{}
|
||||
router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), recorder, logger)
|
||||
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
@@ -331,7 +636,7 @@ func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler {
|
||||
|
||||
func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler {
|
||||
t.Helper()
|
||||
router, err := NewRouter(healthHandler, apiHandler, problem.NewResponder(logger), metrics.New(), logger)
|
||||
router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
@@ -343,7 +648,7 @@ func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getH
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz}
|
||||
router, err := NewRouter(healthHandler, handler, problem.NewResponder(logger), collector, logger)
|
||||
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user