Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: completed the server api
=b9aaf8507246
diff --git a/backend-go/pkg/api/README.md b/backend-go/pkg/api/README.mdindex d65b65e985..7e1c48414c 100644--- a/backend-go/pkg/api/README.md+++ b/backend-go/pkg/api/README.md@@ -5,25 +5,181 @@ Type-safe API framework with pointer-binding schemas. Single source of truth for## Quick Start```go+// Request type (pointer receiver for Schema)type CreateUserRequest struct {Name string `json:"name"`Email string `json:"email"`- Age int `json:"age"`}func (r *CreateUserRequest) Schema() *api.ObjectSchema {return api.Object(map[string]api.Schema{"name": api.String(&r.Name).Required().MinLength(1).MaxLength(100),"email": api.String(&r.Email).Required().Email(),- "age": api.Int(&r.Age).Optional().Min(0).Max(150),})}-// Validate-errs := req.Schema().Validate()+// Response type (pointer receiver for Schema AND Status)+type UserResponse struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Email string `json:"email"`+}++func (r *UserResponse) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "id": api.String(&r.ID).Required(),+ "name": api.String(&r.Name).Required(),+ "email": api.String(&r.Email).Required(),+ })+}++func (*UserResponse) Status() int { return http.StatusCreated }++// Handler returns VALUE type (not pointer)+func createUser(ctx context.Context, req *CreateUserRequest) (UserResponse, error) {+ return UserResponse{ID: "123", Name: req.Name, Email: req.Email}, nil+}++// Registration with builder+r.POST("/users", api.Handler(app, createUser).+ Summary("Create user").+ OperationID("createUser"))+```++## Typed Responses++Handlers return **value types**, response types use **pointer receiver methods**.++```go+// Response type — embed status mixin to avoid writing Status()+type UserResponse struct {+ api.StatusOK // embeds Status() int { return 200 }+ ID string `json:"id"`+}++func (r *UserResponse) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "id": api.String(&r.ID).Required(),+ })+}++// Handler returns VALUE (not pointer)+func getUser(ctx context.Context, req *GetUserRequest) (UserResponse, error) {+ return UserResponse{ID: "123"}, nil+}++// No-content response (204)+type Deleted struct{ api.StatusNoContent }++func (*Deleted) Schema() *api.ObjectSchema { return nil }++func deleteUser(ctx context.Context, req *DeleteRequest) (Deleted, error) {+ return Deleted{}, nil+}+```++### Status Mixins++Embed these instead of writing `Status()` manually:++```go+api.StatusOK // 200+api.StatusCreated // 201+api.StatusAccepted // 202+api.StatusNoContent // 204+api.StatusBadRequest // 400+api.StatusUnauthorized // 401+api.StatusForbidden // 403+api.StatusNotFound // 404+api.StatusConflict // 409+api.StatusUnprocessableEntity // 422+api.StatusInternalServerError // 500+```++### Multi-Status Responses (InterfaceHandler)++For handlers returning different response types at runtime:++```go+// Marker interface+type CreateOrFetchResult interface {+ api.TypedResponse+ marker()+}++// Variant 1 — 201 Created+type CreatedUser struct { ID string }+func (r *CreatedUser) Schema() *api.ObjectSchema { ... }+func (*CreatedUser) Status() int { return 201 }+func (*CreatedUser) marker() {}++// Variant 2 — 200 OK+type ExistingUser struct { ID string }+func (r *ExistingUser) Schema() *api.ObjectSchema { ... }+func (*ExistingUser) Status() int { return 200 }+func (*ExistingUser) marker() {}++// Handler returns interface+func createOrFetch(ctx context.Context, req *Request) (CreateOrFetchResult, error) {+ if existed {+ return &ExistingUser{ID: id}, nil+ }+ return &CreatedUser{ID: id}, nil+}++// Use InterfaceHandler + declare all variants+r.POST("/users", api.InterfaceHandler(app, createOrFetch).+ Responses(&CreatedUser{}, &ExistingUser{}))+```++## Handler Builder++```go+r.GET("/users/{id}", api.Handler(app, getUser).+ Summary("Get user").+ Description("Retrieves a user by ID").+ OperationID("getUser").+ Tags("Users").+ Security(api.NewSecurity("jwt")).+ Deprecated())++// Additional responses (e.g., error types for OpenAPI)+r.POST("/users", api.Handler(app, createUser).+ Responses(&ConflictError{}). // Add 409 to OpenAPI+ WithoutDefault(401, 403)) // Remove inherited defaults+```++## Router++```go+// 1. Create security registry with validators+registry := api.NewSecurityRegistry()+registry.MustRegister("bearer", api.HTTPBearerJWT(), &JWTValidator{})+registry.MustRegister("apiKey", api.APIKeyHeader("X-API-Key"), &APIKeyValidator{})++// 2. Create app with registry — enables unified WithSecurity+app := api.NewApp(api.AppConfig{+ ErrorHandler: errorHandler,+ DefaultResponses: []api.TypedResponse{&ValidationError{}, &InternalError{}},+ SecurityRegistry: registry, // enables WithSecurity to auto-install middleware+})++router := api.NewRouter(api.RouterConfig{App: app})+router.Use(loggingMiddleware)++router.Route("/v1/orgs/{orgId}", func(r *api.Router) {+ // WithSecurity now does BOTH: OpenAPI doc + middleware (one call!)+ r.WithSecurity(api.NewSecurity("bearer"), api.NewSecurity("apiKey"))+ r.WithTags("Organizations")+ r.WithDefaultResponses(&Unauthorized{}, &Forbidden{})++ r.GET("/users", api.Handler(app, listUsers).Summary("List users"))+ r.POST("/users", api.Handler(app, createUser).Summary("Create user"))+})// Generate OpenAPI-openapi := req.Schema().OpenAPI()+spec := router.Spec()+jsonSpec := spec.Generate()```## Schema Types@@ -38,53 +194,74 @@ api.Bool(&b).Required()api.UUID(&u).Required()api.Time(&t).Required()api.Bytes(&b).Required().MinLength(1)-api.Any(&a).Required()-api.Raw(&r).Required()```### Composites```go-// Objectapi.Object(map[string]api.Schema{...}).Required()+api.Array(api.String(nil)).Required().MinItems(1).MaxItems(10)+api.Map(api.String(nil)).Required()+api.Const("fixed-value")+```-// Array-api.Array(api.String(new(string))).Required().MinItems(1).MaxItems(10)+### Component Refs ($ref)-// Map (string keys)-api.Map(api.String(new(string))).Required()+Define reusable schemas that appear in `components/schemas`:-// Reference-api.Ref("#/components/schemas/User")+```go+// Shared schema — .Ref() registers it and makes OpenAPI() return $ref+type User struct {+ ID uuid.UUID `json:"id"`+ Name string `json:"name"`+}-// Const-api.Const("fixed-value")+func (u *User) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "id": api.UUID(&u.ID).Required(),+ "name": api.String(&u.Name).Required(),+ }).Ref("User") // Registers in components/schemas+}++// Use it — calling Schema() triggers registration and returns $ref+type ListResponse struct {+ Users []User `json:"users"`+}++func (r *ListResponse) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "users": api.Array((&User{}).Schema()).Required(), // → {"$ref": "#/components/schemas/User"}+ })+}+```++### Parameter Sources++```go+api.String(&r.ID).From(api.SourcePath).Required().UUID()+api.Int(&r.Page).From(api.SourceQuery).Optional().Default(1)+api.String(&r.Token).From(api.SourceHeader).Required()+api.String(&r.SessionID).From(api.SourceCookie).Required()```## Union Types### Flat Discriminated Union-```json-{"type": "dog", "breed": "Labrador"}-```-```go-// 1. Define interface + variantstype Animal interface {api.UnionanimalMarker()}type Dog struct {+ api.UnionBaseType string `json:"type"`Breed string `json:"breed"`}-func (d *Dog) Schema() *api.ObjectSchema { return api.Object(map[string]api.Schema{...}) }-func (d *Dog) unionMarker() {}+func (d *Dog) Schema() *api.ObjectSchema { ... }func (d *Dog) animalMarker() {}-// 2. Define parservar AnimalParser = api.UnionDef[Animal]{Discriminator: "type",Variants: map[string]func() Animal{@@ -93,193 +270,60 @@ var AnimalParser = api.UnionDef[Animal]{},}-// 3. Use in request (single-pass with json.RawMessage)-type Request struct {- PetRaw json.RawMessage `json:"pet"`- Pet Animal `json:"-"`-}--func (r *Request) UnmarshalJSON(data []byte) error {- type Plain Request- if err := json.Unmarshal(data, (*Plain)(r)); err != nil {- return err- }- return api.ParseUnionField(r.PetRaw, &r.Pet, AnimalParser)-}+// In request schema+"pet": api.UnionField(&r.Pet, AnimalParser).Required()-func (r *Request) Schema() *api.ObjectSchema {- return api.Object(map[string]api.Schema{- "pet": api.UnionField(&r.Pet, AnimalParser).Required(),- })-}-```--### Nested Discriminated Union--```json-{"method": "password", "payload": {"username": "john", "password": "secret"}}-```--```go-var AuthParser = api.NestedUnionDef[AuthMethod]{- Discriminator: "method",- PayloadField: "payload",- Variants: map[string]func() AuthMethod{- "password": func() AuthMethod { return &PasswordPayload{} },- "oauth": func() AuthMethod { return &OAuthPayload{} },- },-}--// Parse from separate fields-api.ParseNestedUnionField(r.MethodRaw, r.PayloadRaw, &r.Auth, AuthParser)+// Parse in UnmarshalJSON+api.ParseUnions(data, api.U("pet", &r.Pet, AnimalParser))```### OneOf / AnyOf```go-// OneOf - exactly one must be present-api.OneOfSchemas(- api.String(&v.Plaintext),- v.Reference.Schema(),-).Required()--// AnyOf - at least one must be present-api.AnyOf(- emailConfig.Schema(),- slackConfig.Schema(),-).Required()--// AllOf - all must be valid (composition)-api.AllOf(- auditFields.Schema(),- deleteFields.Schema(),-)+api.OneOfSchemas(api.String(&v.A), api.String(&v.B)).Required()+api.AnyOf(schemaA, schemaB).Required()+api.AllOf(schemaA, schemaB)```## Authentication```go-// 1. Define schemes (OpenAPI metadata)-var UserJWTScheme = api.HTTPBearerJWT().WithDescription("User JWT")-var APIKeyScheme = api.APIKeyHeader("X-API-Key").WithDescription("API Key")--// 2. Implement validators-type JWTValidator struct {- db pg.DB- keyStore kms.KeyStore-}+// 1. Define schemes + validators, pass to App+registry := api.NewSecurityRegistry()+registry.MustRegister("jwt", api.HTTPBearerJWT(), &JWTValidator{})+registry.MustRegister("apiKey", api.APIKeyHeader("X-API-Key"), &APIKeyValidator{})-func (v *JWTValidator) Validate(ctx context.Context, r *http.Request) (any, error) {- token := extractBearer(r)- claims, err := v.validateToken(token)- if err != nil {- return nil, api.ErrSkipToNextAuth // Try next auth method- }- return claims, nil-}+app := api.NewApp(api.AppConfig{+ SecurityRegistry: registry, // enables unified WithSecurity+})-// 3. Register at startup-registry := api.NewSecurityRegistry()-registry.MustRegister("userJWT", UserJWTScheme, &JWTValidator{db: db})-registry.MustRegister("apiKey", APIKeyScheme, &APIKeyValidator{db: db})--// 4. Apply middleware-middleware := registry.Middleware([]api.Security{- api.NewSecurity("userJWT"), // OR- api.NewSecurity("apiKey"),-}, errorHandler)--// 5. Get auth result in handler-auth := api.GetAuthResult(r.Context())-fmt.Printf("Authenticated via %s\n", auth.Scheme)+// 2. WithSecurity handles BOTH OpenAPI + middleware+r.Route("/protected", func(r *api.Router) {+ r.WithSecurity(api.NewSecurity("jwt"), api.NewSecurity("apiKey"))+ // ... endpoints automatically protected+})++// 3. Get result in handler+auth := api.GetAuthResult(ctx)+claims := auth.GetClaims()```### Security Relationships```go// OR - any one succeeds-[]api.Security{- api.NewSecurity("jwt"),- api.NewSecurity("apiKey"),-}+[]api.Security{api.NewSecurity("jwt"), api.NewSecurity("apiKey")}-// AND - both must pass-[]api.Security{- api.NewSecurity("jwt").And("mfa"),-}+// AND - all must pass (MFA example)+[]api.Security{api.NewSecurity("jwt").And("mfa")}// No auth required[]api.Security{{}}```-## Router--```go-router := api.NewRouter()--// Top-level middleware-router.Use(loggingMiddleware)--// Route group with defaults-router.Route("/v1/secrets", func(r *api.Router) {- r.WithSecurity(api.NewSecurity("bearerAuth"))- r.WithTags("Secrets")-- r.Handle(api.Endpoint{- Method: http.MethodPost,- Pattern: "",- Handler: createSecretHandler,- Request: &CreateSecretRequest{},- Response: &SecretResponse{},- Summary: "Create secret",- OperationID: "createSecret",- })-})--// Generate OpenAPI-spec := api.NewOpenAPISpec(&api.OpenAPIConfig{- Info: api.OpenAPIInfo{Title: "My API", Version: "1.0.0"},- SecuritySchemes: registry.Schemes(),-})-spec.AddEndpoints(router.Endpoints())-jsonSpec, _ := spec.JSONIndent("", " ")-```--## Validation Pattern+**AND Security Note:** If the first scheme passes but the second returns `ErrSkipToNextAuth`, the request is rejected (401) — it does NOT fall through to an OR fallback. This prevents MFA bypass.-```go-func handler(w http.ResponseWriter, r *http.Request) {- var req CreateSecretRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- http.Error(w, err.Error(), 400)- return- }-- if errs := req.Schema().Validate(); len(errs) > 0 {- w.WriteHeader(400)- json.NewEncoder(w).Encode(map[string]any{"errors": errs})- return- }-- // Use req...-}-```--## IsPresent() for OneOf/AnyOf--Used internally by `OneOfSchemas` and `AnyOf` to detect which option is provided:--| Type | Present When |-|------|--------------|-| String | `ptr != nil && *ptr != ""` |-| Int/Float/Bool | `ptr != nil` |-| UUID | `ptr != nil && *ptr != uuid.Nil` |-| Time | `ptr != nil && !ptr.IsZero()` |-| Object | Any property is present |-| Array/Map | Custom `IsPresentFn()` |-| Union | `ptr != nil && *ptr != nil` |--## Available Security Schemes+### Available Schemes```goapi.HTTPBearer()@@ -295,53 +339,50 @@ api.OAuth2ClientCredentials(tokenURL, scopes)api.OAuth2AuthorizationCode(authURL, tokenURL, scopes)```-## JsonNullable for Optional Fields--Distinguish between absent, null, and present values:+## JsonNullable (Tri-State PATCH)```go-type Request struct {- Count api.JsonNullable[int] `json:"count"`+type UpdateRequest struct {+ Name api.JsonNullable[string] `json:"name"`}-// After unmarshaling:-// - {"count": 5} → Present=true, Null=false, Value=5-// - {"count": null} → Present=true, Null=true-// - {} → Present=false, Null=false--// Use Ptr() for schema validation-schema := api.Int(req.Count.Ptr()).Required()-// Returns nil if absent/null, pointer to value if present-```--## Required Validation+// {"name": "Bob"} → Present=true, Null=false, Value="Bob"+// {"name": null} → Present=true, Null=true (explicitly clear)+// {} → Present=false (don't touch)-For `Int`, `Float`, `Bool` — required checks `ptr == nil`, not zero value:--```go-// ptr == nil → required error-// ptr != nil && *ptr == 0 → valid (0 is a value, not missing)--// To detect missing vs zero, use pointer fields:-type Request struct {- Count *int `json:"count"` // nil when field absent+func (r *UpdateRequest) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "name": api.Nullable(&r.Name, api.String(&r.Name.Value)).Optional(),+ })}-api.Int(r.Count).Required() // fails if Count is nil```-## AdditionalProperties--`AdditionalProperties(false)` is **OpenAPI metadata only** — it doesn't enforce validation. To reject unknown fields at parse time:+## Error Handling```go-decoder := json.NewDecoder(r.Body)-decoder.DisallowUnknownFields()-if err := decoder.Decode(&req); err != nil { ... }+// In handlers, return typed errors+return UserResponse{}, api.NotFound("user %s not found", id)+return UserResponse{}, api.Conflict("email already exists")+return UserResponse{}, api.BadRequest("invalid input")+return UserResponse{}, api.Forbidden("access denied")++// Custom error handler+app := api.NewApp(api.AppConfig{+ ErrorHandler: func(ctx context.Context, err error) *api.ErrorBody {+ if apiErr, ok := api.AsError(err); ok {+ return &api.ErrorBody{+ StatusCode: apiErr.Status,+ Message: apiErr.Message,+ Error: apiErr.Name,+ }+ }+ return &api.ErrorBody{StatusCode: 500, Message: "Internal error"}+ },+})```## Common Chainable Methods-All schemas support:```go.Required().Optional()@@ -353,4 +394,5 @@ All schemas support:.ReadOnly().WriteOnly().Default(value)+.From(source) // SourcePath, SourceQuery, SourceHeader, SourceCookie```diff --git a/backend-go/pkg/api/REVIEW.md b/backend-go/pkg/api/REVIEW.mddeleted file mode 100644index b95629f3cd..0000000000--- a/backend-go/pkg/api/REVIEW.md+++ /dev/null@@ -1,130 +0,0 @@-# Review: `backend-go/pkg/api` (Pass 2)--Re-review after the first round of fixes. The package has improved substantially — most of the P0/P1 items from pass 1 are resolved. Below is a status table of the prior findings followed by issues that are still open and a few new issues introduced by the refactor.-------## Status of pass-1 findings--| # | Finding | Status |-|---|---------|--------|-| 1 | AND security claims non-deterministically lost | **Fixed** — `Security` is an ordered `[]SecurityRequirement`; `AuthResult{Schemes, Claims map[string]any}` accumulates per-scheme claims |-| 2 | `ErrSkipToNextAuth` inside AND falls through to next OR | **Documented, not fixed** — see Open #1 |-| 3 | 401 missing `WWW-Authenticate` header | **Fixed** — `buildWWWAuthenticate` populates the header on the default 401 path |-| 4 | `SecurityRegistry` not thread-safe | **Fixed** — `sync.RWMutex` added on all read/write paths |-| 5 | `additionalProperties(false)` not enforced | **Partially fixed** — documented as OpenAPI-only; `ParseRequestWithOptions(DisallowUnknownFields())` exists but is *opt-in and detached* from the schema declaration (see Open #2) |-| 6 | Nested field paths mangled in `ObjectSchema.Validate` | **Fixed** — `inner` is preserved and composed with the outer field name |-| 7 | Required `Int`/`Float`/`Bool` silently accept missing values | **Fixed** — `Validate()` now checks `ptr == nil` instead of `*ptr == 0` |-| 8 | Request body `required` hardcoded to `true` | **Partially fixed** — new helper `BuildOpenAPIRequestBody` computes `required` correctly, but the active spec path `OpenAPISpec.generateRequestBody` (openapi.go:384–398) still hardcodes `true` (see Open #3) |-| 9 | Discriminated `OneOf` skips validation | **Fixed** — `SetActiveVariant` + branch in `Validate()` |-| 10 | `Const` doesn't enforce its value | **Not fixed** — `ConstSchema.Validate()` still returns nil (see Open #4) |-| 11 | Object property iteration non-deterministic in OpenAPI | **Fixed** — `propertyOrder` is now used by `OpenAPI()` |-| 12 | No automatic validation for path/query/header/cookie params | **Partially fixed** — `ParseRequest` exists, but handlers still have to remember to call it *and* validate (see Open #5) |-| 13 | `defaultSecurity`/`defaultTags` don't propagate through `Mount` | **Fixed** — `Mount` copies defaults onto endpoints that lack them |-| 14 | `StringSchema.Pattern` panics on invalid regex | **Fixed** — `TryPattern` (returns error) and `PatternCompiled` (accepts pre-compiled) added |-| 15 | Email validation too permissive | **Fixed** — `EmailStrict()` requires a dot in the domain |-| 16 | `URI` accepts schemeless paths | **Fixed** — `URL()` requires scheme + host |-| 17 | Query array params missing `style`/`explode` | **Partially fixed** — handled in `BuildOpenAPIParameters` (request.go) but **not** in the live `OpenAPISpec.generateParameters` path (see Open #3) |-| 18 | Parameter `description`/`deprecated`/`example` not lifted | **Partially fixed** — same as #17: lifted in `BuildOpenAPIParameters`, not in `generateParameters` |-| 19 | `ExtractPathParams` doesn't strip chi regex constraints | **Fixed** — both `Endpoint.ExtractPathParams` and the new `ExtractPathParams` helper strip `:regex` |-| 20 | All responses labeled "Successful response" | **Fixed** — `ResponseDescriptions` + `defaultResponseDescription` |-| 21 | Global `Security` config not honored on endpoints | Unchanged (consistent with OpenAPI inheritance — acceptable) |-| 22 | `UnionDef.Parse` divergent fast/slow paths | **Fixed** — single parsing path |-| 23 | `NestedUnionDef.OpenAPI` inconsistent with parser on null payload | **Fixed** — `ParseWithType` now rejects null/empty payload |-| Low | `statusCodeToString` rune arithmetic | **Fixed** — uses `strconv.Itoa` |-| Low | `joinStrings` reimplementation | **Fixed** — uses `strings.Join` |--That's all P0/P1 from pass 1 closed or downgraded. Remaining items below.-------## Still open--### Open #1 — `auth.go:603-605` — `ErrSkipToNextAuth` inside AND still fails the whole entry and falls through to the next OR option-The new code makes this explicit and documents the choice:-```go-if errors.Is(err, ErrSkipToNextAuth) {- return nil, ErrSkipToNextAuth-}-```-This is now an intentional design ("scheme not present → AND requirement fails → try next OR"), and it's defensible. But there's a real edge case worth thinking about: in `NewSecurity("jwt").And("mfa")`, if the user supplies a valid JWT but no MFA header, the JWT validator passes and the MFA validator returns `ErrSkipToNextAuth`. The current logic propagates the skip and tries the next OR option — which means a request that successfully authenticated half of an AND requirement gets silently demoted into the next OR option (or unauthenticated). For step-up auth flows you almost certainly want a hard 401 with a hint to provide MFA, not a silent fallback.--Recommendation: distinguish "no credential presented at all" (skip, OR fallback ok) from "first AND leg passed, later AND leg has no credential" (hard fail with `WWW-Authenticate` advertising the missing scheme). The simplest fix is: once *any* validator in the AND group returns claims, treat a subsequent `ErrSkipToNextAuth` as a hard failure for that requirement.--### Open #3 — Two parallel OpenAPI generation paths; the live one still has the pass-1 bugs-The new helpers in `request.go` (`BuildOpenAPIParameters`, `BuildOpenAPIRequestBody`) correctly:-- compute `requestBody.required` from field-level `IsRequired()`,-- add `style: form, explode: true` to array query params,-- lift `description`/`deprecated`/`example` from the schema to the parameter object,-- merge body and parameter sources from a single schema.--But the actual spec generator — `OpenAPISpec.generateOperation` → `generateRequestBody`/`generateParameters` (openapi.go) — does **none** of these. Unless a caller bypasses `OpenAPISpec.AddEndpoints` and emits operations manually using the new helpers, every endpoint in the generated spec still suffers from pass-1's #8, #17, #18. The dead code in `openapi.go` is what gets shipped today.--Recommendation: rewrite `generateRequestBody`/`generateParameters` to delegate to the new helpers when the endpoint's request schema has typed sources (i.e. `req.Schema()` is set), and keep the legacy `PathParams/QueryParams/HeaderParams/CookieParams` maps as a fallback only. Right now we have two ways to express the same thing and they disagree.---### Open #5 — `ParseRequest` does not call `Validate()` after parsing-The new parser populates fields from path/query/header/cookie/body but never runs `req.Schema().Validate()`. Every handler still has to remember to call it. Given the framework's selling point is single-source-of-truth validation+OpenAPI, this is the wrong default. A `MustParse` or `ParseAndValidate` returning typed errors would close the gap and reduce footguns.-------## New issues introduced by the refactor--### New #1 — `ParseRequest` has a parameter-source-confusion / mass-assignment hazard (`request.go:44–87`)-Order of operations:-1. Loop over path/query/header/cookie schemas, call `setFieldValue` which writes into the struct's bound pointer.-2. Call `json.NewDecoder(r.Body).Decode(req)` which writes into the **whole struct** based on its JSON tags.--If a struct field is bound to a path/query/header schema (e.g. `OrgID` with `From(SourcePath)`) but its struct tag isn't `json:"-"`, a request body containing that JSON key will overwrite the path-bound value *after* it was set from the URL. This is exactly the mass-assignment shape OWASP warns about.--The existing tests skirt this by convention (`OrgID string `json:"-"`` in `request_test.go:15`), but nothing in the framework enforces it. A schema bound to `*UserID` with `From(SourcePath)` and a struct field `UserID uuid.UUID `json:"user_id"`` is a silent vulnerability: clients can supply `{"user_id": "<victim>"}` in the body and override the URL parameter.--Recommendation, in priority order:-- Reverse the order: decode body **first**, then overwrite with path/query/header/cookie values (URL-supplied wins).-- Or: at registration time, panic if any non-`SourceBody` schema's struct field has a usable JSON tag (i.e. not `json:"-"` and not unexported).-- At minimum, document the `json:"-"` requirement loudly in the `From()` godoc.--This is the most security-relevant open issue.--### New #2 — `ParseRequest` skips body when `r.ContentLength == 0`-`request.go:83` — `r.ContentLength != 0` is the gate. Two problems:-- `ContentLength == -1` means "unknown" (HTTP/1.1 chunked, HTTP/2 without an explicit header). The condition is true, so body *is* parsed — fine for chunked.-- `ContentLength == 0` skips parsing. But a request can legitimately set `Content-Length: 0` and still expect downstream errors (e.g. POST with no body where the schema requires body fields). Today such a request silently passes parsing and only fails at `Validate()`.--This is benign as long as Validate() is called — but combined with Open #5 (no auto-validate), it produces silent success.--### New #3 — `setFieldValue` returns nil on empty value (`request.go:94-96`)-For required path params, chi rejects missing path parts via 404 (so this is fine for paths), but for required headers/cookies/query, `value == ""` is just treated as "not provided" and `setFieldValue` returns nil. Without a follow-up `Validate()`, the request gets to the handler with the field zero. Same root cause as Open #5; double-flagging because it interacts with required-headers in particular (e.g. `X-Org-ID` header missing → silent zero).--### New #4 — `r.URL.Query().Get(name)` parses the URL on every field (`request.go:54`)-Minor perf nit: `r.URL.Query()` is `O(n)` over the raw query string. Hoist it out of the loop and call `.Get(name)` on the cached `url.Values`. (`ParseRequestWithOptions` does call `r.URL.Query()` once per field too — same change.)--### New #5 — `ParseRequest` doesn't handle array-typed query params-The new code admits this in a comment: `// For array fields, we would need special handling // For now, take the first value` (request.go:361-363). `ParseQueryArray`/`ParseQueryArrayCSV` exist as helpers but aren't wired through `setFieldValue`, so `?tags=a&tags=b` against an `Array(String(...)).From(SourceQuery)` schema silently drops everything but the first value.--### New #6 — `errors.Is` should be used for `http.ErrNoCookie`-`request.go:71, 379` use `err == http.ErrNoCookie`. It works because `http.ErrNoCookie` is a sentinel, but `errors.Is(err, http.ErrNoCookie)` is the convention and survives `fmt.Errorf("...%w")` wrapping in middleware.--### New #7 — `setFieldValue` doesn't validate format hints-A `String(&id).UUID().From(SourcePath)` schema accepts any non-empty string from the URL — the UUID format check only happens in `Validate()`, not in the parser. That's actually the right layering, but combined with Open #5 it means the value reaches the handler unvalidated. Worth flagging that `setFieldValue` is a binder, not a parser — its only "validation" is that the type-coercion (e.g. `strconv.ParseInt`) succeeds.--### New #8 — `SplitSchemaBySource` loses `propertyOrder` (`request.go:202-227`)-When `BuildOpenAPIRequestBody` calls `SplitSchemaBySource`, the resulting `bodySchema` is built via `Object(bodyProps)` which captures *current map order* into `propertyOrder` — i.e. randomized. The new helpers undo the determinism fix from pass-1's #11 when used. Carry over the relevant subset of `schema.propertyOrder`.--### New #9 — `buildWWWAuthenticate` for apiKey schemes returns empty string (`auth.go:664-665`)-There's no IANA-registered challenge for `apiKey` schemes, so this is technically correct. But if a route only accepts an apiKey, the WWW-Authenticate header falls back to `"Bearer"` (the function's default at line 647), which is misleading: it tells the client to use Bearer when the server actually wants an API key in a specific header. Either omit the header for apiKey-only routes or include a custom challenge (e.g. `ApiKey realm="X-API-Key"`) — even though non-standard, it's more truthful.--### New #10 — `JsonNullable[T]` is a clean addition but the schema framework doesn't know about it-`nullable.go` introduces the absent/null/present tri-state Go is missing, with `Ptr() *T` to bridge to schemas. Nice. But there's no `Nullable[T]()` schema constructor that binds to `JsonNullable[T]` directly — every caller has to do `String(req.Name.Ptr())` boilerplate. Worth adding a small wrapper so the schema can read the tri-state directly (e.g. distinguish "set to null" from "absent" for PATCH semantics, which is the main reason `JsonNullable` exists).-------## Updated must-fix list--1. **New #1** — `ParseRequest` mass-assignment risk. Reverse the bind order or panic on misuse. **P0** — actively exploitable if a handler forgets `json:"-"`.-2. **Open #3** — wire the new helpers into `OpenAPISpec.generateOperation`; right now the spec generator still emits the pass-1 bugs (`required: true` hardcoded, missing `style`/`explode`, etc.). **P1**.-3. **Open #5** — make `ParseRequest` (or a sibling) call `Schema().Validate()`. Without this the framework's central promise — single-source-of-truth validation — isn't met. **P1**.-4. **Open #1** — partial-AND skip semantics. **P2** (design choice, but flag in docs at minimum).-5. **Open #2** — link `AdditionalProperties(false)` to `DisallowUnknownFields()`. **P2**.--The remaining items are nice-to-haves. The framework is in materially better shape than pass 1 — the schema, auth, and validation cores are all correct now. The exposure has shifted to the new request-binding layer and to the inconsistency between the new helpers and the still-live spec generator.diff --git a/backend-go/pkg/api/REVIEW_TEST.md b/backend-go/pkg/api/REVIEW_TEST.mddeleted file mode 100644index 996cd652af..0000000000--- a/backend-go/pkg/api/REVIEW_TEST.md+++ /dev/null@@ -1,141 +0,0 @@-# Test review--## Summary-The tests cover the common paths well, but there are three patterns to address:--1. **High duplication** in the primitive-schema, security-scheme, and middleware tests — many groups of 5–11 tests follow identical shapes that would compress to a single table-driven test.-2. **The new `request.go` and `nullable.go` (pass-2 additions) are dramatically undertested** — only 2 tests exist for `request.go`; most public functions (cookie/header parsing, options, helpers, array-query helpers) have zero coverage.-3. **Several pass-2 fixes have no guarding test** — `buildWWWAuthenticate`, `Mount` default propagation, chi regex stripping, `ResponseDescriptions`, registry concurrency. The code is fixed but a regression would not be caught.--There's also one test file (`request_test.go:78`) where the schema is built and discarded — `_ = schema` — so the test verifies nothing about the schema it claims to test.-------## Tests to merge / simplify--### 1. Primitive schema validation (`schema_test.go`)-The 10+ tests of the shape `TestStringSchema_<rule>` (MinLength, MaxLength, Length, Pattern, Enum, FormatEmail, FormatUUID, FormatURI, FormatDateTime, FormatDate) all follow:-```go-val := "<bad>"-schema := String(&val).<rule>(...)-errs := schema.Validate()-require.Len(t, errs, 1)-assert.Equal(t, "<code>", errs[0].Code)-val = "<good>"-errs = schema.Validate()-assert.Empty(t, errs)-```-This is one table-driven test. Same for `IntSchema_{Min,Max,Range,ExclusiveMin,ExclusiveMax,MultipleOf,Enum}` and `FloatSchema_{Min,Max,Range,ExclusiveMinMax}`. Roughly 25 functions → 3 table tests.--### 2. OpenAPI modifier tests (`schema_composite_test.go:494–578`)-`TestObjectSchema_Modifiers`, `TestArraySchema_Modifiers`, `TestMapSchema_Modifiers`, `TestOneOfSchema_Modifiers`, `TestAnyOfSchema_Modifiers`, `TestAllOfSchema_Modifiers` all chain the same `.Nullable().ReadOnly().WriteOnly().Deprecated().Example(...)` and assert the same five keys. Fold into one parameterised test driven by `[]struct{ name; build func() Schema }`.--### 3. Per-schema OpenAPI shape tests (`schema_test.go`)-`Test<X>Schema_OpenAPI` × 9 each: build with modifiers, call `.OpenAPI()`, check keys. Could be a table of `(schemaBuilder, expectedKeys map[string]any)`. Cuts ~250 lines.--### 4. Per-type `IsPresent` tests (`ispresent_test.go`)-Every test follows: nil ptr → false, zero value → conditional, non-zero → true. A single table over the schema constructors with the same three subtests covers all 9 primitive types in one function.--### 5. Security-scheme constructors (`auth_test.go:16–135`)-11 sequential `TestHTTPBearer`, `TestAPIKeyHeader`, `TestOAuth2Implicit`, etc. — each builds, asserts type/scheme/in/name. Table with `(name, build, expect)` collapses to ~30 lines.--### 6. Middleware test boilerplate (`auth_test.go:483–795`)-12 middleware tests repeat: build registry, register N validators, build middleware, fire `httptest.NewRequest`, assert status. Extract a helper like:-```go-func runMiddleware(t *testing.T, validators map[string]Validator, security []Security, handler http.HandlerFunc) *httptest.ResponseRecorder { ... }-```-Each test then collapses to 5–10 lines. The duplication is currently ~25 lines per test.--### 7. Router method tests (`router_test.go:16–92`)-`TestRouter_{Get,Post,Put,Patch,Delete}` × 5 — identical shape, register one route and assert the registered method. Table-driven.--### 8. OpenAPI parameter source tests (`openapi_test.go:248–404`)-`TestOpenAPISpec_Generate_{Path,Query,Header,Cookie}Parameters` — same structure, only `in` value and source map differ. Single table.--### 9. ParseUnionField tests (`union_helpers_test.go:13–73`)-6 tests (`_ValidDog`, `_ValidCat`, `_Null`, `_Empty`, `_UnknownType`, `_InvalidJSON`) — classic table candidate over `(name, raw, wantErr, assertAnimal)`.--### 10. Drop the "rebuild schema after modifying values" pattern-`TestObjectSchema_Validate` (schema_composite_test.go:30–34) and `TestAllOfSchema_Validate` (line 427–434) both **rebuild** the schema after assigning values, because the original captured a nil pointer. This is awkward. Either:-- Start with non-nil pointers and assign to `*ptr` (so the same schema instance is reused), or-- Wrap the build in a helper `buildSchema(name, age)` and call it twice.--The current form misleads readers into thinking that mutating the bound value mid-test is exercised.-------## Coverage gaps — pass-2 fixes with no guarding test--These are the highest-priority gaps because they cover **code changes that don't have regression protection**:--| Pass-2 fix | Current test coverage |-|---|---|-| `buildWWWAuthenticate` populates `WWW-Authenticate` on default 401 | **None** — `TestMiddleware_FailedAuth_DefaultHandler` only checks `rec.Code == 401`, never `rec.Header().Get("WWW-Authenticate")`. |-| `SecurityRegistry` mutex (concurrent register/read) | **None** — no `t.Parallel` + goroutine test. |-| `Mount` propagates `defaultSecurity`/`defaultTags` | **None** — `TestRouter_Mount` doesn't set defaults on the parent, so the propagation branch is untested. |-| `ExtractPathParams` strips chi regex (`{id:[0-9]+}`) | **None** — no test passes a regex-constrained pattern. |-| `ResponseDescriptions` + `defaultResponseDescription` | **None** — `TestOpenAPISpec_Generate_MultipleResponses` only checks status codes exist, never the description string. `WithResponseDescriptions` option is uncovered. |-| `OneOf().SetActiveVariant().Validate()` — discriminated branch | **Covered** in `TestOneOfSchema_DiscriminatedValidation` — good. |-| Nested object error paths composed with `.` (pass-1 #6 fix) | **Covered** in `TestObjectSchema_NestedFieldPaths` — good. |-| Required Int/Float/Bool — nil-ptr-vs-zero | **Covered** for each — good. |--Add five small tests for the rows above and the pass-2 work is properly guarded.-------## Coverage gaps — `request.go` (the new layer)--Only 2 tests exist (`TestParseRequest_PathAndQuery`, `TestParseRequest_UUIDPath`). Missing:--1. **Mass-assignment hazard (Review's New #1)** — there is **no test** showing what happens when a request body contains a JSON key that matches a `From(SourcePath)` field's JSON tag. This is exactly the test that would catch the bug. Add:- ```go- // POST /orgs/legitimate-org/secrets body={"orgId":"attacker-org","name":"x"}- // Assert req.OrgID == "legitimate-org" (path wins) OR document and assert body wins- ```-2. `ParseRequest` with `r.ContentLength == 0` — body parsing should be skipped, validation of body fields should still flag required.-3. `ParseRequest` with chunked transfer encoding (`ContentLength == -1`) — body should still parse.-4. Cookie parameter parsing — not tested at all. Missing cookie should be tolerated; present cookie should populate.-5. Header parameter parsing — not tested at all.-6. Required header/cookie missing — should error at validation time, not parse time.-7. `setFieldValue` error paths — non-numeric for `Int` query, invalid UUID for path, malformed time. None exercised.-8. `ParseRequestWithOptions(DisallowUnknownFields())` — option exists but no test asserts that unknown body fields are rejected.-9. `ParseQueryArray` / `ParseQueryArrayCSV` — both defined, no tests.-10. `SplitSchemaBySource`, `BuildOpenAPIParameters`, `BuildOpenAPIRequestBody` — none of the new OpenAPI helpers have tests. Given these helpers are the "right" code (Open #3 in REVIEW.md) but aren't yet wired into `OpenAPISpec`, leaving them untested compounds the divergence risk.-11. `request_test.go:78` — `_ = schema` discards a built schema; either remove or actually validate against `chi.URLParam`.-------## Coverage gaps — other--- `OneOfSchemas` with `ValidateFn` override — defined but no test asserts the override path bypasses the default oneOf logic.-- `ArraySchema.Validate()` and `MapSchema.Validate()` without `ValidateFn` → returns nil — no test pins this behaviour (subtle: it means array/map item validation is a no-op by default).-- `AnyOf()` and `AllOf()` with **zero schemas** — required behaviour unclear (current code returns "at least one option" for AnyOf, no errors for AllOf). No tests guard either.-- `Const` validation is asserted **empty** (`TestConstSchema_Validate`) — this test currently *passes* but it locks in the still-open "Const doesn't enforce" bug from REVIEW.md. If/when the fix lands, this test will silently keep passing for the wrong reason. Either add a `// TODO: enforce` comment or invert: assert that mismatched const values *should* fail and skip until fixed.-- `Endpoint` with `Method: HEAD` / `OPTIONS` / custom — `router.Handle()` has fallbacks for these but no test exercises them.-- `Router.With(...).Route(prefix, ...)` — middleware + route group composition is untested.-- `defaultResponseDescription` for boundary codes (199, 300, 599, 600) — no test.-- `statusCodeToString` for non-standard codes — no test.-------## Brittleness / smells--- `integration_test.go:135` — `require.GreaterOrEqual(t, len(errs), 2)`. Loose bound. The shape "should have errors for email, street, zipCode" is asserted with `||` (line 141). If a regression makes one of them silently disappear, the test still passes. Replace with an exact count and explicit per-field assertions.-- `oneof_anyof_test.go:220–225` — left-in stream-of-consciousness comment block (`// Actually, let me think about this...`). Clean up.-- `union_test.go:84-91` and `union_helpers_test.go:59-66` — `assert.Contains(err.Error(), "unknown type value")` is fragile (matches the source string verbatim). Prefer wrapping union parse errors with sentinel `errors.New("...")` values that tests can `errors.Is` against. Same goes for `"missing discriminator"` and `"missing payload"`.-- `oneof_anyof_test.go:14` — `var intPtr *int` then `Int(intPtr)` is a clever encoding of "nil-pointer means not-present", but it reads as a typo. A one-line comment helps, or split.-------## Recommended sequence--If you want one ordered pass:--1. **Add the five "pass-2 fix regression" tests** (the table above) — highest leverage; they prevent the most-recent improvements from regressing.-2. **Add a single mass-assignment test for `ParseRequest`** — even before the fix lands, the test pins down the current (vulnerable) behaviour and forces a conversation when someone changes the order.-3. **Fold the primitive schema validation + OpenAPI tests into table-driven** — biggest line-count win (`schema_test.go` could lose 300+ lines without losing a case).-4. **Cover the rest of `request.go`** — cookie/header parsing, options, array helpers, OpenAPI helpers.-5. Clean up the brittle error-string assertions by introducing sentinel errors in `union.go` (`var ErrUnknownVariant = errors.New(...)`) — small refactor, cleaner tests.-6. **Then** merge the security-scheme constructors and middleware boilerplate.--Items 1 and 2 are correctness wins. 3–6 are maintenance wins.diff --git a/backend-go/pkg/api/auth.go b/backend-go/pkg/api/auth.goindex 5f967b661e..99768c5a83 100644--- a/backend-go/pkg/api/auth.go+++ b/backend-go/pkg/api/auth.go@@ -3,6 +3,7 @@ package apiimport ("context""errors"+ "fmt""net/http""strings""sync"@@ -604,10 +605,14 @@ func (r *SecurityRegistry) trySecurityRequirement(req *http.Request, sec Securitclaims, err := registered.validator.Validate(req.Context(), req)if err != nil {- // Inside AND: ErrSkipToNextAuth means this requirement failed- // (the scheme wasn't present/applicable), so the whole AND fails.- // We still return ErrSkipToNextAuth to try the next OR option.if errors.Is(err, ErrSkipToNextAuth) {+ // If a previous scheme in this AND already succeeded, we cannot+ // skip to the next OR option — that would bypass the second factor.+ // Return a hard 401 instead.+ if len(result.Schemes) > 0 {+ return nil, fmt.Errorf("missing required auth scheme %q after %v succeeded", requirement.Scheme, result.Schemes)+ }+ // No scheme has succeeded yet; safe to try the next OR option.return nil, ErrSkipToNextAuth}// Any other error (invalid token, expired, etc.) is a hard failurediff --git a/backend-go/pkg/api/auth_test.go b/backend-go/pkg/api/auth_test.goindex 21fab20dc4..ce97ed0445 100644--- a/backend-go/pkg/api/auth_test.go+++ b/backend-go/pkg/api/auth_test.go@@ -14,125 +14,82 @@ import (// --- Security Scheme Constructors ----func TestHTTPBearer(t *testing.T) {- scheme := HTTPBearer()-- assert.Equal(t, "http", scheme.Type)- assert.Equal(t, "bearer", scheme.Scheme)- assert.Equal(t, "", scheme.BearerFormat)-}--func TestHTTPBearerJWT(t *testing.T) {- scheme := HTTPBearerJWT().WithDescription("JWT authentication")-- assert.Equal(t, "http", scheme.Type)- assert.Equal(t, "bearer", scheme.Scheme)- assert.Equal(t, "JWT", scheme.BearerFormat)- assert.Equal(t, "JWT authentication", scheme.Description)-}--func TestHTTPBasic(t *testing.T) {- scheme := HTTPBasic().WithDescription("Basic HTTP auth")-- assert.Equal(t, "http", scheme.Type)- assert.Equal(t, "basic", scheme.Scheme)- assert.Equal(t, "Basic HTTP auth", scheme.Description)-}--func TestAPIKeyHeader(t *testing.T) {- scheme := APIKeyHeader("X-API-Key").WithDescription("API key in header")-- assert.Equal(t, "apiKey", scheme.Type)- assert.Equal(t, "header", scheme.In)- assert.Equal(t, "X-API-Key", scheme.Name)- assert.Equal(t, "API key in header", scheme.Description)-}--func TestAPIKeyQuery(t *testing.T) {- scheme := APIKeyQuery("api_key").WithDescription("API key in query")-- assert.Equal(t, "apiKey", scheme.Type)- assert.Equal(t, "query", scheme.In)- assert.Equal(t, "api_key", scheme.Name)- assert.Equal(t, "API key in query", scheme.Description)-}--func TestAPIKeyCookie(t *testing.T) {- scheme := APIKeyCookie("session").WithDescription("Session cookie")-- assert.Equal(t, "apiKey", scheme.Type)- assert.Equal(t, "cookie", scheme.In)- assert.Equal(t, "session", scheme.Name)- assert.Equal(t, "Session cookie", scheme.Description)-}--func TestOpenIDConnect(t *testing.T) {- scheme := OpenIDConnect("https://example.com/.well-known/openid-configuration").- WithDescription("OIDC auth")-- assert.Equal(t, "openIdConnect", scheme.Type)- assert.Equal(t, "https://example.com/.well-known/openid-configuration", scheme.OpenIDConnectURL)- assert.Equal(t, "OIDC auth", scheme.Description)-}--func TestOAuth2Implicit(t *testing.T) {- scopes := map[string]string{- "read": "Read access",- "write": "Write access",+func TestSecuritySchemeConstructors(t *testing.T) {+ scopes := map[string]string{"read": "Read access", "write": "Write access"}++ tests := []struct {+ name string+ build func() *SecurityScheme+ verify func(t *testing.T, s *SecurityScheme)+ }{+ {"HTTPBearer", HTTPBearer, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "http", s.Type)+ assert.Equal(t, "bearer", s.Scheme)+ }},+ {"HTTPBearerJWT", HTTPBearerJWT, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "http", s.Type)+ assert.Equal(t, "bearer", s.Scheme)+ assert.Equal(t, "JWT", s.BearerFormat)+ }},+ {"HTTPBasic", HTTPBasic, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "http", s.Type)+ assert.Equal(t, "basic", s.Scheme)+ }},+ {"APIKeyHeader", func() *SecurityScheme { return APIKeyHeader("X-API-Key") }, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "apiKey", s.Type)+ assert.Equal(t, "header", s.In)+ assert.Equal(t, "X-API-Key", s.Name)+ }},+ {"APIKeyQuery", func() *SecurityScheme { return APIKeyQuery("api_key") }, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "apiKey", s.Type)+ assert.Equal(t, "query", s.In)+ assert.Equal(t, "api_key", s.Name)+ }},+ {"APIKeyCookie", func() *SecurityScheme { return APIKeyCookie("session") }, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "apiKey", s.Type)+ assert.Equal(t, "cookie", s.In)+ assert.Equal(t, "session", s.Name)+ }},+ {"OpenIDConnect", func() *SecurityScheme { return OpenIDConnect("https://example.com/.well-known/openid") }, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "openIdConnect", s.Type)+ assert.Equal(t, "https://example.com/.well-known/openid", s.OpenIDConnectURL)+ }},+ {"OAuth2Implicit", func() *SecurityScheme { return OAuth2Implicit("https://example.com/auth", scopes) }, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "oauth2", s.Type)+ require.NotNil(t, s.Flows.Implicit)+ assert.Equal(t, "https://example.com/auth", s.Flows.Implicit.AuthorizationURL)+ }},+ {"OAuth2Password", func() *SecurityScheme { return OAuth2Password("https://example.com/token", scopes) }, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "oauth2", s.Type)+ require.NotNil(t, s.Flows.Password)+ assert.Equal(t, "https://example.com/token", s.Flows.Password.TokenURL)+ }},+ {"OAuth2ClientCredentials", func() *SecurityScheme { return OAuth2ClientCredentials("https://example.com/token", scopes) }, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "oauth2", s.Type)+ require.NotNil(t, s.Flows.ClientCredentials)+ assert.Equal(t, "https://example.com/token", s.Flows.ClientCredentials.TokenURL)+ }},+ {"OAuth2AuthorizationCode", func() *SecurityScheme {+ return OAuth2AuthorizationCode("https://example.com/auth", "https://example.com/token", scopes)+ }, func(t *testing.T, s *SecurityScheme) {+ assert.Equal(t, "oauth2", s.Type)+ require.NotNil(t, s.Flows.AuthorizationCode)+ assert.Equal(t, "https://example.com/auth", s.Flows.AuthorizationCode.AuthorizationURL)+ assert.Equal(t, "https://example.com/token", s.Flows.AuthorizationCode.TokenURL)+ }},}- scheme := OAuth2Implicit("https://example.com/auth", scopes).- WithDescription("OAuth2 implicit flow")- assert.Equal(t, "oauth2", scheme.Type)- assert.Equal(t, "OAuth2 implicit flow", scheme.Description)- require.NotNil(t, scheme.Flows)- require.NotNil(t, scheme.Flows.Implicit)- assert.Equal(t, "https://example.com/auth", scheme.Flows.Implicit.AuthorizationURL)- assert.Equal(t, scopes, scheme.Flows.Implicit.Scopes)-}--func TestOAuth2Password(t *testing.T) {- scopes := map[string]string{- "read": "Read access",- }- scheme := OAuth2Password("https://example.com/token", scopes).- WithDescription("OAuth2 password flow")-- assert.Equal(t, "oauth2", scheme.Type)- require.NotNil(t, scheme.Flows)- require.NotNil(t, scheme.Flows.Password)- assert.Equal(t, "https://example.com/token", scheme.Flows.Password.TokenURL)- assert.Equal(t, scopes, scheme.Flows.Password.Scopes)-}--func TestOAuth2ClientCredentials(t *testing.T) {- scopes := map[string]string{- "admin": "Admin access",+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ scheme := tt.build()+ tt.verify(t, scheme)+ })}- scheme := OAuth2ClientCredentials("https://example.com/token", scopes).- WithDescription("OAuth2 client credentials")-- assert.Equal(t, "oauth2", scheme.Type)- require.NotNil(t, scheme.Flows)- require.NotNil(t, scheme.Flows.ClientCredentials)- assert.Equal(t, "https://example.com/token", scheme.Flows.ClientCredentials.TokenURL)}-func TestOAuth2AuthorizationCode(t *testing.T) {- scopes := map[string]string{- "profile": "Profile access",- }- scheme := OAuth2AuthorizationCode(- "https://example.com/auth",- "https://example.com/token",- scopes,- ).WithDescription("OAuth2 authorization code flow")-- assert.Equal(t, "oauth2", scheme.Type)- require.NotNil(t, scheme.Flows)- require.NotNil(t, scheme.Flows.AuthorizationCode)- assert.Equal(t, "https://example.com/auth", scheme.Flows.AuthorizationCode.AuthorizationURL)- assert.Equal(t, "https://example.com/token", scheme.Flows.AuthorizationCode.TokenURL)+func TestSecurityScheme_WithDescription(t *testing.T) {+ scheme := HTTPBearerJWT().WithDescription("JWT auth")+ assert.Equal(t, "JWT auth", scheme.Description)}// --- SecurityScheme.OpenAPI ---@@ -767,6 +724,43 @@ func TestMiddleware_ANDRelationship_OneFails(t *testing.T) {assert.Equal(t, http.StatusUnauthorized, rec.Code)}+func TestMiddleware_ANDRelationship_PartialSuccessNoFallback(t *testing.T) {+ // Security fix: when jwt succeeds but mfa returns ErrSkipToNextAuth,+ // it should NOT fall through to an OR fallback (e.g., api-key only).+ // This prevents bypassing MFA by omitting the MFA header.+ reg := NewSecurityRegistry()+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{claims: "jwt-claims"})+ reg.MustRegister("mfa", APIKeyHeader("X-MFA"), &mockValidator{err: ErrSkipToNextAuth})+ reg.MustRegister("apiKey", APIKeyHeader("X-API-Key"), &mockValidator{claims: "apikey-claims"})++ var handlerCalled bool+ var capturedAuthResult *AuthResult++ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handlerCalled = true+ capturedAuthResult = GetAuthResult(r.Context())+ w.WriteHeader(http.StatusOK)+ })++ // Security: [jwt AND mfa] OR [apiKey]+ // If jwt passes but mfa skips, should NOT fall through to apiKey-only+ middleware := reg.Middleware([]Security{+ NewSecurity("jwt").And("mfa"),+ NewSecurity("apiKey"),+ }, nil)+ wrapped := middleware(handler)++ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)+ rec := httptest.NewRecorder()++ wrapped.ServeHTTP(rec, req)++ // Should be 401, not 200 via apiKey fallback+ assert.Equal(t, http.StatusUnauthorized, rec.Code)+ assert.False(t, handlerCalled, "handler should not be called - MFA bypass attempt")+ assert.Nil(t, capturedAuthResult)+}+func TestMiddleware_UnregisteredScheme(t *testing.T) {reg := NewSecurityRegistry()diff --git a/backend-go/pkg/api/errors.go b/backend-go/pkg/api/errors.gonew file mode 100644index 0000000000..c0b672ff52--- /dev/null+++ b/backend-go/pkg/api/errors.go@@ -0,0 +1,128 @@+package api++import (+ "errors"+ "fmt"+)++// Error is the application-level error returned by handlers.+// It carries an HTTP-visible name, message, status code, and optional+// structured details. Follows the errutil convention.+type Error struct {+ Name string+ Status int+ Message string+ Details any+ Err error+}++func (e *Error) Error() string {+ if e.Err != nil {+ return e.Message + ": " + e.Err.Error()+ }+ return e.Message+}++func (e *Error) Unwrap() error {+ return e.Err+}++func (e *Error) WithName(name string) *Error {+ e.Name = name+ return e+}++func (e *Error) WithStatus(status int) *Error {+ e.Status = status+ return e+}++func (e *Error) WithMessage(message string) *Error {+ e.Message = message+ return e+}++func (e *Error) WithDetails(details any) *Error {+ e.Details = details+ return e+}++func (e *Error) WithErr(err error) *Error {+ e.Err = err+ return e+}++func (e *Error) WithErrf(format string, args ...any) *Error {+ e.Err = fmt.Errorf(format, args...)+ return e+}++// Error constructors++func BadRequest(format string, args ...any) *Error {+ return &Error{Name: "BadRequest", Status: 400, Message: fmt.Sprintf(format, args...)}+}++func Unauthorized(format string, args ...any) *Error {+ return &Error{Name: "UnauthorizedError", Status: 401, Message: fmt.Sprintf(format, args...)}+}++func Forbidden(format string, args ...any) *Error {+ return &Error{Name: "ForbiddenError", Status: 403, Message: fmt.Sprintf(format, args...)}+}++func NotFound(format string, args ...any) *Error {+ return &Error{Name: "NotFound", Status: 404, Message: fmt.Sprintf(format, args...)}+}++func Conflict(format string, args ...any) *Error {+ return &Error{Name: "Conflict", Status: 409, Message: fmt.Sprintf(format, args...)}+}++func UnprocessableEntity(format string, args ...any) *Error {+ return &Error{Name: "UnprocessableEntity", Status: 422, Message: fmt.Sprintf(format, args...)}+}++func RateLimit(format string, args ...any) *Error {+ return &Error{Name: "RateLimitExceeded", Status: 429, Message: fmt.Sprintf(format, args...)}+}++func InternalServer(format string, args ...any) *Error {+ return &Error{Name: "InternalServerError", Status: 500, Message: fmt.Sprintf(format, args...)}+}++func DatabaseErr(format string, args ...any) *Error {+ return &Error{Name: "DatabaseError", Status: 500, Message: fmt.Sprintf(format, args...)}+}++func GatewayTimeout(format string, args ...any) *Error {+ return &Error{Name: "GatewayTimeoutError", Status: 504, Message: fmt.Sprintf(format, args...)}+}++// ValidationErr creates a 400 error from validation errors.+func ValidationErr(errs []ValidationError) *Error {+ return &Error{+ Name: "ValidationError",+ Status: 400,+ Message: "Validation failed",+ Details: errs,+ }+}++// AsError extracts an *Error from err if present.+func AsError(err error) (*Error, bool) {+ var apiErr *Error+ if errors.As(err, &apiErr) {+ return apiErr, true+ }+ return nil, false+}++// AsValidationErrors extracts ValidationErrors from err if present.+func AsValidationErrors(err error) (ValidationErrors, bool) {+ var validationErrs ValidationErrors+ if errors.As(err, &validationErrs) {+ return validationErrs, true+ }+ return nil, false+}diff --git a/backend-go/pkg/api/handler.go b/backend-go/pkg/api/handler.gonew file mode 100644index 0000000000..983f4d56fa--- /dev/null+++ b/backend-go/pkg/api/handler.go@@ -0,0 +1,694 @@+package api++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+)++// ErrorBody is the JSON response shape sent to clients on error.+// Matches the Node.js backend format for API compatibility.+type ErrorBody struct {+ StatusCode int `json:"statusCode"`+ Message string `json:"message"`+ Error string `json:"error"`+ Details any `json:"details,omitempty"`+}++// ErrorHandler is a user-provided function that handles errors.+// It receives the error, performs matching/logging, and returns the response body.+type ErrorHandler func(ctx context.Context, err error) *ErrorBody++// =============================================================================+// TypedResponse — the new response interface+// =============================================================================++// TypedResponse is a response type that carries its own status code and schema.+// Implementations declare:+// - Schema() *ObjectSchema — the OpenAPI body schema, or nil for no-content.+// - Status() int — the HTTP status code this response produces.+type TypedResponse interface {+ Schema() *ObjectSchema+ Status() int+}++// Status mixins — embed these to avoid writing Status() manually.+//+// type UserResponse struct {+// api.StatusOK+// ID string `json:"id"`+// Name string `json:"name"`+// }+type (+ StatusOK struct{} // 200+ StatusCreated struct{} // 201+ StatusAccepted struct{} // 202+ StatusNoContent struct{} // 204+ StatusBadRequest struct{} // 400+ StatusUnauthorized struct{} // 401+ StatusForbidden struct{} // 403+ StatusNotFound struct{} // 404+ StatusConflict struct{} // 409+ StatusUnprocessableEntity struct{} // 422+ StatusInternalServerError struct{} // 500+)++func (StatusOK) Status() int { return http.StatusOK }+func (StatusCreated) Status() int { return http.StatusCreated }+func (StatusAccepted) Status() int { return http.StatusAccepted }+func (StatusNoContent) Status() int { return http.StatusNoContent }+func (StatusBadRequest) Status() int { return http.StatusBadRequest }+func (StatusUnauthorized) Status() int { return http.StatusUnauthorized }+func (StatusForbidden) Status() int { return http.StatusForbidden }+func (StatusNotFound) Status() int { return http.StatusNotFound }+func (StatusConflict) Status() int { return http.StatusConflict }+func (StatusUnprocessableEntity) Status() int { return http.StatusUnprocessableEntity }+func (StatusInternalServerError) Status() int { return http.StatusInternalServerError }++// =============================================================================+// App+// =============================================================================++// App holds the configuration for the handler system.+type App struct {+ errorHandler ErrorHandler+ defaultResponses []TypedResponse+ securityRegistry *SecurityRegistry+}++// AppConfig configures the App.+type AppConfig struct {+ ErrorHandler ErrorHandler+ DefaultResponses []TypedResponse // universal defaults (typically 400, 500)+ SecurityRegistry *SecurityRegistry // enables WithSecurity to auto-install middleware+}++// NewApp creates a new App with the given configuration.+func NewApp(cfg AppConfig) *App {+ errorHandler := cfg.ErrorHandler+ if errorHandler == nil {+ errorHandler = defaultErrorHandler+ }+ return &App{+ errorHandler: errorHandler,+ defaultResponses: cfg.DefaultResponses,+ securityRegistry: cfg.SecurityRegistry,+ }+}++// DefaultResponses returns the app's default responses.+func (a *App) DefaultResponses() []TypedResponse {+ return a.defaultResponses+}++// SecurityRegistry returns the app's security registry, or nil if not configured.+func (a *App) SecurityRegistry() *SecurityRegistry {+ return a.securityRegistry+}++// =============================================================================+// HandlerBuilder — the new builder-based API+// =============================================================================++// ptrSchemaProvider constrains P to be a pointer to T that implements SchemaProvider.+type ptrSchemaProvider[T any] interface {+ SchemaProvider+ *T+}++// ptrTypedResponse constrains P to be a pointer to T that implements TypedResponse.+type ptrTypedResponse[T any] interface {+ TypedResponse+ *T+}++// HandlerBuilder builds a typed handler with OpenAPI metadata.+type HandlerBuilder[Req any, ReqP ptrSchemaProvider[Req], Resp any, RespP ptrTypedResponse[Resp]] struct {+ app *App+ handler func(context.Context, *Req) (Resp, error)+ summary string+ description string+ operationID string+ tags []string+ deprecated bool+ security []Security+ extraResponses []TypedResponse+ withoutDefaults []int+}++// Handler creates a builder for a typed handler.+// Req and Resp are inferred from the fn signature.+func Handler[Req any, ReqP ptrSchemaProvider[Req], Resp any, RespP ptrTypedResponse[Resp]](+ app *App,+ fn func(context.Context, *Req) (Resp, error),+) *HandlerBuilder[Req, ReqP, Resp, RespP] {+ return &HandlerBuilder[Req, ReqP, Resp, RespP]{+ app: app,+ handler: fn,+ }+}++// Summary sets the OpenAPI summary.+func (b *HandlerBuilder[Req, ReqP, Resp, RespP]) Summary(s string) *HandlerBuilder[Req, ReqP, Resp, RespP] {+ b.summary = s+ return b+}++// Description sets the OpenAPI description.+func (b *HandlerBuilder[Req, ReqP, Resp, RespP]) Description(s string) *HandlerBuilder[Req, ReqP, Resp, RespP] {+ b.description = s+ return b+}++// OperationID sets the OpenAPI operationId.+func (b *HandlerBuilder[Req, ReqP, Resp, RespP]) OperationID(s string) *HandlerBuilder[Req, ReqP, Resp, RespP] {+ b.operationID = s+ return b+}++// Tags sets the OpenAPI tags.+func (b *HandlerBuilder[Req, ReqP, Resp, RespP]) Tags(tags ...string) *HandlerBuilder[Req, ReqP, Resp, RespP] {+ b.tags = tags+ return b+}++// Deprecated marks the endpoint as deprecated.+func (b *HandlerBuilder[Req, ReqP, Resp, RespP]) Deprecated() *HandlerBuilder[Req, ReqP, Resp, RespP] {+ b.deprecated = true+ return b+}++// Security sets the security requirements for this endpoint.+func (b *HandlerBuilder[Req, ReqP, Resp, RespP]) Security(security ...Security) *HandlerBuilder[Req, ReqP, Resp, RespP] {+ b.security = security+ return b+}++// Responses declares additional response variants for multi-status endpoints.+// Each argument's Status() and Schema() are read at registration time.+func (b *HandlerBuilder[Req, ReqP, Resp, RespP]) Responses(extras ...TypedResponse) *HandlerBuilder[Req, ReqP, Resp, RespP] {+ b.extraResponses = append(b.extraResponses, extras...)+ return b+}++// WithoutDefault suppresses inherited default responses for this endpoint.+func (b *HandlerBuilder[Req, ReqP, Resp, RespP]) WithoutDefault(statusCodes ...int) *HandlerBuilder[Req, ReqP, Resp, RespP] {+ b.withoutDefaults = append(b.withoutDefaults, statusCodes...)+ return b+}++// EndpointSpec is the contract between the builder and the router.+type EndpointSpec interface {+ build(basePath string, routerDefaults []TypedResponse, routerTags []string, routerSecurity []Security) (http.HandlerFunc, Endpoint)+}++// build implements EndpointSpec.+func (b *HandlerBuilder[Req, ReqP, Resp, RespP]) build(_ string, routerDefaults []TypedResponse, routerTags []string, routerSecurity []Security) (http.HandlerFunc, Endpoint) {+ // Build http.HandlerFunc+ handler := wrapTypedHandler[Req, ReqP, Resp, RespP](b.app, b.handler)++ // Compute merged responses map+ responses := map[int]SchemaProvider{}++ // 1. App defaults+ for _, r := range b.app.defaultResponses {+ responses[r.Status()] = typedResponseSchema{r}+ }+ // 2. Router defaults+ for _, r := range routerDefaults {+ responses[r.Status()] = typedResponseSchema{r}+ }+ // 3. Handler's primary response type+ var respZero Resp+ respProvider := RespP(&respZero)+ responses[respProvider.Status()] = typedResponseSchema{respProvider}++ // 4. Extra responses declared via Responses(...)+ seen := map[int]bool{}+ for _, r := range b.extraResponses {+ status := r.Status()+ if seen[status] {+ panic(fmt.Sprintf("api: duplicate status %d in Responses()", status))+ }+ seen[status] = true+ responses[status] = typedResponseSchema{r}+ }+ // 5. Apply opt-outs+ for _, code := range b.withoutDefaults {+ delete(responses, code)+ }++ // Build request schema from type parameter+ var reqZero Req+ reqProvider := ReqP(&reqZero)++ // Determine tags+ tags := b.tags+ if len(tags) == 0 && len(routerTags) > 0 {+ tags = append([]string{}, routerTags...)+ }++ // Determine security+ security := b.security+ if security == nil && len(routerSecurity) > 0 {+ security = append([]Security{}, routerSecurity...)+ }++ return handler, Endpoint{+ Handler: handler,+ Request: reqProvider,+ Responses: responses,+ Summary: b.summary,+ Description: b.description,+ OperationID: b.operationID,+ Tags: tags,+ Deprecated: b.deprecated,+ Security: security,+ }+}++// =============================================================================+// InterfaceHandler — for multi-status handlers returning interface types+// =============================================================================++// InterfaceHandlerBuilder builds a handler that returns a TypedResponse interface.+// Use this for multi-status endpoints where the response type varies at runtime.+type InterfaceHandlerBuilder[Req any, ReqP ptrSchemaProvider[Req], Resp TypedResponse] struct {+ app *App+ handler func(context.Context, *Req) (Resp, error)+ summary string+ description string+ operationID string+ tags []string+ deprecated bool+ security []Security+ responses []TypedResponse+ withoutDefaults []int+}++// InterfaceHandler creates a builder for handlers returning interface types.+// Use Responses() to declare all possible response types for OpenAPI.+func InterfaceHandler[Req any, ReqP ptrSchemaProvider[Req], Resp TypedResponse](+ app *App,+ fn func(context.Context, *Req) (Resp, error),+) *InterfaceHandlerBuilder[Req, ReqP, Resp] {+ return &InterfaceHandlerBuilder[Req, ReqP, Resp]{+ app: app,+ handler: fn,+ }+}++func (b *InterfaceHandlerBuilder[Req, ReqP, Resp]) Summary(s string) *InterfaceHandlerBuilder[Req, ReqP, Resp] {+ b.summary = s+ return b+}++func (b *InterfaceHandlerBuilder[Req, ReqP, Resp]) Description(s string) *InterfaceHandlerBuilder[Req, ReqP, Resp] {+ b.description = s+ return b+}++func (b *InterfaceHandlerBuilder[Req, ReqP, Resp]) OperationID(s string) *InterfaceHandlerBuilder[Req, ReqP, Resp] {+ b.operationID = s+ return b+}++func (b *InterfaceHandlerBuilder[Req, ReqP, Resp]) Tags(tags ...string) *InterfaceHandlerBuilder[Req, ReqP, Resp] {+ b.tags = tags+ return b+}++func (b *InterfaceHandlerBuilder[Req, ReqP, Resp]) Deprecated() *InterfaceHandlerBuilder[Req, ReqP, Resp] {+ b.deprecated = true+ return b+}++func (b *InterfaceHandlerBuilder[Req, ReqP, Resp]) Security(security ...Security) *InterfaceHandlerBuilder[Req, ReqP, Resp] {+ b.security = security+ return b+}++// Responses declares all possible response types for this endpoint.+// Required for InterfaceHandler since we can't infer from the interface type.+func (b *InterfaceHandlerBuilder[Req, ReqP, Resp]) Responses(responses ...TypedResponse) *InterfaceHandlerBuilder[Req, ReqP, Resp] {+ b.responses = append(b.responses, responses...)+ return b+}++func (b *InterfaceHandlerBuilder[Req, ReqP, Resp]) WithoutDefault(statusCodes ...int) *InterfaceHandlerBuilder[Req, ReqP, Resp] {+ b.withoutDefaults = append(b.withoutDefaults, statusCodes...)+ return b+}++func (b *InterfaceHandlerBuilder[Req, ReqP, Resp]) build(_ string, routerDefaults []TypedResponse, routerTags []string, routerSecurity []Security) (http.HandlerFunc, Endpoint) {+ handler := wrapInterfaceHandler[Req, ReqP, Resp](b.app, b.handler)++ responses := map[int]SchemaProvider{}++ // 1. App defaults+ for _, r := range b.app.defaultResponses {+ responses[r.Status()] = typedResponseSchema{r}+ }+ // 2. Router defaults+ for _, r := range routerDefaults {+ responses[r.Status()] = typedResponseSchema{r}+ }+ // 3. Declared responses (required for interface handlers)+ for _, r := range b.responses {+ responses[r.Status()] = typedResponseSchema{r}+ }+ // 4. Apply opt-outs+ for _, code := range b.withoutDefaults {+ delete(responses, code)+ }++ var reqZero Req+ reqProvider := ReqP(&reqZero)++ tags := b.tags+ if len(tags) == 0 && len(routerTags) > 0 {+ tags = append([]string{}, routerTags...)+ }++ security := b.security+ if security == nil && len(routerSecurity) > 0 {+ security = append([]Security{}, routerSecurity...)+ }++ return handler, Endpoint{+ Handler: handler,+ Request: reqProvider,+ Responses: responses,+ Summary: b.summary,+ Description: b.description,+ OperationID: b.operationID,+ Tags: tags,+ Deprecated: b.deprecated,+ Security: security,+ }+}++func wrapInterfaceHandler[Req any, ReqP ptrSchemaProvider[Req], Resp TypedResponse](+ app *App,+ fn func(context.Context, *Req) (Resp, error),+) http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ ctx := r.Context()++ httpCtx := &HTTPContext{request: r, response: w}+ ctx = context.WithValue(ctx, httpContextKey{}, httpCtx)++ var req Req+ ptr := ReqP(&req)+ if err := ParseAndValidate(r, ptr); err != nil {+ writeErrorResponse(w, app.errorHandler(ctx, err))+ return+ }++ result, err := fn(ctx, &req)+ if err != nil {+ writeErrorResponse(w, app.errorHandler(ctx, err))+ return+ }++ // For interface types, call methods directly on the interface+ status := result.Status()+ schema := result.Schema()++ if schema == nil {+ w.WriteHeader(status)+ return+ }++ writeJSONResponse(w, status, result)+ }+}++// typedResponseSchema wraps a TypedResponse to implement SchemaProvider.+type typedResponseSchema struct {+ resp TypedResponse+}++func (t typedResponseSchema) Schema() *ObjectSchema {+ return t.resp.Schema()+}++// wrapTypedHandler creates the http.HandlerFunc for a typed handler.+func wrapTypedHandler[Req any, ReqP ptrSchemaProvider[Req], Resp any, RespP ptrTypedResponse[Resp]](+ app *App,+ fn func(context.Context, *Req) (Resp, error),+) http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ ctx := r.Context()++ httpCtx := &HTTPContext{request: r, response: w}+ ctx = context.WithValue(ctx, httpContextKey{}, httpCtx)++ var req Req+ ptr := ReqP(&req)+ if err := ParseAndValidate(r, ptr); err != nil {+ writeErrorResponse(w, app.errorHandler(ctx, err))+ return+ }++ result, err := fn(ctx, &req)+ if err != nil {+ writeErrorResponse(w, app.errorHandler(ctx, err))+ return+ }++ // Status and schema come from the typed result via pointer+ respPtr := RespP(&result)+ status := respPtr.Status()+ schema := respPtr.Schema()++ if schema == nil {+ // No-content response+ w.WriteHeader(status)+ return+ }++ writeJSONResponse(w, status, result)+ }+}++// =============================================================================+// HTTPContext+// =============================================================================++// HTTPContext provides access to the underlying HTTP request/response.+type HTTPContext struct {+ request *http.Request+ response http.ResponseWriter+}++type httpContextKey struct{}++// HTTP retrieves the HTTPContext from the context.+func HTTP(ctx context.Context) *HTTPContext {+ if h, ok := ctx.Value(httpContextKey{}).(*HTTPContext); ok {+ return h+ }+ return nil+}++func (h *HTTPContext) Request() *http.Request {+ return h.request+}++func (h *HTTPContext) ResponseWriter() http.ResponseWriter {+ return h.response+}++func (h *HTTPContext) Header(name string) string {+ return h.request.Header.Get(name)+}++func (h *HTTPContext) SetHeader(name, value string) {+ h.response.Header().Set(name, value)+}++func (h *HTTPContext) Cookie(name string) (*http.Cookie, error) {+ return h.request.Cookie(name)+}++func (h *HTTPContext) SetCookie(cookie *http.Cookie) {+ http.SetCookie(h.response, cookie)+}++// =============================================================================+// Legacy API — Result-based handlers (kept for compatibility)+// =============================================================================++// Result represents a successful response with status code and body.+type Result interface {+ statusCode() int+ body() any+}++type result struct {+ status int+ data any+}++func (r *result) statusCode() int { return r.status }+func (r *result) body() any { return r.data }++// Result constructors++func OK(body any) Result {+ return &result{status: http.StatusOK, data: body}+}++func Created(body any) Result {+ return &result{status: http.StatusCreated, data: body}+}++func Accepted(body any) Result {+ return &result{status: http.StatusAccepted, data: body}+}++func NoContent() Result {+ return &result{status: http.StatusNoContent, data: nil}+}++func Status(code int, body any) Result {+ return &result{status: code, data: body}+}++// LegacyHandlerFunc is the old signature for handlers returning Result.+type LegacyHandlerFunc[Req any] func(ctx context.Context, req *Req) (Result, error)++// TypedHandler bundles an HTTP handler with its request/response schemas for OpenAPI.+// Used by the legacy Handle() function.+type TypedHandler struct {+ HTTPHandler http.HandlerFunc+ Request SchemaProvider+ Response SchemaProvider+}++// Handle wraps a legacy Result-based handler into a TypedHandler.+//+// Deprecated: Use Handler() with typed responses instead.+func Handle[T any, P ptrSchemaProvider[T]](app *App, handler LegacyHandlerFunc[T], request, response SchemaProvider) TypedHandler {+ httpHandler := func(w http.ResponseWriter, r *http.Request) {+ ctx := r.Context()++ httpCtx := &HTTPContext{request: r, response: w}+ ctx = context.WithValue(ctx, httpContextKey{}, httpCtx)++ var req T+ ptr := P(&req)+ if err := ParseAndValidate(r, ptr); err != nil {+ writeErrorResponse(w, app.errorHandler(ctx, err))+ return+ }++ result, err := handler(ctx, &req)+ if err != nil {+ writeErrorResponse(w, app.errorHandler(ctx, err))+ return+ }++ if result == nil {+ w.WriteHeader(http.StatusNoContent)+ return+ }++ writeJSONResponse(w, result.statusCode(), result.body())+ }++ return TypedHandler{+ HTTPHandler: httpHandler,+ Request: request,+ Response: response,+ }+}++// HandleFunc is a convenience for when you don't need request parsing.+//+// Deprecated: Use Handler() with typed responses instead.+func HandleFunc(app *App, handler func(ctx context.Context) (Result, error)) TypedHandler {+ httpHandler := func(w http.ResponseWriter, r *http.Request) {+ ctx := r.Context()++ httpCtx := &HTTPContext{request: r, response: w}+ ctx = context.WithValue(ctx, httpContextKey{}, httpCtx)++ result, err := handler(ctx)+ if err != nil {+ writeErrorResponse(w, app.errorHandler(ctx, err))+ return+ }++ if result == nil {+ w.WriteHeader(http.StatusNoContent)+ return+ }++ writeJSONResponse(w, result.statusCode(), result.body())+ }++ return TypedHandler{+ HTTPHandler: httpHandler,+ }+}++// =============================================================================+// Helpers+// =============================================================================++func writeJSONResponse(w http.ResponseWriter, status int, body any) {+ if body == nil {+ w.WriteHeader(status)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(body)+}++func writeErrorResponse(w http.ResponseWriter, body *ErrorBody) {+ if body == nil {+ w.WriteHeader(http.StatusInternalServerError)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(body.StatusCode)+ _ = json.NewEncoder(w).Encode(body)+}++// defaultErrorHandler provides basic error handling without logging.+func defaultErrorHandler(_ context.Context, err error) *ErrorBody {+ if apiErr, ok := AsError(err); ok {+ if apiErr.Status >= 500 {+ return &ErrorBody{+ StatusCode: apiErr.Status,+ Message: "Something went wrong",+ Error: apiErr.Name,+ }+ }+ return &ErrorBody{+ StatusCode: apiErr.Status,+ Message: apiErr.Message,+ Error: apiErr.Name,+ Details: apiErr.Details,+ }+ }++ if validationErrs, ok := AsValidationErrors(err); ok {+ return &ErrorBody{+ StatusCode: 400,+ Message: "Validation failed",+ Error: "ValidationError",+ Details: validationErrs,+ }+ }++ return &ErrorBody{+ StatusCode: 500,+ Message: "Something went wrong",+ Error: "InternalServerError",+ }+}diff --git a/backend-go/pkg/api/http_test.go b/backend-go/pkg/api/http_test.gonew file mode 100644index 0000000000..1e0c8c8348--- /dev/null+++ b/backend-go/pkg/api/http_test.go@@ -0,0 +1,1174 @@+package api++import (+ "bytes"+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// =============================================================================+// Request / response types+//+// Each type focuses on one schema feature. They are wired into a single shared+// test server (setupTestServer) so every integration case is a row in TestHTTP.+// =============================================================================++// --- Body validation (mixed) ---++type SimpleRequest struct {+ Name string `json:"name"`+ Email string `json:"email"`+ Count int `json:"count"`+}++func (r *SimpleRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "name": String(&r.Name).Required().MinLength(2).MaxLength(50),+ "email": String(&r.Email).Required().Email(),+ "count": Int(&r.Count).Optional().Min(0).Max(1000),+ }).Title("SimpleRequest")+}++type SimpleResponse struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Email string `json:"email"`+ Count int `json:"count"`+}++func (r *SimpleResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "id": String(&r.ID).Required(),+ "name": String(&r.Name).Required(),+ "email": String(&r.Email).Required(),+ "count": Int(&r.Count).Optional(),+ }).Title("SimpleResponse")+}++func (*SimpleResponse) Status() int { return http.StatusOK }++// CreatedSimpleResponse for 201 responses+type CreatedSimpleResponse struct {+ SimpleResponse+}++func (*CreatedSimpleResponse) Status() int { return http.StatusCreated }++// --- Path + query (no body) ---++type GetItemRequest struct {+ ID string `json:"-"`+ Page int `json:"-"`+ PageSize int `json:"-"`+ Search string `json:"-"`+ StatusField string `json:"-"`+}++func (r *GetItemRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "id": String(&r.ID).From(SourcePath).Required().UUID(),+ "page": Int(&r.Page).From(SourceQuery).Optional().Min(1).Default(1),+ "pageSize": Int(&r.PageSize).From(SourceQuery).Optional().Min(1).Max(100).Default(20),+ "search": String(&r.Search).From(SourceQuery).Optional().MaxLength(100),+ "status": String(&r.StatusField).From(SourceQuery).Optional().Enum("active", "inactive", "pending"),+ }).Title("GetItemRequest")+}++// --- Full mixed request: body + path + query + header ---++type FullRequest struct {+ ID string `json:"-"`+ Page int `json:"-"`+ PageSize int `json:"-"`+ RequestID string `json:"-"`+ Name string `json:"name"`+ Email string `json:"email"`+ Age int `json:"age"`+ Score float64 `json:"score"`+ IsActive bool `json:"isActive"`+ Tags []string `json:"tags"`+ ResourceID uuid.UUID `json:"resourceId"`+ Description string `json:"description"`+}++func (r *FullRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "id": String(&r.ID).From(SourcePath).Required().UUID(),+ "page": Int(&r.Page).From(SourceQuery).Optional().Min(1).Default(1),+ "pageSize": Int(&r.PageSize).From(SourceQuery).Optional().Min(1).Max(100).Default(20),+ "X-Request-ID": String(&r.RequestID).From(SourceHeader).Optional().UUID(),++ "name": String(&r.Name).Required().MinLength(1).MaxLength(100),+ "email": String(&r.Email).Required().Email(),+ "age": Int(&r.Age).Optional().Min(0).Max(150),+ "score": Float(&r.Score).Optional().Min(0).Max(100),+ "isActive": Bool(&r.IsActive).Optional(),+ "tags": Array(String(nil)).Optional().MinItems(0).MaxItems(10),+ "resourceId": UUID(&r.ResourceID).Optional(),+ "description": String(&r.Description).Optional().MaxLength(500),+ }).Title("FullRequest")+}++type FullResponse struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Email string `json:"email"`+ Page int `json:"page"`+ PageSize int `json:"pageSize"`+ Search string `json:"search,omitempty"`+ StatusField string `json:"status,omitempty"`+ Tags []string `json:"tags,omitempty"`+}++func (r *FullResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "id": String(&r.ID).Required(),+ "name": String(&r.Name).Required(),+ "email": String(&r.Email).Required(),+ "page": Int(&r.Page).Required(),+ "pageSize": Int(&r.PageSize).Required(),+ "search": String(&r.Search).Optional(),+ "status": String(&r.StatusField).Optional(),+ "tags": Array(String(nil)).Optional(),+ }).Title("FullResponse")+}++func (*FullResponse) Status() int { return http.StatusOK }++// --- Path only ---++type DeleteItemRequest struct {+ ID string `json:"-"`+}++func (r *DeleteItemRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "id": String(&r.ID).From(SourcePath).Required().UUID(),+ }).Title("DeleteItemRequest")+}++// Deleted is a no-content response (204)+type Deleted struct{}++func (Deleted) Schema() *ObjectSchema { return nil }+func (Deleted) Status() int { return http.StatusNoContent }++// --- Path source for error type dispatch ---++type ErrorTypeRequest struct {+ ErrorType string `json:"-"`+}++func (r *ErrorTypeRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "type": String(&r.ErrorType).From(SourcePath).Required(),+ }).Title("ErrorTypeRequest")+}++// OKStatus is a simple OK response+type OKStatus struct {+ StatusMsg string `json:"status"`+}++func (r *OKStatus) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "status": String(&r.StatusMsg).Required(),+ })+}++func (*OKStatus) Status() int { return http.StatusOK }++// --- Cookies ---++type CookieRequest struct {+ SessionID string `json:"-"`+ UserID string `json:"-"`+}++func (r *CookieRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "session_id": String(&r.SessionID).From(SourceCookie).Required(),+ "user_id": String(&r.UserID).From(SourceCookie).Optional(),+ }).Title("CookieRequest")+}++type CookieResponse struct {+ SessionID string `json:"sessionId"`+ UserID string `json:"userId"`+}++func (r *CookieResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "sessionId": String(&r.SessionID).Required(),+ "userId": String(&r.UserID).Optional(),+ })+}++func (*CookieResponse) Status() int { return http.StatusOK }++// --- Date query param ---++type TimeQueryRequest struct {+ ID string `json:"-"`+ StartDate string `json:"-"`+}++func (r *TimeQueryRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "id": String(&r.ID).From(SourcePath).Required().UUID(),+ "startDate": String(&r.StartDate).From(SourceQuery).Optional().Description("Start date in YYYY-MM-DD format"),+ }).Title("TimeQueryRequest")+}++type TimeResponse struct {+ ID string `json:"id"`+ StartDate string `json:"startDate,omitempty"`+}++func (r *TimeResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "id": String(&r.ID).Required(),+ "startDate": String(&r.StartDate).Optional(),+ })+}++func (*TimeResponse) Status() int { return http.StatusOK }++// --- Pattern validation ---++type PatternRequest struct {+ Code string `json:"code"`+ Phone string `json:"phone"`+ SlugField string `json:"slug"`+}++func (r *PatternRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "code": String(&r.Code).Required().Pattern(`^[A-Z]{3}-\d{4}$`).Description("Format: XXX-0000"),+ "phone": String(&r.Phone).Optional().Pattern(`^\+\d{1,3}-\d{3}-\d{3}-\d{4}$`),+ "slug": String(&r.SlugField).Optional().Pattern(`^[a-z0-9]+(?:-[a-z0-9]+)*$`),+ }).Title("PatternRequest")+}++func (*PatternRequest) Status() int { return http.StatusOK }++// --- URL/URI format ---++type URLRequest struct {+ Website string `json:"website"`+ Callback string `json:"callback"`+ ResourceURI string `json:"resourceUri"`+}++func (r *URLRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "website": String(&r.Website).Required().URL(),+ "callback": String(&r.Callback).Optional().URL(),+ "resourceUri": String(&r.ResourceURI).Optional().URI(),+ }).Title("URLRequest")+}++func (*URLRequest) Status() int { return http.StatusOK }++// --- Float validation ---++type MeasurementRequest struct {+ Temperature float64 `json:"temperature"`+ Humidity float64 `json:"humidity"`+ Pressure float64 `json:"pressure"`+}++func (r *MeasurementRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "temperature": Float(&r.Temperature).Required().Min(-273.15).Max(1000),+ "humidity": Float(&r.Humidity).Optional().Min(0).Max(100),+ "pressure": Float(&r.Pressure).Optional().Min(0),+ }).Title("MeasurementRequest")+}++func (*MeasurementRequest) Status() int { return http.StatusOK }++// --- Array with custom validation ---++type TagsRequest struct {+ Name string `json:"name"`+ Tags []string `json:"tags"`+}++func (r *TagsRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "name": String(&r.Name).Required(),+ "tags": Array(String(nil)).+ Required().+ MinItems(1).+ MaxItems(5).+ Description("At least 1, at most 5 tags").+ ValidateFn(func() []ValidationError {+ var errs []ValidationError+ if len(r.Tags) < 1 {+ errs = append(errs, ValidationError{Code: "min_items", Message: "must have at least 1 tag"})+ }+ if len(r.Tags) > 5 {+ errs = append(errs, ValidationError{Code: "max_items", Message: "must have at most 5 tags"})+ }+ return errs+ }).+ IsPresentFn(func() bool { return len(r.Tags) > 0 }),+ }).Title("TagsRequest")+}++func (*TagsRequest) Status() int { return http.StatusOK }++// --- Nested object ---++type CreateOrderRequest struct {+ CustomerName string `json:"customerName"`+ ShippingAddress struct {+ Street string `json:"street"`+ City string `json:"city"`+ ZipCode string `json:"zipCode"`+ Country string `json:"country"`+ } `json:"shippingAddress"`+}++func (r *CreateOrderRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "customerName": String(&r.CustomerName).Required().MinLength(1),+ "shippingAddress": Object(map[string]Schema{+ "street": String(&r.ShippingAddress.Street).Required().MinLength(1).MaxLength(200),+ "city": String(&r.ShippingAddress.City).Required().MinLength(1).MaxLength(100),+ "zipCode": String(&r.ShippingAddress.ZipCode).Required().Pattern(`^\d{5}(-\d{4})?$`),+ "country": String(&r.ShippingAddress.Country).Required().Enum("US", "CA", "UK", "DE"),+ }).Required(),+ }).Title("CreateOrderRequest")+}++func (*CreateOrderRequest) Status() int { return http.StatusOK }++// --- Nullable fields bound to actual pointer struct fields ---++type NullableRequest struct {+ Name string `json:"name"`+ Nickname *string `json:"nickname"`+ Age *int `json:"age"`+}++func (r *NullableRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "name": String(&r.Name).Required(),+ "nickname": String(r.Nickname).Optional().Nullable(),+ "age": Int(r.Age).Optional().Nullable().Min(0),+ }).Title("NullableRequest")+}++type NullableResponse struct {+ Name string `json:"name"`+ HasNickname bool `json:"hasNickname"`+ HasAge bool `json:"hasAge"`+}++func (r *NullableResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "name": String(&r.Name).Required(),+ "hasNickname": Bool(&r.HasNickname).Required(),+ "hasAge": Bool(&r.HasAge).Required(),+ })+}++func (*NullableResponse) Status() int { return http.StatusOK }++// --- Context echo (reads headers, sets headers / cookies) ---++type ContextRequest struct {+ Data string `json:"data"`+}++func (r *ContextRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "data": String(&r.Data).Optional(),+ }).Title("ContextRequest")+}++type ContextResponse struct {+ ReceivedHeader string `json:"receivedHeader"`+ Data string `json:"data"`+}++func (r *ContextResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "receivedHeader": String(&r.ReceivedHeader).Optional(),+ "data": String(&r.Data).Optional(),+ })+}++func (*ContextResponse) Status() int { return http.StatusOK }++// --- Discriminated union ---++type PetUnion interface {+ Union+ petMarker()+}++type DogPet struct {+ UnionBase+ Type string `json:"type"`+ Name string `json:"name"`+ Breed string `json:"breed"`+}++func (d *DogPet) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "type": String(&d.Type).Required(),+ "name": String(&d.Name).Required().MinLength(1),+ "breed": String(&d.Breed).Required().MinLength(1),+ }).Title("DogPet")+}+func (d *DogPet) unionMarker() {}+func (d *DogPet) petMarker() {}++type CatPet struct {+ UnionBase+ Type string `json:"type"`+ Name string `json:"name"`+ Indoor bool `json:"indoor"`+}++func (c *CatPet) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "type": String(&c.Type).Required(),+ "name": String(&c.Name).Required().MinLength(1),+ "indoor": Bool(&c.Indoor).Optional(),+ }).Title("CatPet")+}+func (c *CatPet) unionMarker() {}+func (c *CatPet) petMarker() {}++var PetUnionDef = UnionDef[PetUnion]{+ Discriminator: "type",+ Variants: map[string]func() PetUnion{+ "dog": func() PetUnion { return &DogPet{} },+ "cat": func() PetUnion { return &CatPet{} },+ },+}++type AdoptPetRequest struct {+ AdopterName string `json:"adopterName"`+ Pet PetUnion `json:"-"`+}++func (r *AdoptPetRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "adopterName": String(&r.AdopterName).Required().MinLength(1),+ "pet": UnionField(&r.Pet, PetUnionDef).Required(),+ }).Title("AdoptPetRequest")+}++func (r *AdoptPetRequest) UnmarshalJSON(data []byte) error {+ type plain AdoptPetRequest+ if err := json.Unmarshal(data, (*plain)(r)); err != nil {+ return err+ }+ return ParseUnions(data, U("pet", &r.Pet, PetUnionDef))+}++type AdoptResponse struct {+ Adopter string `json:"adopter"`+ PetType string `json:"petType"`+ PetName string `json:"petName"`+}++func (r *AdoptResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "adopter": String(&r.Adopter).Required(),+ "petType": String(&r.PetType).Required(),+ "petName": String(&r.PetName).Required(),+ })+}++func (*AdoptResponse) Status() int { return http.StatusCreated }++// --- Multi-status response types ---++type ProcessResult interface {+ TypedResponse+ processMarker()+}++type ProcessOK struct {+ StatusMsg string `json:"status"`+}++func (r *ProcessOK) Schema() *ObjectSchema {+ return Object(map[string]Schema{"status": String(&r.StatusMsg).Required()})+}+func (*ProcessOK) Status() int { return http.StatusOK }+func (*ProcessOK) processMarker() {}++type ProcessCreated struct {+ ID string `json:"id"`+}++func (r *ProcessCreated) Schema() *ObjectSchema {+ return Object(map[string]Schema{"id": String(&r.ID).Required()})+}+func (*ProcessCreated) Status() int { return http.StatusCreated }+func (*ProcessCreated) processMarker() {}++type ProcessAccepted struct {+ StatusMsg string `json:"status"`+}++func (r *ProcessAccepted) Schema() *ObjectSchema {+ return Object(map[string]Schema{"status": String(&r.StatusMsg).Required()})+}+func (*ProcessAccepted) Status() int { return http.StatusAccepted }+func (*ProcessAccepted) processMarker() {}++type ProcessNoContent struct{}++func (*ProcessNoContent) Schema() *ObjectSchema { return nil }+func (*ProcessNoContent) Status() int { return http.StatusNoContent }+func (*ProcessNoContent) processMarker() {}++type ProcessCustom struct {+ StatusMsg string `json:"status"`+}++func (r *ProcessCustom) Schema() *ObjectSchema {+ return Object(map[string]Schema{"status": String(&r.StatusMsg).Required()})+}+func (*ProcessCustom) Status() int { return 207 }+func (*ProcessCustom) processMarker() {}++// --- Health response ---++type HealthResponse struct {+ StatusMsg string `json:"status"`+}++func (r *HealthResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{"status": String(&r.StatusMsg).Required()})+}+func (*HealthResponse) Status() int { return http.StatusOK }++// =============================================================================+// Handlers+//+// One generic echo for the "just bounce the parsed request back" cases.+// Custom handlers only for the things that need server-side behavior+// (errors, status codes, header/cookie writes).+// =============================================================================++func errorByName(_ context.Context, req *SimpleRequest) (OKStatus, error) {+ switch req.Name {+ case "conflict":+ return OKStatus{}, Conflict("item %s already exists", req.Name)+ case "notfound":+ return OKStatus{}, NotFound("item not found")+ case "forbidden":+ return OKStatus{}, Forbidden("access denied")+ }+ return OKStatus{StatusMsg: "ok"}, nil+}++func errorByType(_ context.Context, req *ErrorTypeRequest) (OKStatus, error) {+ switch req.ErrorType {+ case "bad-request":+ return OKStatus{}, BadRequest("invalid input")+ case "unauthorized":+ return OKStatus{}, Unauthorized("not authenticated")+ case "forbidden":+ return OKStatus{}, Forbidden("access denied")+ case "not-found":+ return OKStatus{}, NotFound("resource not found")+ case "conflict":+ return OKStatus{}, Conflict("resource already exists")+ case "unprocessable":+ return OKStatus{}, UnprocessableEntity("cannot process")+ case "rate-limit":+ return OKStatus{}, RateLimit("too many requests")+ case "internal":+ return OKStatus{}, InternalServer("something broke")+ case "database":+ return OKStatus{}, DatabaseErr("db connection failed")+ case "gateway-timeout":+ return OKStatus{}, GatewayTimeout("upstream timeout")+ }+ return OKStatus{StatusMsg: "ok"}, nil+}++func statusByName(_ context.Context, req *SimpleRequest) (ProcessResult, error) {+ switch req.Name {+ case "create":+ return &ProcessCreated{ID: "new-id"}, nil+ case "accepted":+ return &ProcessAccepted{StatusMsg: "processing"}, nil+ case "nocontent":+ return &ProcessNoContent{}, nil+ case "custom":+ return &ProcessCustom{StatusMsg: "multi-status"}, nil+ }+ return &ProcessOK{StatusMsg: "ok"}, nil+}++func contextEcho(ctx context.Context, req *ContextRequest) (ContextResponse, error) {+ httpCtx := HTTP(ctx)+ if httpCtx == nil {+ return ContextResponse{}, InternalServer("no http context")+ }+ customHeader := httpCtx.Header("X-Custom-Header")+ httpCtx.SetHeader("X-Response-Header", "response-value")+ httpCtx.SetCookie(&http.Cookie{Name: "test_cookie", Value: "cookie-value"})+ return ContextResponse{ReceivedHeader: customHeader, Data: req.Data}, nil+}++func getItemEcho(_ context.Context, req *GetItemRequest) (FullResponse, error) {+ return FullResponse{+ ID: req.ID,+ Name: "Test Item",+ Email: "[email protected]",+ Page: req.Page,+ PageSize: req.PageSize,+ Search: req.Search,+ StatusField: req.StatusField,+ }, nil+}++func updateItemEcho(_ context.Context, req *FullRequest) (FullResponse, error) {+ return FullResponse{+ ID: req.ID,+ Name: req.Name,+ Email: req.Email,+ Page: req.Page,+ PageSize: req.PageSize,+ Tags: req.Tags,+ }, nil+}++func deleteItemEcho(_ context.Context, _ *DeleteItemRequest) (Deleted, error) {+ return Deleted{}, nil+}++func createItem(_ context.Context, req *SimpleRequest) (CreatedSimpleResponse, error) {+ return CreatedSimpleResponse{+ SimpleResponse: SimpleResponse{+ ID: uuid.New().String(),+ Name: req.Name,+ Email: req.Email,+ Count: req.Count,+ },+ }, nil+}++func cookieEcho(_ context.Context, req *CookieRequest) (CookieResponse, error) {+ return CookieResponse{SessionID: req.SessionID, UserID: req.UserID}, nil+}++func timeEcho(_ context.Context, req *TimeQueryRequest) (TimeResponse, error) {+ return TimeResponse{ID: req.ID, StartDate: req.StartDate}, nil+}++func adoptEcho(_ context.Context, req *AdoptPetRequest) (AdoptResponse, error) {+ var petType, petName string+ switch p := req.Pet.(type) {+ case *DogPet:+ petType, petName = "dog", p.Name+ case *CatPet:+ petType, petName = "cat", p.Name+ }+ return AdoptResponse{+ Adopter: req.AdopterName,+ PetType: petType,+ PetName: petName,+ }, nil+}++func nullableEcho(_ context.Context, req *NullableRequest) (NullableResponse, error) {+ return NullableResponse{+ Name: req.Name,+ HasNickname: req.Nickname != nil,+ HasAge: req.Age != nil,+ }, nil+}++func patternEcho(_ context.Context, req *PatternRequest) (PatternRequest, error) {+ return *req, nil+}++func urlEcho(_ context.Context, req *URLRequest) (URLRequest, error) {+ return *req, nil+}++func measurementEcho(_ context.Context, req *MeasurementRequest) (MeasurementRequest, error) {+ return *req, nil+}++func tagsEcho(_ context.Context, req *TagsRequest) (TagsRequest, error) {+ return *req, nil+}++func orderEcho(_ context.Context, req *CreateOrderRequest) (CreateOrderRequest, error) {+ return *req, nil+}++func healthHandler(_ context.Context, _ *EmptyRequest) (HealthResponse, error) {+ return HealthResponse{StatusMsg: "healthy"}, nil+}++// =============================================================================+// Shared server setup+// =============================================================================++func testErrorHandler(_ context.Context, err error) *ErrorBody {+ if apiErr, ok := AsError(err); ok {+ return &ErrorBody{+ StatusCode: apiErr.Status,+ Message: apiErr.Message,+ Error: apiErr.Name,+ Details: apiErr.Details,+ }+ }+ if validationErrs, ok := AsValidationErrors(err); ok {+ return &ErrorBody{+ StatusCode: 400,+ Message: "Validation failed",+ Error: "ValidationError",+ Details: validationErrs,+ }+ }+ return &ErrorBody{StatusCode: 500, Message: "Internal server error", Error: "InternalServerError"}+}++func setupTestServer(t *testing.T) (*httptest.Server, *Router) {+ t.Helper()+ app := NewApp(AppConfig{ErrorHandler: testErrorHandler})++ r := NewRouter(RouterConfig{App: app})++ // --- Body validation ---+ r.POST("/items", Handler(app, createItem).+ Summary("Create item").+ OperationID("createItem").+ Tags("Items"))++ // --- Path + query (no body) ---+ r.GET("/items/{id}", Handler(app, getItemEcho).+ Summary("Get item").+ OperationID("getItem").+ Tags("Items"))++ // --- Path + query + header + body ---+ r.PUT("/items/{id}", Handler(app, updateItemEcho).+ Summary("Update item").+ OperationID("updateItem").+ Tags("Items"))++ // --- Path only / no content response ---+ r.DELETE("/items/{id}", Handler(app, deleteItemEcho).+ Summary("Delete item").+ OperationID("deleteItem").+ Tags("Items"))++ // --- Application errors ---+ r.POST("/error", Handler(app, errorByName).+ Summary("Trigger error by name").+ Tags("Errors"))++ r.GET("/error/{type}", Handler(app, errorByType).+ Summary("Trigger error by type").+ Tags("Errors"))++ // --- Schema features ---+ r.POST("/codes", Handler(app, patternEcho).Tags("Schema"))+ r.POST("/links", Handler(app, urlEcho).Tags("Schema"))+ r.POST("/measurements", Handler(app, measurementEcho).Tags("Schema"))+ r.POST("/tagged", Handler(app, tagsEcho).Tags("Schema"))+ r.POST("/orders", Handler(app, orderEcho).Tags("Orders"))+ r.POST("/nullable", Handler(app, nullableEcho).Tags("Schema"))+ r.POST("/adopt", Handler(app, adoptEcho).Tags("Pets"))++ // --- Cookie source ---+ r.GET("/session", Handler(app, cookieEcho).Tags("Session"))++ // --- Date query ---+ r.GET("/events/{id}", Handler(app, timeEcho).Tags("Events"))++ // --- Status codes (multi-status) ---+ r.POST("/process", InterfaceHandler(app, statusByName).+ Tags("Process").+ Responses(&ProcessOK{}, &ProcessCreated{}, &ProcessAccepted{}, &ProcessNoContent{}, &ProcessCustom{}))++ // --- HTTPContext ---+ r.POST("/context-test", Handler(app, contextEcho).Tags("Context"))++ // --- Health ---+ r.GET("/health", Handler(app, healthHandler).Tags("Health"))++ srv := httptest.NewServer(r)+ t.Cleanup(srv.Close)+ return srv, r+}++// =============================================================================+// HTTP helpers+// =============================================================================++// m is a shorthand for inline JSON bodies in the test table.+type m = map[string]any++// do issues an HTTP request and reads the full body. The response body is+// auto-closed via t.Cleanup, so callers don't have to.+func do(t *testing.T, srv *httptest.Server, method, path string, body any, headers map[string]string, cookies []*http.Cookie) (resp *http.Response, respBody []byte) {+ t.Helper()++ var reader io.Reader+ if body != nil {+ b, err := json.Marshal(body)+ require.NoError(t, err)+ reader = bytes.NewReader(b)+ }++ req, err := http.NewRequestWithContext(context.Background(), method, srv.URL+path, reader)+ require.NoError(t, err)+ if body != nil {+ req.Header.Set("Content-Type", "application/json")+ }+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ for _, c := range cookies {+ req.AddCookie(c)+ }++ resp, err = http.DefaultClient.Do(req)+ require.NoError(t, err)+ t.Cleanup(func() { _ = resp.Body.Close() })++ respBody, err = io.ReadAll(resp.Body)+ require.NoError(t, err)++ return resp, respBody+}++// assertFieldError checks that the response body contains a validation error+// targeting the named field. Order-insensitive.+func assertFieldError(t *testing.T, body []byte, field string) {+ t.Helper()++ var errBody ErrorBody+ require.NoError(t, json.Unmarshal(body, &errBody), "body: %s", string(body))++ details, _ := errBody.Details.([]any)+ require.NotEmpty(t, details, "expected validation details, body: %s", string(body))++ for _, d := range details {+ if dm, _ := d.(map[string]any); dm != nil && dm["field"] == field {+ return+ }+ }+ t.Errorf("expected validation error for field %q, got: %s", field, string(body))+}++// jsonBody decodes a JSON body into the requested type.+func jsonBody[T any](t *testing.T, body []byte) T {+ t.Helper()+ var v T+ require.NoError(t, json.Unmarshal(body, &v), "body: %s", string(body))+ return v+}++// =============================================================================+// TestHTTP — one table over every integration case+// =============================================================================++func TestHTTP(t *testing.T) {+ server, _ := setupTestServer(t)++ validUUID := uuid.New().String()+ longName := string(make([]byte, 51))++ tests := []struct {+ name string+ method string+ path string+ body any+ headers map[string]string+ cookies []*http.Cookie+ wantStatus int+ wantField string // optional: assert validation error has this field+ wantErrorName string // optional: assert error body's "error" field+ verify func(t *testing.T, resp *http.Response, body []byte)+ }{+ // --- body validation ---+ {name: "body/missing required name", method: "POST", path: "/items", body: m{"email": "[email protected]"}, wantStatus: 400, wantField: "name"},+ {name: "body/invalid email format", method: "POST", path: "/items", body: m{"name": "Test", "email": "not-an-email"}, wantStatus: 400, wantField: "email"},+ {name: "body/name too short", method: "POST", path: "/items", body: m{"name": "A", "email": "[email protected]"}, wantStatus: 400, wantField: "name"},+ {name: "body/name too long", method: "POST", path: "/items", body: m{"name": longName, "email": "[email protected]"}, wantStatus: 400, wantField: "name"},+ {name: "body/count below minimum", method: "POST", path: "/items", body: m{"name": "Test", "email": "[email protected]", "count": -1}, wantStatus: 400, wantField: "count"},+ {name: "body/count above maximum", method: "POST", path: "/items", body: m{"name": "Test", "email": "[email protected]", "count": 1001}, wantStatus: 400, wantField: "count"},+ {name: "body/valid simple request", method: "POST", path: "/items", body: m{"name": "Test Item", "email": "[email protected]", "count": 42}, wantStatus: 201,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]any](t, body)+ assert.Equal(t, "Test Item", r["name"])+ assert.Equal(t, "[email protected]", r["email"])+ assert.Equal(t, float64(42), r["count"])+ }},++ // --- path / query ---+ {name: "path/invalid uuid", method: "GET", path: "/items/not-a-uuid", wantStatus: 400},+ {name: "query/invalid enum", method: "GET", path: "/items/" + validUUID + "?status=invalid", wantStatus: 400},+ {name: "query/defaults applied", method: "GET", path: "/items/" + validUUID, wantStatus: 200,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]any](t, body)+ assert.Equal(t, float64(1), r["page"])+ assert.Equal(t, float64(20), r["pageSize"])+ }},+ {name: "query/all params honored", method: "GET", path: "/items/" + validUUID + "?page=5&pageSize=50&search=test&status=active", wantStatus: 200,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]any](t, body)+ assert.Equal(t, float64(5), r["page"])+ assert.Equal(t, float64(50), r["pageSize"])+ assert.Equal(t, "test", r["search"])+ assert.Equal(t, "active", r["status"])+ }},+ {name: "query/partial defaults", method: "GET", path: "/items/" + validUUID + "?page=3", wantStatus: 200,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]any](t, body)+ assert.Equal(t, float64(3), r["page"])+ assert.Equal(t, float64(20), r["pageSize"])+ }},++ // --- full request ---+ {name: "full/valid PUT with body+query", method: "PUT", path: "/items/" + validUUID + "?page=2",+ body: m{"name": "Updated", "email": "[email protected]", "tags": []string{"tag1", "tag2"}},+ wantStatus: 200,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]any](t, body)+ assert.Equal(t, "Updated", r["name"])+ assert.Equal(t, float64(2), r["page"])+ }},++ // --- delete / no content ---+ {name: "delete/returns 204", method: "DELETE", path: "/items/" + validUUID, wantStatus: 204},++ // --- application errors via body name ---+ {name: "app-err/conflict", method: "POST", path: "/error", body: m{"name": "conflict", "email": "[email protected]"}, wantStatus: 409,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ e := jsonBody[ErrorBody](t, body)+ assert.Equal(t, "Conflict", e.Error)+ assert.Equal(t, "item conflict already exists", e.Message)+ }},+ {name: "app-err/not found", method: "POST", path: "/error", body: m{"name": "notfound", "email": "[email protected]"}, wantStatus: 404,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ assert.Equal(t, "NotFound", jsonBody[ErrorBody](t, body).Error)+ }},+ {name: "app-err/forbidden", method: "POST", path: "/error", body: m{"name": "forbidden", "email": "[email protected]"}, wantStatus: 403,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ assert.Equal(t, "ForbiddenError", jsonBody[ErrorBody](t, body).Error)+ }},++ // --- application errors via path-source dispatch ---+ {name: "err-type/bad-request", method: "GET", path: "/error/bad-request", wantStatus: 400, wantErrorName: "BadRequest"},+ {name: "err-type/unauthorized", method: "GET", path: "/error/unauthorized", wantStatus: 401, wantErrorName: "UnauthorizedError"},+ {name: "err-type/forbidden", method: "GET", path: "/error/forbidden", wantStatus: 403, wantErrorName: "ForbiddenError"},+ {name: "err-type/not-found", method: "GET", path: "/error/not-found", wantStatus: 404, wantErrorName: "NotFound"},+ {name: "err-type/conflict", method: "GET", path: "/error/conflict", wantStatus: 409, wantErrorName: "Conflict"},+ {name: "err-type/unprocessable", method: "GET", path: "/error/unprocessable", wantStatus: 422, wantErrorName: "UnprocessableEntity"},+ {name: "err-type/rate-limit", method: "GET", path: "/error/rate-limit", wantStatus: 429, wantErrorName: "RateLimitExceeded"},+ {name: "err-type/internal", method: "GET", path: "/error/internal", wantStatus: 500, wantErrorName: "InternalServerError"},+ {name: "err-type/database", method: "GET", path: "/error/database", wantStatus: 500, wantErrorName: "DatabaseError"},+ {name: "err-type/gateway-timeout", method: "GET", path: "/error/gateway-timeout", wantStatus: 504, wantErrorName: "GatewayTimeoutError"},++ // --- pattern ---+ {name: "pattern/valid code", method: "POST", path: "/codes", body: m{"code": "ABC-1234"}, wantStatus: 200},+ {name: "pattern/lowercase code", method: "POST", path: "/codes", body: m{"code": "abc-1234"}, wantStatus: 400, wantField: "code"},+ {name: "pattern/wrong format", method: "POST", path: "/codes", body: m{"code": "ABCD-123"}, wantStatus: 400, wantField: "code"},+ {name: "pattern/valid phone", method: "POST", path: "/codes", body: m{"code": "ABC-1234", "phone": "+1-555-123-4567"}, wantStatus: 200},+ {name: "pattern/valid slug", method: "POST", path: "/codes", body: m{"code": "ABC-1234", "slug": "my-awesome-post"}, wantStatus: 200},+ {name: "pattern/invalid slug (uppercase)", method: "POST", path: "/codes", body: m{"code": "ABC-1234", "slug": "My-Post"}, wantStatus: 400, wantField: "slug"},++ // --- URL ---+ {name: "url/valid https", method: "POST", path: "/links", body: m{"website": "https://example.com"}, wantStatus: 200},+ {name: "url/valid http with path+query", method: "POST", path: "/links", body: m{"website": "http://example.com/path?query=1"}, wantStatus: 200},+ {name: "url/no scheme", method: "POST", path: "/links", body: m{"website": "example.com"}, wantStatus: 400, wantField: "website"},+ {name: "url/no host", method: "POST", path: "/links", body: m{"website": "https://"}, wantStatus: 400, wantField: "website"},+ {name: "url/relative uri", method: "POST", path: "/links", body: m{"website": "https://example.com", "resourceUri": "/api/v1/users"}, wantStatus: 200},++ // --- floats ---+ {name: "float/valid measurements", method: "POST", path: "/measurements", body: m{"temperature": 25.5, "humidity": 60.0, "pressure": 1013.25}, wantStatus: 200},+ {name: "float/below absolute zero", method: "POST", path: "/measurements", body: m{"temperature": -300.0}, wantStatus: 400, wantField: "temperature"},+ {name: "float/humidity over 100", method: "POST", path: "/measurements", body: m{"temperature": 20.0, "humidity": 150.0}, wantStatus: 400, wantField: "humidity"},+ {name: "float/negative pressure", method: "POST", path: "/measurements", body: m{"temperature": 20.0, "pressure": -10.0}, wantStatus: 400, wantField: "pressure"},++ // --- arrays ---+ {name: "array/valid tags", method: "POST", path: "/tagged", body: m{"name": "Item", "tags": []string{"go", "api", "test"}}, wantStatus: 200},+ {name: "array/empty tags", method: "POST", path: "/tagged", body: m{"name": "Item", "tags": []string{}}, wantStatus: 400, wantField: "tags"},+ {name: "array/too many tags", method: "POST", path: "/tagged", body: m{"name": "Item", "tags": []string{"a", "b", "c", "d", "e", "f"}}, wantStatus: 400, wantField: "tags"},+ {name: "array/missing tags", method: "POST", path: "/tagged", body: m{"name": "Item"}, wantStatus: 400, wantField: "tags"},++ // --- nested object ---+ {name: "nested/valid order", method: "POST", path: "/orders",+ body: m{+ "customerName": "John Doe",+ "shippingAddress": m{+ "street": "123 Main St", "city": "New York", "zipCode": "10001", "country": "US",+ },+ },+ wantStatus: 200},+ {name: "nested/missing required nested field", method: "POST", path: "/orders",+ body: m{+ "customerName": "John Doe",+ "shippingAddress": m{+ "street": "123 Main St", "city": "New York", "country": "US",+ },+ },+ wantStatus: 400, wantField: "shippingAddress.zipCode"},+ {name: "nested/invalid nested enum", method: "POST", path: "/orders",+ body: m{+ "customerName": "John Doe",+ "shippingAddress": m{+ "street": "123 Main St", "city": "Tokyo", "zipCode": "12345", "country": "JP",+ },+ },+ wantStatus: 400, wantField: "shippingAddress.country"},+ {name: "nested/invalid nested pattern", method: "POST", path: "/orders",+ body: m{+ "customerName": "John Doe",+ "shippingAddress": m{+ "street": "123 Main St", "city": "NYC", "zipCode": "ABCDE", "country": "US",+ },+ },+ wantStatus: 400, wantField: "shippingAddress.zipCode"},++ // --- cookies ---+ {name: "cookie/both present", method: "GET", path: "/session", wantStatus: 200,+ cookies: []*http.Cookie{+ {Name: "session_id", Value: "sess-123"},+ {Name: "user_id", Value: "user-456"},+ },+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]string](t, body)+ assert.Equal(t, "sess-123", r["sessionId"])+ assert.Equal(t, "user-456", r["userId"])+ }},+ {name: "cookie/required missing", method: "GET", path: "/session", wantStatus: 400},++ // --- time query ---+ {name: "time/with date query param", method: "GET", path: "/events/" + validUUID + "?startDate=2024-01-15", wantStatus: 200,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]any](t, body)+ assert.Equal(t, "2024-01-15", r["startDate"])+ }},+ {name: "time/without optional query", method: "GET", path: "/events/" + validUUID, wantStatus: 200},++ // --- status codes ---+ {name: "status/created", method: "POST", path: "/process", body: m{"name": "create", "email": "[email protected]"}, wantStatus: 201},+ {name: "status/accepted", method: "POST", path: "/process", body: m{"name": "accepted", "email": "[email protected]"}, wantStatus: 202},+ {name: "status/no content", method: "POST", path: "/process", body: m{"name": "nocontent", "email": "[email protected]"}, wantStatus: 204},+ {name: "status/custom 207", method: "POST", path: "/process", body: m{"name": "custom", "email": "[email protected]"}, wantStatus: 207},+ {name: "status/default 200", method: "POST", path: "/process", body: m{"name": "other", "email": "[email protected]"}, wantStatus: 200},++ // --- HTTPContext ---+ {name: "ctx/reads header / sets header+cookie", method: "POST", path: "/context-test",+ body: m{"data": "test"},+ headers: map[string]string{"X-Custom-Header": "custom-value"},+ wantStatus: 200,+ verify: func(t *testing.T, resp *http.Response, body []byte) {+ assert.Equal(t, "response-value", resp.Header.Get("X-Response-Header"))+ var foundCookie bool+ for _, c := range resp.Cookies() {+ if c.Name == "test_cookie" && c.Value == "cookie-value" {+ foundCookie = true+ }+ }+ assert.True(t, foundCookie, "should have set test_cookie")+ r := jsonBody[map[string]string](t, body)+ assert.Equal(t, "custom-value", r["receivedHeader"])+ }},++ // --- discriminated union ---+ {name: "union/adopt dog", method: "POST", path: "/adopt",+ body: m{+ "adopterName": "John",+ "pet": m{"type": "dog", "name": "Buddy", "breed": "Golden Retriever"},+ },+ wantStatus: 201,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]string](t, body)+ assert.Equal(t, "dog", r["petType"])+ assert.Equal(t, "Buddy", r["petName"])+ }},+ {name: "union/adopt cat", method: "POST", path: "/adopt",+ body: m{+ "adopterName": "Jane",+ "pet": m{"type": "cat", "name": "Whiskers", "indoor": true},+ },+ wantStatus: 201,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ assert.Equal(t, "cat", jsonBody[map[string]string](t, body)["petType"])+ }},+ {name: "union/unknown pet type returns 500", method: "POST", path: "/adopt",+ body: m{"adopterName": "Bob", "pet": m{"type": "fish", "name": "Nemo"}},+ wantStatus: 500},+ {name: "union/missing pet field", method: "POST", path: "/adopt",+ body: m{"adopterName": "Alice"},+ wantStatus: 400, wantField: "pet"},++ // --- nullable ---+ {name: "nullable/all fields present", method: "POST", path: "/nullable",+ body: m{"name": "John", "nickname": "Johnny", "age": 30},+ wantStatus: 200,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]any](t, body)+ assert.Equal(t, true, r["hasNickname"])+ assert.Equal(t, true, r["hasAge"])+ }},+ {name: "nullable/optional fields omitted", method: "POST", path: "/nullable",+ body: m{"name": "John"},+ wantStatus: 200,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]any](t, body)+ assert.Equal(t, false, r["hasNickname"])+ assert.Equal(t, false, r["hasAge"])+ }},+ {name: "nullable/optional fields explicit null", method: "POST", path: "/nullable",+ body: m{"name": "John", "nickname": nil, "age": nil},+ wantStatus: 200,+ verify: func(t *testing.T, _ *http.Response, body []byte) {+ r := jsonBody[map[string]any](t, body)+ assert.Equal(t, false, r["hasNickname"])+ assert.Equal(t, false, r["hasAge"])+ }},+ {name: "nullable/age below minimum", method: "POST", path: "/nullable",+ body: m{"name": "John", "age": -5},+ wantStatus: 400, wantField: "age"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ //nolint:bodyclose // Response body is closed by do() via t.Cleanup+ resp, body := do(t, server, tt.method, tt.path, tt.body, tt.headers, tt.cookies)++ assert.Equal(t, tt.wantStatus, resp.StatusCode, "body: %s", string(body))++ if tt.wantField != "" {+ assertFieldError(t, body, tt.wantField)+ }+ if tt.wantErrorName != "" {+ assert.Equal(t, tt.wantErrorName, jsonBody[ErrorBody](t, body).Error)+ }+ if tt.verify != nil {+ tt.verify(t, resp, body)+ }+ })+ }+}diff --git a/backend-go/pkg/api/ispresent_test.go b/backend-go/pkg/api/ispresent_test.goindex 42d2a5beb6..68cd819476 100644--- a/backend-go/pkg/api/ispresent_test.go+++ b/backend-go/pkg/api/ispresent_test.go@@ -9,339 +9,153 @@ import ("github.com/stretchr/testify/assert")-// --- IsPresent Tests for Primitive Types -----func TestStringSchema_IsPresent(t *testing.T) {- t.Run("nil pointer", func(t *testing.T) {- schema := String(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("empty string", func(t *testing.T) {- val := ""- schema := String(&val)- assert.False(t, schema.IsPresent())- })-- t.Run("non-empty string", func(t *testing.T) {- val := "hello"- schema := String(&val)- assert.True(t, schema.IsPresent())- })-- t.Run("whitespace string", func(t *testing.T) {- val := " "- schema := String(&val)- assert.True(t, schema.IsPresent())- })-}--func TestIntSchema_IsPresent(t *testing.T) {- t.Run("nil pointer", func(t *testing.T) {- schema := Int(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("zero value", func(t *testing.T) {- val := 0- schema := Int(&val)- assert.True(t, schema.IsPresent()) // Zero is still present- })-- t.Run("non-zero value", func(t *testing.T) {- val := 42- schema := Int(&val)- assert.True(t, schema.IsPresent())- })-- t.Run("negative value", func(t *testing.T) {- val := -10- schema := Int(&val)- assert.True(t, schema.IsPresent())- })-}--func TestFloatSchema_IsPresent(t *testing.T) {- t.Run("nil pointer", func(t *testing.T) {- schema := Float(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("zero value", func(t *testing.T) {- val := 0.0- schema := Float(&val)- assert.True(t, schema.IsPresent())- })-- t.Run("non-zero value", func(t *testing.T) {- val := 3.14- schema := Float(&val)- assert.True(t, schema.IsPresent())- })-}--func TestBoolSchema_IsPresent(t *testing.T) {- t.Run("nil pointer", func(t *testing.T) {- schema := Bool(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("false value", func(t *testing.T) {- val := false- schema := Bool(&val)- assert.True(t, schema.IsPresent()) // false is still present- })-- t.Run("true value", func(t *testing.T) {- val := true- schema := Bool(&val)- assert.True(t, schema.IsPresent())- })-}--func TestUUIDSchema_IsPresent(t *testing.T) {- t.Run("nil pointer", func(t *testing.T) {- schema := UUID(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("nil UUID", func(t *testing.T) {- val := uuid.Nil- schema := UUID(&val)- assert.False(t, schema.IsPresent())- })-- t.Run("valid UUID", func(t *testing.T) {- val := uuid.New()- schema := UUID(&val)- assert.True(t, schema.IsPresent())- })-}--func TestTimeSchema_IsPresent(t *testing.T) {- t.Run("nil pointer", func(t *testing.T) {- schema := Time(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("zero time", func(t *testing.T) {- val := time.Time{}- schema := Time(&val)- assert.False(t, schema.IsPresent())- })-- t.Run("valid time", func(t *testing.T) {- val := time.Now()- schema := Time(&val)- assert.True(t, schema.IsPresent())- })-}--func TestBytesSchema_IsPresent(t *testing.T) {- t.Run("nil pointer", func(t *testing.T) {- schema := Bytes(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("empty bytes", func(t *testing.T) {- val := []byte{}- schema := Bytes(&val)- assert.False(t, schema.IsPresent())- })-- t.Run("non-empty bytes", func(t *testing.T) {- val := []byte{1, 2, 3}- schema := Bytes(&val)- assert.True(t, schema.IsPresent())- })-}--func TestAnySchema_IsPresent(t *testing.T) {- t.Run("nil pointer", func(t *testing.T) {- schema := Any(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("nil value", func(t *testing.T) {- var val any- schema := Any(&val)- assert.False(t, schema.IsPresent())- })-- t.Run("non-nil value", func(t *testing.T) {- var val any = "hello"- schema := Any(&val)- assert.True(t, schema.IsPresent())- })-}--func TestRawSchema_IsPresent(t *testing.T) {- t.Run("nil pointer", func(t *testing.T) {- schema := Raw(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("empty raw", func(t *testing.T) {- val := json.RawMessage{}- schema := Raw(&val)- assert.False(t, schema.IsPresent())- })-- t.Run("non-empty raw", func(t *testing.T) {- val := json.RawMessage(`{"foo": "bar"}`)- schema := Raw(&val)- assert.True(t, schema.IsPresent())- })+func TestSchema_IsPresent(t *testing.T) {+ validUUID := uuid.New()+ validTime := time.Now()++ tests := []struct {+ name string+ build func() Schema+ wantPresent bool+ }{+ // String+ {"string/nil", func() Schema { return String(nil) }, false},+ {"string/empty", func() Schema { v := ""; return String(&v) }, false},+ {"string/non-empty", func() Schema { v := "hello"; return String(&v) }, true},+ {"string/whitespace", func() Schema { v := " "; return String(&v) }, true},++ // Int+ {"int/nil", func() Schema { return Int(nil) }, false},+ {"int/zero", func() Schema { v := 0; return Int(&v) }, true},+ {"int/non-zero", func() Schema { v := 42; return Int(&v) }, true},+ {"int/negative", func() Schema { v := -10; return Int(&v) }, true},++ // Float+ {"float/nil", func() Schema { return Float(nil) }, false},+ {"float/zero", func() Schema { v := 0.0; return Float(&v) }, true},+ {"float/non-zero", func() Schema { v := 3.14; return Float(&v) }, true},++ // Bool+ {"bool/nil", func() Schema { return Bool(nil) }, false},+ {"bool/false", func() Schema { v := false; return Bool(&v) }, true},+ {"bool/true", func() Schema { v := true; return Bool(&v) }, true},++ // UUID+ {"uuid/nil", func() Schema { return UUID(nil) }, false},+ {"uuid/zero", func() Schema { v := uuid.Nil; return UUID(&v) }, false},+ {"uuid/valid", func() Schema { return UUID(&validUUID) }, true},++ // Time+ {"time/nil", func() Schema { return Time(nil) }, false},+ {"time/zero", func() Schema { v := time.Time{}; return Time(&v) }, false},+ {"time/valid", func() Schema { return Time(&validTime) }, true},++ // Bytes+ {"bytes/nil", func() Schema { return Bytes(nil) }, false},+ {"bytes/empty", func() Schema { v := []byte{}; return Bytes(&v) }, false},+ {"bytes/non-empty", func() Schema { v := []byte{1, 2, 3}; return Bytes(&v) }, true},++ // Any+ {"any/nil-ptr", func() Schema { return Any(nil) }, false},+ {"any/nil-value", func() Schema { var v any; return Any(&v) }, false},+ {"any/non-nil", func() Schema { var v any = "hello"; return Any(&v) }, true},++ // Raw+ {"raw/nil", func() Schema { return Raw(nil) }, false},+ {"raw/empty", func() Schema { v := json.RawMessage{}; return Raw(&v) }, false},+ {"raw/non-empty", func() Schema { v := json.RawMessage(`{"foo":"bar"}`); return Raw(&v) }, true},++ // Const+ {"const/nil", func() Schema { return Const(nil) }, false},+ {"const/value", func() Schema { return Const("fixed") }, true},++ // Ref+ {"ref", func() Schema { return Ref("#/components/schemas/User") }, false},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ schema := tt.build()+ assert.Equal(t, tt.wantPresent, schema.IsPresent())+ })+ }}-// --- IsPresent Tests for Composite Types -----func TestObjectSchema_IsPresent(t *testing.T) {- t.Run("no properties present", func(t *testing.T) {+func TestCompositeSchema_IsPresent(t *testing.T) {+ t.Run("object/none present", func(t *testing.T) {name := ""- schema := Object(map[string]Schema{- "name": String(&name),- })- // name is empty string = not present for string+ schema := Object(map[string]Schema{"name": String(&name)})assert.False(t, schema.IsPresent())})- t.Run("one property present", func(t *testing.T) {+ t.Run("object/one present", func(t *testing.T) {name := "John"- schema := Object(map[string]Schema{- "name": String(&name),- })+ schema := Object(map[string]Schema{"name": String(&name)})assert.True(t, schema.IsPresent())})- t.Run("multiple properties some present", func(t *testing.T) {+ t.Run("object/partial present", func(t *testing.T) {name := ""age := 25- schema := Object(map[string]Schema{- "name": String(&name),- "age": Int(&age),- })- assert.True(t, schema.IsPresent()) // age is present+ schema := Object(map[string]Schema{"name": String(&name), "age": Int(&age)})+ assert.True(t, schema.IsPresent())})-}-func TestArraySchema_IsPresent(t *testing.T) {- t.Run("no isPresentFn", func(t *testing.T) {+ t.Run("array/no fn", func(t *testing.T) {schema := Array(String(new(string)))- assert.False(t, schema.IsPresent()) // Default is false+ assert.False(t, schema.IsPresent())})- t.Run("with isPresentFn returning false", func(t *testing.T) {+ t.Run("array/empty", func(t *testing.T) {items := []string{}- schema := Array(String(new(string))).IsPresentFn(func() bool {- return len(items) > 0- })+ schema := Array(String(new(string))).IsPresentFn(func() bool { return len(items) > 0 })assert.False(t, schema.IsPresent())})- t.Run("with isPresentFn returning true", func(t *testing.T) {+ t.Run("array/non-empty", func(t *testing.T) {items := []string{"a", "b"}- schema := Array(String(new(string))).IsPresentFn(func() bool {- return len(items) > 0- })+ schema := Array(String(new(string))).IsPresentFn(func() bool { return len(items) > 0 })assert.True(t, schema.IsPresent())})-}-func TestMapSchema_IsPresent(t *testing.T) {- t.Run("no isPresentFn", func(t *testing.T) {+ t.Run("map/no fn", func(t *testing.T) {schema := Map(String(new(string)))assert.False(t, schema.IsPresent())})- t.Run("with isPresentFn returning true", func(t *testing.T) {+ t.Run("map/non-empty", func(t *testing.T) {m := map[string]string{"key": "value"}- schema := Map(String(new(string))).IsPresentFn(func() bool {- return len(m) > 0- })+ schema := Map(String(new(string))).IsPresentFn(func() bool { return len(m) > 0 })assert.True(t, schema.IsPresent())})-}-func TestOneOfSchema_IsPresent(t *testing.T) {- t.Run("no schema present", func(t *testing.T) {- strVal := ""- intVal := 0- schema := OneOfSchemas(- String(&strVal),- )- assert.False(t, schema.IsPresent())- _ = intVal+ t.Run("oneOf/none", func(t *testing.T) {+ v := ""+ assert.False(t, OneOfSchemas(String(&v)).IsPresent())})- t.Run("one schema present", func(t *testing.T) {- strVal := "hello"- schema := OneOfSchemas(- String(&strVal),- )- assert.True(t, schema.IsPresent())+ t.Run("oneOf/one", func(t *testing.T) {+ v := "hello"+ assert.True(t, OneOfSchemas(String(&v)).IsPresent())})-}-func TestAnyOfSchema_IsPresent(t *testing.T) {- t.Run("no schema present", func(t *testing.T) {- strVal := ""- schema := AnyOf(- String(&strVal),- )- assert.False(t, schema.IsPresent())+ t.Run("anyOf/none", func(t *testing.T) {+ v := ""+ assert.False(t, AnyOf(String(&v)).IsPresent())})- t.Run("one schema present", func(t *testing.T) {- strVal := "hello"- schema := AnyOf(- String(&strVal),- )- assert.True(t, schema.IsPresent())+ t.Run("anyOf/one", func(t *testing.T) {+ v := "hello"+ assert.True(t, AnyOf(String(&v)).IsPresent())})- t.Run("multiple schemas present", func(t *testing.T) {- strVal := "hello"- intVal := 42- schema := AnyOf(- String(&strVal),- Int(&intVal),- )- assert.True(t, schema.IsPresent())- })-}--func TestAllOfSchema_IsPresent(t *testing.T) {- t.Run("no schema present", func(t *testing.T) {- strVal := ""- schema := AllOf(- String(&strVal),- )- assert.False(t, schema.IsPresent())+ t.Run("allOf/none", func(t *testing.T) {+ v := ""+ assert.False(t, AllOf(String(&v)).IsPresent())})- t.Run("any schema present", func(t *testing.T) {- strVal := "hello"- schema := AllOf(- String(&strVal),- )- assert.True(t, schema.IsPresent())- })-}--func TestRefSchema_IsPresent(t *testing.T) {- schema := Ref("#/components/schemas/User")- assert.False(t, schema.IsPresent()) // Ref has no bound value-}--func TestConstSchema_IsPresent(t *testing.T) {- t.Run("nil value", func(t *testing.T) {- schema := Const(nil)- assert.False(t, schema.IsPresent())- })-- t.Run("non-nil value", func(t *testing.T) {- schema := Const("fixed")- assert.True(t, schema.IsPresent())+ t.Run("allOf/present", func(t *testing.T) {+ v := "hello"+ assert.True(t, AllOf(String(&v)).IsPresent())})}diff --git a/backend-go/pkg/api/openapi.go b/backend-go/pkg/api/openapi.goindex 4f23d3ff4a..1c62789040 100644--- a/backend-go/pkg/api/openapi.go+++ b/backend-go/pkg/api/openapi.go@@ -525,6 +525,14 @@ func (s *OpenAPISpec) generateResponses(ep *Endpoint) map[string]any {}func (s *OpenAPISpec) generateResponseObject(schema SchemaProvider, contentType, description string) map[string]any {+ objSchema := schema.Schema()+ if objSchema == nil {+ // No content response (e.g., 204)+ return map[string]any{+ "description": description,+ }+ }+if contentType == "" {contentType = "application/json"}@@ -533,7 +541,7 @@ func (s *OpenAPISpec) generateResponseObject(schema SchemaProvider, contentType,"description": description,"content": map[string]any{contentType: map[string]any{- "schema": schema.Schema().OpenAPI(),+ "schema": objSchema.OpenAPI(),},},}@@ -586,11 +594,24 @@ func (s *OpenAPISpec) generateComponents() map[string]any {components["securitySchemes"] = secSchemes}- if len(s.schemas) > 0 {- schemas := make(map[string]any)- for name, provider := range s.schemas {- schemas[name] = provider.Schema().OpenAPI()+ // Merge explicitly added schemas with registry schemas+ schemas := make(map[string]any)++ // Add schemas from DefaultRegistry (registered via .Ref())+ for name, schema := range DefaultRegistry.All() {+ if refable, ok := schema.(Refable); ok {+ schemas[name] = refable.Definition()+ } else {+ schemas[name] = schema.OpenAPI()}+ }++ // Add explicitly registered schemas (can override registry)+ for name, provider := range s.schemas {+ schemas[name] = provider.Schema().OpenAPI()+ }++ if len(schemas) > 0 {components["schemas"] = schemas}diff --git a/backend-go/pkg/api/openapi_test.go b/backend-go/pkg/api/openapi_test.goindex ae61b10d04..8e606b272d 100644--- a/backend-go/pkg/api/openapi_test.go+++ b/backend-go/pkg/api/openapi_test.go@@ -3,13 +3,16 @@ package apiimport ("encoding/json""net/http"+ "strings""testing""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")-// --- Test Types ---+// =============================================================================+// Shared test types+// =============================================================================type CreateUserRequest struct {Name string@@ -49,915 +52,440 @@ func (r *ErrorResponse) Schema() *ObjectSchema {}).Title("ErrorResponse")}-// --- OpenAPISpec Tests -----func TestNewOpenAPISpec(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }+type emptyResponse struct{}- spec := NewOpenAPISpec(config)- require.NotNil(t, spec)+func (r *emptyResponse) Schema() *ObjectSchema { return Object(nil) }- // Should default to 3.0.3- assert.Equal(t, "3.0.3", spec.config.OpenAPIVersion)+// schemaProviderWrapper wraps a raw *ObjectSchema as a SchemaProvider.+type schemaProviderWrapper struct {+ schema *ObjectSchema}-func TestOpenAPISpec_CustomVersion(t *testing.T) {- config := &OpenAPIConfig{- OpenAPIVersion: "3.1.0",- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }+func (w *schemaProviderWrapper) Schema() *ObjectSchema { return w.schema }- spec := NewOpenAPISpec(config)- assert.Equal(t, "3.1.0", spec.config.OpenAPIVersion)-}+// =============================================================================+// Helpers+// =============================================================================-func TestOpenAPISpec_Generate_Basic(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Description: "A test API",- Version: "1.0.0",- },+// minimalConfig returns a baseline OpenAPIConfig with required Info fields set.+func minimalConfig() *OpenAPIConfig {+ return &OpenAPIConfig{+ Info: OpenAPIInfo{Title: "Test API", Version: "1.0.0"},}-- spec := NewOpenAPISpec(config)- result := spec.Generate()-- assert.Equal(t, "3.0.3", result["openapi"])-- info := result["info"].(map[string]any)- assert.Equal(t, "Test API", info["title"])- assert.Equal(t, "A test API", info["description"])- assert.Equal(t, "1.0.0", info["version"])}-func TestOpenAPISpec_Generate_FullInfo(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Full API",- Description: "Complete API info",- Version: "2.0.0",- TermsOfService: "https://example.com/tos",- Contact: &OpenAPIContact{- Name: "API Support",- URL: "https://example.com/support",- Email: "[email protected]",- },- License: &OpenAPILicense{- Name: "MIT",- URL: "https://opensource.org/licenses/MIT",- },- },- }-+// generate builds a spec from config + endpoints and returns the Generate() output.+func generate(t *testing.T, config *OpenAPIConfig, endpoints ...Endpoint) map[string]any {+ t.Helper()spec := NewOpenAPISpec(config)- result := spec.Generate()-- info := result["info"].(map[string]any)- assert.Equal(t, "https://example.com/tos", info["termsOfService"])-- contact := info["contact"].(map[string]any)- assert.Equal(t, "API Support", contact["name"])- assert.Equal(t, "https://example.com/support", contact["url"])- assert.Equal(t, "[email protected]", contact["email"])-- license := info["license"].(map[string]any)- assert.Equal(t, "MIT", license["name"])- assert.Equal(t, "https://opensource.org/licenses/MIT", license["url"])-}--func TestOpenAPISpec_Generate_Servers(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- Servers: []Server{- {- URL: "https://api.example.com",- Description: "Production",- },- {- URL: "https://staging-api.example.com",- Description: "Staging",- },- },+ if len(endpoints) > 0 {+ spec.AddEndpoints(endpoints)}-- spec := NewOpenAPISpec(config)- result := spec.Generate()-- servers := result["servers"].([]map[string]any)- require.Len(t, servers, 2)-- assert.Equal(t, "https://api.example.com", servers[0]["url"])- assert.Equal(t, "Production", servers[0]["description"])+ return spec.Generate()}-func TestOpenAPISpec_Generate_ServerVariables(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- Servers: []Server{- {- URL: "https://{environment}.example.com",- Description: "Multi-env server",- Variables: map[string]ServerVariable{- "environment": {- Default: "api",- Enum: []string{"api", "staging", "dev"},- Description: "Environment",- },- },- },- },- }-- spec := NewOpenAPISpec(config)- result := spec.Generate()-- servers := result["servers"].([]map[string]any)- vars := servers[0]["variables"].(map[string]any)- envVar := vars["environment"].(map[string]any)-- assert.Equal(t, "api", envVar["default"])- assert.Equal(t, []string{"api", "staging", "dev"}, envVar["enum"])- assert.Equal(t, "Environment", envVar["description"])+// pathOp drills into result["paths"][pattern][method] and returns the operation map.+func pathOp(t *testing.T, result map[string]any, pattern, method string) map[string]any {+ t.Helper()+ paths, ok := result["paths"].(map[string]any)+ require.True(t, ok, "missing paths")+ pathItem, ok := paths[pattern].(map[string]any)+ require.True(t, ok, "missing path %q", pattern)+ op, ok := pathItem[method].(map[string]any)+ require.True(t, ok, "missing %s on %q", method, pattern)+ return op}-func TestOpenAPISpec_Generate_Paths(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{- {- Method: http.MethodGet,- Pattern: "/users",- Handler: nil,- Summary: "List users",- Description: "Returns all users",- Tags: []string{"Users"},- OperationID: "listUsers",- Response: &UserResponse{},- },- {- Method: http.MethodPost,- Pattern: "/users",- Handler: nil,- Summary: "Create user",- Tags: []string{"Users"},- OperationID: "createUser",- Request: &CreateUserRequest{},- Response: &UserResponse{},- },- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- usersPath := paths["/users"].(map[string]any)-- // GET /users- getOp := usersPath["get"].(map[string]any)- assert.Equal(t, "List users", getOp["summary"])- assert.Equal(t, "Returns all users", getOp["description"])- assert.Equal(t, []string{"Users"}, getOp["tags"])- assert.Equal(t, "listUsers", getOp["operationId"])-- // POST /users- postOp := usersPath["post"].(map[string]any)- assert.Equal(t, "Create user", postOp["summary"])- assert.NotNil(t, postOp["requestBody"])-}--func TestOpenAPISpec_Generate_PathParameters(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{- {- Method: http.MethodGet,- Pattern: "/users/{userId}/posts/{postId}",- Handler: nil,- PathParams: map[string]Schema{- "userId": String(new(string)).UUID().Description("User ID"),- "postId": Int(new(int)).Min(1).Description("Post ID"),- },- },- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- path := paths["/users/{userId}/posts/{postId}"].(map[string]any)- getOp := path["get"].(map[string]any)- params := getOp["parameters"].([]map[string]any)-- require.Len(t, params, 2)-- // First param should be userId (extracted from path order)- userIdParam := findParamByName(params, "userId")- require.NotNil(t, userIdParam)- assert.Equal(t, "path", userIdParam["in"])- assert.Equal(t, true, userIdParam["required"])-- postIdParam := findParamByName(params, "postId")- require.NotNil(t, postIdParam)- assert.Equal(t, "path", postIdParam["in"])-}--func findParamByName(params []map[string]any, name string) map[string]any {+func findParamBySource(params []map[string]any, name, in string) map[string]any {for _, p := range params {- if p["name"] == name {+ if p["name"] == name && p["in"] == in {return p}}return nil}-func TestOpenAPISpec_Generate_QueryParameters(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }+// =============================================================================+// Spec construction / version+// =============================================================================- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{- {- Method: http.MethodGet,- Pattern: "/search",- Handler: nil,- QueryParams: map[string]Schema{- "q": String(new(string)).Required().MinLength(1),- "limit": Int(new(int)).Optional().Min(1).Max(100),- "offset": Int(new(int)).Optional().Min(0),- },- },+func TestNewOpenAPISpec_DefaultsAndOverride(t *testing.T) {+ t.Run("default version", func(t *testing.T) {+ spec := NewOpenAPISpec(minimalConfig())+ assert.Equal(t, "3.0.3", spec.config.OpenAPIVersion)})- result := spec.Generate()-- paths := result["paths"].(map[string]any)- searchPath := paths["/search"].(map[string]any)- getOp := searchPath["get"].(map[string]any)- params := getOp["parameters"].([]map[string]any)-- require.Len(t, params, 3)-- qParam := findParamByName(params, "q")- require.NotNil(t, qParam)- assert.Equal(t, "query", qParam["in"])- assert.Equal(t, true, qParam["required"])-- limitParam := findParamByName(params, "limit")- require.NotNil(t, limitParam)- assert.Equal(t, "query", limitParam["in"])- _, hasRequired := limitParam["required"]- assert.False(t, hasRequired) // Optional param shouldn't have required field+ t.Run("explicit version", func(t *testing.T) {+ c := minimalConfig()+ c.OpenAPIVersion = "3.1.0"+ spec := NewOpenAPISpec(c)+ assert.Equal(t, "3.1.0", spec.config.OpenAPIVersion)+ })}-func TestOpenAPISpec_Generate_HeaderParameters(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }+// =============================================================================+// Config-level features (single table)+// =============================================================================- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{+func TestOpenAPISpec_ConfigFeatures(t *testing.T) {+ tests := []struct {+ name string+ mutate func(*OpenAPIConfig)+ verify func(t *testing.T, result map[string]any)+ }{{- Method: http.MethodGet,- Pattern: "/test",- Handler: nil,- HeaderParams: map[string]Schema{- "X-Request-ID": String(new(string)).Required().UUID(),+ name: "basic info",+ mutate: func(c *OpenAPIConfig) {+ c.Info.Description = "A test API"+ },+ verify: func(t *testing.T, result map[string]any) {+ info := result["info"].(map[string]any)+ assert.Equal(t, "Test API", info["title"])+ assert.Equal(t, "A test API", info["description"])+ assert.Equal(t, "1.0.0", info["version"])+ assert.Equal(t, "3.0.3", result["openapi"])},},- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- testPath := paths["/test"].(map[string]any)- getOp := testPath["get"].(map[string]any)- params := getOp["parameters"].([]map[string]any)-- require.Len(t, params, 1)- assert.Equal(t, "X-Request-ID", params[0]["name"])- assert.Equal(t, "header", params[0]["in"])- assert.Equal(t, true, params[0]["required"])-}--func TestOpenAPISpec_Generate_CookieParameters(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{{- Method: http.MethodGet,- Pattern: "/test",- Handler: nil,- CookieParams: map[string]Schema{- "session": String(new(string)).Required(),+ name: "full info with contact + license + ToS",+ mutate: func(c *OpenAPIConfig) {+ c.Info.TermsOfService = "https://example.com/tos"+ c.Info.Contact = &OpenAPIContact{+ Name: "Support", URL: "https://example.com/support", Email: "[email protected]",+ }+ c.Info.License = &OpenAPILicense{Name: "MIT", URL: "https://mit.example.com"}+ },+ verify: func(t *testing.T, result map[string]any) {+ info := result["info"].(map[string]any)+ assert.Equal(t, "https://example.com/tos", info["termsOfService"])+ contact := info["contact"].(map[string]any)+ assert.Equal(t, "Support", contact["name"])+ assert.Equal(t, "[email protected]", contact["email"])+ license := info["license"].(map[string]any)+ assert.Equal(t, "MIT", license["name"])},},- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- testPath := paths["/test"].(map[string]any)- getOp := testPath["get"].(map[string]any)- params := getOp["parameters"].([]map[string]any)-- require.Len(t, params, 1)- assert.Equal(t, "session", params[0]["name"])- assert.Equal(t, "cookie", params[0]["in"])-}--func TestOpenAPISpec_Generate_RequestBody(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{{- Method: http.MethodPost,- Pattern: "/users",- Handler: nil,- Request: &CreateUserRequest{},- },- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- usersPath := paths["/users"].(map[string]any)- postOp := usersPath["post"].(map[string]any)- reqBody := postOp["requestBody"].(map[string]any)-- assert.Equal(t, true, reqBody["required"])-- content := reqBody["content"].(map[string]any)- jsonContent := content["application/json"].(map[string]any)- schema := jsonContent["schema"].(map[string]any)-- assert.Equal(t, "object", schema["type"])- assert.Equal(t, "CreateUserRequest", schema["title"])-}--func TestOpenAPISpec_Generate_Responses(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",+ name: "servers list",+ mutate: func(c *OpenAPIConfig) {+ c.Servers = []Server{+ {URL: "https://api.example.com", Description: "Production"},+ {URL: "https://staging-api.example.com", Description: "Staging"},+ }+ },+ verify: func(t *testing.T, result map[string]any) {+ servers := result["servers"].([]map[string]any)+ require.Len(t, servers, 2)+ assert.Equal(t, "https://api.example.com", servers[0]["url"])+ assert.Equal(t, "Production", servers[0]["description"])+ },},- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{{- Method: http.MethodGet,- Pattern: "/users",- Handler: nil,- Response: &UserResponse{},- },- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- usersPath := paths["/users"].(map[string]any)- getOp := usersPath["get"].(map[string]any)- responses := getOp["responses"].(map[string]any)-- resp200 := responses["200"].(map[string]any)- content := resp200["content"].(map[string]any)- jsonContent := content["application/json"].(map[string]any)- schema := jsonContent["schema"].(map[string]any)-- assert.Equal(t, "object", schema["type"])- assert.Equal(t, "UserResponse", schema["title"])-}--func TestOpenAPISpec_Generate_MultipleResponses(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",+ name: "server variables",+ mutate: func(c *OpenAPIConfig) {+ c.Servers = []Server{{+ URL: "https://{environment}.example.com",+ Description: "Multi-env",+ Variables: map[string]ServerVariable{+ "environment": {+ Default: "api", Enum: []string{"api", "staging", "dev"}, Description: "Environment",+ },+ },+ }}+ },+ verify: func(t *testing.T, result map[string]any) {+ vars := result["servers"].([]map[string]any)[0]["variables"].(map[string]any)+ envVar := vars["environment"].(map[string]any)+ assert.Equal(t, "api", envVar["default"])+ assert.Equal(t, []string{"api", "staging", "dev"}, envVar["enum"])+ assert.Equal(t, "Environment", envVar["description"])+ },},- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{{- Method: http.MethodPost,- Pattern: "/users",- Handler: nil,- Request: &CreateUserRequest{},- Responses: map[int]SchemaProvider{- 201: &UserResponse{},- 400: &ErrorResponse{},+ name: "security schemes",+ mutate: func(c *OpenAPIConfig) {+ c.SecuritySchemes = map[string]*SecurityScheme{+ "jwt": HTTPBearerJWT().WithDescription("JWT auth"),+ "api_key": APIKeyHeader("X-API-Key").WithDescription("API key"),+ }+ },+ verify: func(t *testing.T, result map[string]any) {+ secSchemes := result["components"].(map[string]any)["securitySchemes"].(map[string]any)+ jwt := secSchemes["jwt"].(map[string]any)+ assert.Equal(t, "http", jwt["type"])+ assert.Equal(t, "JWT", jwt["bearerFormat"])+ ak := secSchemes["api_key"].(map[string]any)+ assert.Equal(t, "apiKey", ak["type"])+ assert.Equal(t, "X-API-Key", ak["name"])},},- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- usersPath := paths["/users"].(map[string]any)- postOp := usersPath["post"].(map[string]any)- responses := postOp["responses"].(map[string]any)-- assert.Contains(t, responses, "201")- assert.Contains(t, responses, "400")-}--func TestOpenAPISpec_Generate_SecuritySchemes(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- SecuritySchemes: map[string]*SecurityScheme{- "jwt": HTTPBearerJWT().WithDescription("JWT authentication"),- "api_key": APIKeyHeader("X-API-Key").WithDescription("API key authentication"),- },- }-- spec := NewOpenAPISpec(config)- result := spec.Generate()-- components := result["components"].(map[string]any)- secSchemes := components["securitySchemes"].(map[string]any)-- jwtScheme := secSchemes["jwt"].(map[string]any)- assert.Equal(t, "http", jwtScheme["type"])- assert.Equal(t, "bearer", jwtScheme["scheme"])- assert.Equal(t, "JWT", jwtScheme["bearerFormat"])-- apiKeyScheme := secSchemes["api_key"].(map[string]any)- assert.Equal(t, "apiKey", apiKeyScheme["type"])- assert.Equal(t, "header", apiKeyScheme["in"])- assert.Equal(t, "X-API-Key", apiKeyScheme["name"])-}--func TestOpenAPISpec_Generate_EndpointSecurity(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- SecuritySchemes: map[string]*SecurityScheme{- "jwt": HTTPBearerJWT().WithDescription("JWT"),- },- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{{- Method: http.MethodGet,- Pattern: "/protected",- Handler: nil,- Security: []Security{NewSecurity("jwt")},- },- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- protectedPath := paths["/protected"].(map[string]any)- getOp := protectedPath["get"].(map[string]any)- security := getOp["security"].([]map[string][]string)-- require.Len(t, security, 1)- assert.Contains(t, security[0], "jwt")-}--func TestOpenAPISpec_Generate_GlobalSecurity(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- Security: []Security{- NewSecurity("jwt"),- },- }-- spec := NewOpenAPISpec(config)- result := spec.Generate()-- security := result["security"].([]map[string][]string)- require.Len(t, security, 1)- assert.Contains(t, security[0], "jwt")-}--func TestOpenAPISpec_Generate_Tags(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",+ name: "global security",+ mutate: func(c *OpenAPIConfig) {+ c.Security = []Security{NewSecurity("jwt")}+ },+ verify: func(t *testing.T, result map[string]any) {+ sec := result["security"].([]map[string][]string)+ require.Len(t, sec, 1)+ assert.Contains(t, sec[0], "jwt")+ },},- Tags: []OpenAPITag{- {- Name: "Users",- Description: "User management endpoints",+ {+ name: "tags with external docs",+ mutate: func(c *OpenAPIConfig) {+ c.Tags = []OpenAPITag{+ {Name: "Users", Description: "User mgmt"},+ {Name: "Admin", Description: "Admin", ExternalDocs: &OpenAPIExternalDocs{+ Description: "Admin guide", URL: "https://example.com/admin",+ }},+ }},- {- Name: "Admin",- Description: "Admin endpoints",- ExternalDocs: &OpenAPIExternalDocs{- Description: "Admin guide",- URL: "https://example.com/admin",- },+ verify: func(t *testing.T, result map[string]any) {+ tags := result["tags"].([]map[string]any)+ require.Len(t, tags, 2)+ assert.Equal(t, "Users", tags[0]["name"])+ adminDocs := tags[1]["externalDocs"].(map[string]any)+ assert.Equal(t, "https://example.com/admin", adminDocs["url"])},},- }-- spec := NewOpenAPISpec(config)- result := spec.Generate()-- tags := result["tags"].([]map[string]any)- require.Len(t, tags, 2)-- assert.Equal(t, "Users", tags[0]["name"])- assert.Equal(t, "User management endpoints", tags[0]["description"])-- assert.Equal(t, "Admin", tags[1]["name"])- extDocs := tags[1]["externalDocs"].(map[string]any)- assert.Equal(t, "https://example.com/admin", extDocs["url"])-}--func TestOpenAPISpec_Generate_ExternalDocs(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",+ {+ name: "external docs",+ mutate: func(c *OpenAPIConfig) {+ c.ExternalDocs = &OpenAPIExternalDocs{+ Description: "Full docs", URL: "https://docs.example.com",+ }+ },+ verify: func(t *testing.T, result map[string]any) {+ ed := result["externalDocs"].(map[string]any)+ assert.Equal(t, "Full docs", ed["description"])+ assert.Equal(t, "https://docs.example.com", ed["url"])+ },},- ExternalDocs: &OpenAPIExternalDocs{- Description: "Full documentation",- URL: "https://docs.example.com",+ {+ name: "x-extensions at root",+ mutate: func(c *OpenAPIConfig) {+ c.Extensions = map[string]any{+ "x-custom": "value",+ "x-generator": "api-framework",+ }+ },+ verify: func(t *testing.T, result map[string]any) {+ assert.Equal(t, "value", result["x-custom"])+ assert.Equal(t, "api-framework", result["x-generator"])+ },},}- spec := NewOpenAPISpec(config)- result := spec.Generate()-- extDocs := result["externalDocs"].(map[string]any)- assert.Equal(t, "Full documentation", extDocs["description"])- assert.Equal(t, "https://docs.example.com", extDocs["url"])-}--func TestOpenAPISpec_Generate_Extensions(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- Extensions: map[string]any{- "x-custom": "value",- "x-generator": "api-framework",- },+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ cfg := minimalConfig()+ tt.mutate(cfg)+ tt.verify(t, generate(t, cfg))+ })}-- spec := NewOpenAPISpec(config)- result := spec.Generate()-- assert.Equal(t, "value", result["x-custom"])- assert.Equal(t, "api-framework", result["x-generator"])}-func TestOpenAPISpec_Generate_DeprecatedEndpoint(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }+// =============================================================================+// Per-endpoint OpenAPI features (single table)+// Covers fields not exercised by TestOpenAPI_FromServer.+// =============================================================================- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{+func TestOpenAPISpec_EndpointFeatures(t *testing.T) {+ tests := []struct {+ name string+ endpoint Endpoint+ verify func(t *testing.T, op map[string]any)+ }{{- Method: http.MethodGet,- Pattern: "/old",- Handler: nil,- Deprecated: true,- },- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- oldPath := paths["/old"].(map[string]any)- getOp := oldPath["get"].(map[string]any)-- assert.Equal(t, true, getOp["deprecated"])-}--func TestOpenAPISpec_Generate_EndpointExternalDocs(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",+ name: "deprecated flag",+ endpoint: Endpoint{+ Method: http.MethodGet, Pattern: "/old", Deprecated: true,+ },+ verify: func(t *testing.T, op map[string]any) {+ assert.Equal(t, true, op["deprecated"])+ },},- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{{- Method: http.MethodGet,- Pattern: "/complex",- Handler: nil,- ExternalDocsURL: "https://docs.example.com/complex",- ExternalDocsDesc: "Detailed documentation",- },- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- path := paths["/complex"].(map[string]any)- getOp := path["get"].(map[string]any)- extDocs := getOp["externalDocs"].(map[string]any)-- assert.Equal(t, "https://docs.example.com/complex", extDocs["url"])- assert.Equal(t, "Detailed documentation", extDocs["description"])-}--func TestOpenAPISpec_Generate_EndpointServers(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",+ name: "external docs",+ endpoint: Endpoint{+ Method: http.MethodGet, Pattern: "/x",+ ExternalDocsURL: "https://docs.example.com/x", ExternalDocsDesc: "Detailed docs",+ },+ verify: func(t *testing.T, op map[string]any) {+ ed := op["externalDocs"].(map[string]any)+ assert.Equal(t, "https://docs.example.com/x", ed["url"])+ assert.Equal(t, "Detailed docs", ed["description"])+ },},- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{{- Method: http.MethodGet,- Pattern: "/special",- Handler: nil,- Servers: []Server{- {- URL: "https://special.example.com",- Description: "Special server",- },+ name: "server overrides",+ endpoint: Endpoint{+ Method: http.MethodGet, Pattern: "/special",+ Servers: []Server{{URL: "https://special.example.com", Description: "Special"}},+ },+ verify: func(t *testing.T, op map[string]any) {+ srv := op["servers"].([]map[string]any)+ require.Len(t, srv, 1)+ assert.Equal(t, "https://special.example.com", srv[0]["url"])},},- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- path := paths["/special"].(map[string]any)- getOp := path["get"].(map[string]any)- servers := getOp["servers"].([]map[string]any)-- require.Len(t, servers, 1)- assert.Equal(t, "https://special.example.com", servers[0]["url"])-}--func TestOpenAPISpec_Generate_EndpointCallbacks(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{{- Method: http.MethodPost,- Pattern: "/webhooks",- Handler: nil,- Callbacks: map[string]any{- "onEvent": map[string]any{- "{$request.body#/callbackUrl}": map[string]any{- "post": map[string]any{- "summary": "Event callback",+ name: "callbacks",+ endpoint: Endpoint{+ Method: http.MethodPost, Pattern: "/webhooks",+ Callbacks: map[string]any{+ "onEvent": map[string]any{+ "{$request.body#/callbackUrl}": map[string]any{+ "post": map[string]any{"summary": "Event callback"},},},},},+ verify: func(t *testing.T, op map[string]any) {+ assert.NotNil(t, op["callbacks"])+ },},- })-- result := spec.Generate()-- paths := result["paths"].(map[string]any)- path := paths["/webhooks"].(map[string]any)- postOp := path["post"].(map[string]any)-- assert.NotNil(t, postOp["callbacks"])-}--func TestOpenAPISpec_Generate_EndpointExtensions(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",+ {+ name: "x-extensions",+ endpoint: Endpoint{+ Method: http.MethodGet, Pattern: "/custom",+ Extensions: map[string]any{"x-custom-field": "custom-value"},+ },+ verify: func(t *testing.T, op map[string]any) {+ assert.Equal(t, "custom-value", op["x-custom-field"])+ },},- }-- spec := NewOpenAPISpec(config)- spec.AddEndpoints([]Endpoint{{- Method: http.MethodGet,- Pattern: "/custom",- Handler: nil,- Extensions: map[string]any{- "x-custom-field": "custom-value",+ name: "per-endpoint security",+ endpoint: Endpoint{+ Method: http.MethodGet, Pattern: "/protected",+ Security: []Security{NewSecurity("jwt")},+ },+ verify: func(t *testing.T, op map[string]any) {+ sec := op["security"].([]map[string][]string)+ require.Len(t, sec, 1)+ assert.Contains(t, sec[0], "jwt")},},- })+ }- result := spec.Generate()+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ result := generate(t, minimalConfig(), tt.endpoint)+ method := strings.ToLower(tt.endpoint.Method)+ tt.verify(t, pathOp(t, result, tt.endpoint.Pattern, method))+ })+ }+}- paths := result["paths"].(map[string]any)- path := paths["/custom"].(map[string]any)- getOp := path["get"].(map[string]any)+// MultipleResponses isn't exercised by FromServer (server uses Response, not Responses map).+func TestOpenAPISpec_MultipleResponses(t *testing.T) {+ result := generate(t, minimalConfig(), Endpoint{+ Method: http.MethodPost,+ Pattern: "/users",+ Request: &CreateUserRequest{},+ Responses: map[int]SchemaProvider{+ 201: &UserResponse{},+ 400: &ErrorResponse{},+ },+ })- assert.Equal(t, "custom-value", getOp["x-custom-field"])+ responses := pathOp(t, result, "/users", "post")["responses"].(map[string]any)+ assert.Contains(t, responses, "201")+ assert.Contains(t, responses, "400")}-func TestOpenAPISpec_AddSchema(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }+// =============================================================================+// AddSchema + JSON serialization+// =============================================================================- spec := NewOpenAPISpec(config)+func TestOpenAPISpec_AddSchema(t *testing.T) {+ spec := NewOpenAPISpec(minimalConfig())spec.AddSchema("User", &UserResponse{})spec.AddSchema("Error", &ErrorResponse{})- result := spec.Generate()-- components := result["components"].(map[string]any)- schemas := components["schemas"].(map[string]any)-+ schemas := spec.Generate()["components"].(map[string]any)["schemas"].(map[string]any)assert.Contains(t, schemas, "User")assert.Contains(t, schemas, "Error")-- userSchema := schemas["User"].(map[string]any)- assert.Equal(t, "object", userSchema["type"])-}--func TestOpenAPISpec_JSON(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }-- spec := NewOpenAPISpec(config)- jsonBytes, err := spec.JSON()-- require.NoError(t, err)- assert.NotEmpty(t, jsonBytes)-- // Verify it's valid JSON- var parsed map[string]any- err = json.Unmarshal(jsonBytes, &parsed)- require.NoError(t, err)-- assert.Equal(t, "Test API", parsed["info"].(map[string]any)["title"])+ assert.Equal(t, "object", schemas["User"].(map[string]any)["type"])}-func TestOpenAPISpec_JSONIndent(t *testing.T) {- config := &OpenAPIConfig{- Info: OpenAPIInfo{- Title: "Test API",- Version: "1.0.0",- },- }+func TestOpenAPISpec_JSONOutput(t *testing.T) {+ spec := NewOpenAPISpec(minimalConfig())- spec := NewOpenAPISpec(config)- jsonBytes, err := spec.JSONIndent("", " ")+ t.Run("JSON()", func(t *testing.T) {+ b, err := spec.JSON()+ require.NoError(t, err)+ var parsed map[string]any+ require.NoError(t, json.Unmarshal(b, &parsed))+ assert.Equal(t, "Test API", parsed["info"].(map[string]any)["title"])+ })- require.NoError(t, err)- assert.Contains(t, string(jsonBytes), "\n")- assert.Contains(t, string(jsonBytes), " ")+ t.Run("JSONIndent() pretty-prints", func(t *testing.T) {+ b, err := spec.JSONIndent("", " ")+ require.NoError(t, err)+ assert.Contains(t, string(b), "\n")+ assert.Contains(t, string(b), " ")+ })}-// --- Endpoint Helper Tests -----func TestEndpoint_ExtractPathParams(t *testing.T) {- ep := Endpoint{- Pattern: "/users/{userId}/posts/{postId}",- }-- params := ep.ExtractPathParams()+// =============================================================================+// Endpoint helpers+// =============================================================================- assert.Equal(t, []string{"userId", "postId"}, params)-}--func TestEndpoint_ExtractPathParams_NoParams(t *testing.T) {- ep := Endpoint{- Pattern: "/users",- }-- params := ep.ExtractPathParams()+func TestEndpoint_Helpers(t *testing.T) {+ t.Run("ExtractPathParams", func(t *testing.T) {+ assert.Equal(t,+ []string{"userId", "postId"},+ (&Endpoint{Pattern: "/users/{userId}/posts/{postId}"}).ExtractPathParams(),+ )+ assert.Empty(t, (&Endpoint{Pattern: "/users"}).ExtractPathParams())+ })- assert.Empty(t, params)-}+ t.Run("OpenAPIPath returns Pattern", func(t *testing.T) {+ assert.Equal(t, "/users/{id}", (&Endpoint{Pattern: "/users/{id}"}).OpenAPIPath())+ })-func TestEndpoint_OpenAPIPath(t *testing.T) {- ep := Endpoint{- Pattern: "/users/{id}",- }+ t.Run("RequiredSchemes dedups and lists schemes", func(t *testing.T) {+ ep := Endpoint{Security: []Security{NewSecurity("jwt"), NewSecurity("api_key")}}+ schemes := ep.RequiredSchemes()+ assert.Len(t, schemes, 2)+ assert.Contains(t, schemes, "jwt")+ assert.Contains(t, schemes, "api_key")- path := ep.OpenAPIPath()+ empty := (&Endpoint{}).RequiredSchemes()+ assert.Empty(t, empty)- assert.Equal(t, "/users/{id}", path)+ dup := Endpoint{Security: []Security{NewSecurity("jwt"), NewSecurity("jwt")}}+ assert.Equal(t, []string{"jwt"}, dup.RequiredSchemes())+ })}-func TestEndpoint_RequiredSchemes(t *testing.T) {- ep := Endpoint{- Security: []Security{- NewSecurity("jwt"),- NewSecurity("api_key"),- },+func TestEndpoint_ExtractPathParams_StripChiRegex(t *testing.T) {+ tests := []struct {+ pattern string+ expected []string+ }{+ {"/users/{id}", []string{"id"}},+ {"/users/{id:[0-9]+}", []string{"id"}},+ {"/orgs/{orgId:[a-f0-9-]+}/projects/{projectId:[0-9]+}", []string{"orgId", "projectId"}},+ {"/v{version:[0-9]+}/api", []string{"version"}},+ {"/files/{path:.*}", []string{"path"}},}- schemes := ep.RequiredSchemes()-- assert.Contains(t, schemes, "jwt")- assert.Contains(t, schemes, "api_key")- assert.Len(t, schemes, 2)-}--func TestEndpoint_RequiredSchemes_Empty(t *testing.T) {- ep := Endpoint{}-- schemes := ep.RequiredSchemes()-- assert.Empty(t, schemes)-}--func TestEndpoint_RequiredSchemes_Dedup(t *testing.T) {- ep := Endpoint{- Security: []Security{- NewSecurity("jwt"),- NewSecurity("jwt"), // Duplicate- },+ for _, tt := range tests {+ t.Run(tt.pattern, func(t *testing.T) {+ assert.Equal(t, tt.expected, (&Endpoint{Pattern: tt.pattern}).ExtractPathParams())+ })}-- schemes := ep.RequiredSchemes()-- assert.Len(t, schemes, 1)- assert.Contains(t, schemes, "jwt")}-// --- Response Description Tests -----type emptyResponse struct{}--func (r *emptyResponse) Schema() *ObjectSchema { return Object(nil) }+// =============================================================================+// Response descriptions+// =============================================================================func TestOpenAPI_ResponseDescriptions(t *testing.T) {- spec := NewOpenAPISpec(&OpenAPIConfig{- Info: OpenAPIInfo{Title: "Test", Version: "1.0"},- })-- spec.AddEndpoints([]Endpoint{{+ result := generate(t, minimalConfig(), Endpoint{Method: http.MethodGet,Pattern: "/test",Response: &emptyResponse{},@@ -971,27 +499,17 @@ func TestOpenAPI_ResponseDescriptions(t *testing.T) {200: "Success - item returned",400: "Invalid request parameters",},- }})+ })- generated := spec.Generate()- paths := generated["paths"].(map[string]any)- testPath := paths["/test"].(map[string]any)- getOp := testPath["get"].(map[string]any)- responses := getOp["responses"].(map[string]any)+ responses := pathOp(t, result, "/test", "get")["responses"].(map[string]any)// Custom descriptions- resp200 := responses["200"].(map[string]any)- assert.Equal(t, "Success - item returned", resp200["description"])-- resp400 := responses["400"].(map[string]any)- assert.Equal(t, "Invalid request parameters", resp400["description"])-- // Default descriptions- resp404 := responses["404"].(map[string]any)- assert.Equal(t, "Not found", resp404["description"])+ assert.Equal(t, "Success - item returned", responses["200"].(map[string]any)["description"])+ assert.Equal(t, "Invalid request parameters", responses["400"].(map[string]any)["description"])- resp500 := responses["500"].(map[string]any)- assert.Equal(t, "Internal server error", resp500["description"])+ // Default descriptions (from defaultResponseDescription)+ assert.Equal(t, "Not found", responses["404"].(map[string]any)["description"])+ assert.Equal(t, "Internal server error", responses["500"].(map[string]any)["description"])}func TestOpenAPI_DefaultResponseDescriptions(t *testing.T) {@@ -1016,29 +534,241 @@ func TestOpenAPI_DefaultResponseDescriptions(t *testing.T) {for _, tt := range tests {t.Run(statusCodeToString(tt.code), func(t *testing.T) {- result := defaultResponseDescription(tt.code)- assert.Equal(t, tt.expected, result)+ assert.Equal(t, tt.expected, defaultResponseDescription(tt.code))})}}-func TestEndpoint_ExtractPathParams_StripChiRegex(t *testing.T) {- tests := []struct {- pattern string- expected []string- }{- {"/users/{id}", []string{"id"}},- {"/users/{id:[0-9]+}", []string{"id"}},- {"/orgs/{orgId:[a-f0-9-]+}/projects/{projectId:[0-9]+}", []string{"orgId", "projectId"}},- {"/v{version:[0-9]+}/api", []string{"version"}},- {"/files/{path:.*}", []string{"path"}},- }+// =============================================================================+// Schema $ref tests+// =============================================================================- for _, tt := range tests {- t.Run(tt.pattern, func(t *testing.T) {- ep := Endpoint{Pattern: tt.pattern}- params := ep.ExtractPathParams()- assert.Equal(t, tt.expected, params)- })- }+func TestObjectSchema_Ref(t *testing.T) {+ DefaultRegistry.Clear()++ var name, email string+ userSchema := Object(map[string]Schema{+ "name": String(&name).Required(),+ "email": String(&email).Email(),+ }).Title("User").Ref("User")++ openAPI := userSchema.OpenAPI()+ assert.Equal(t, "#/components/schemas/User", openAPI["$ref"])+ assert.NotContains(t, openAPI, "type")++ def := userSchema.Definition()+ assert.Equal(t, "object", def["type"])+ assert.Equal(t, "User", def["title"])+ assert.Contains(t, def, "properties")++ assert.Equal(t, "User", userSchema.RefName())+ assert.NotNil(t, DefaultRegistry.Get("User"))+}++func TestObjectSchema_Ref_InOpenAPISpec(t *testing.T) {+ DefaultRegistry.Clear()++ var errorCode, errorMsg string+ errorSchema := Object(map[string]Schema{+ "code": String(&errorCode).Required(),+ "message": String(&errorMsg).Required(),+ }).Title("Error").Ref("Error")++ result := generate(t, minimalConfig(), Endpoint{+ Method: http.MethodGet,+ Pattern: "/items",+ Response: &emptyResponse{},+ Responses: map[int]SchemaProvider{+ 400: &schemaProviderWrapper{schema: errorSchema},+ },+ })++ // Components should include the Error schema from the registry+ schemas := result["components"].(map[string]any)["schemas"].(map[string]any)+ assert.Contains(t, schemas, "Error")+ errDef := schemas["Error"].(map[string]any)+ assert.Equal(t, "object", errDef["type"])+ assert.Equal(t, "Error", errDef["title"])++ // The 400 response should be a $ref+ respSchema := pathOp(t, result, "/items", "get")["responses"].(map[string]any)["400"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)+ assert.Equal(t, "#/components/schemas/Error", respSchema["$ref"])+}++func TestArraySchema_Ref(t *testing.T) {+ DefaultRegistry.Clear()++ var item string+ tagsSchema := Array(String(&item)).MinItems(1).Ref("Tags")++ openAPI := tagsSchema.OpenAPI()+ assert.Equal(t, "#/components/schemas/Tags", openAPI["$ref"])++ def := tagsSchema.Definition()+ assert.Equal(t, "array", def["type"])+ assert.Equal(t, 1, def["minItems"])++ assert.Equal(t, "Tags", tagsSchema.RefName())+}++// =============================================================================+// Server-driven OpenAPI integration test+//+// Uses the same setupTestServer fixture as http_test.go to verify that the+// OpenAPI spec generated from a real Router accurately reflects every feature+// the HTTP suite exercises. This catches drift between the spec and the+// validation/parsing layer in a way that pure unit tests can't.+// =============================================================================++func TestOpenAPI_FromServer(t *testing.T) {+ _, router := setupTestServer(t)++ spec := NewOpenAPISpec(&OpenAPIConfig{+ Info: OpenAPIInfo{Title: "Test API", Version: "1.0.0"},+ SecuritySchemes: map[string]*SecurityScheme{+ "bearerAuth": HTTPBearerJWT(),+ },+ })+ spec.AddEndpoints(router.Endpoints())+ result := spec.Generate()+ paths := result["paths"].(map[string]any)++ t.Run("every registered path appears", func(t *testing.T) {+ expected := []string{+ "/items", "/items/{id}",+ "/error", "/error/{type}",+ "/codes", "/links", "/measurements", "/tagged", "/orders", "/nullable", "/adopt",+ "/session", "/events/{id}",+ "/process", "/context-test", "/health",+ }+ for _, p := range expected {+ assert.Contains(t, paths, p, "missing path %q in spec", p)+ }+ })++ t.Run("path param has required=true and uuid format", func(t *testing.T) {+ params := pathOp(t, result, "/items/{id}", "get")["parameters"].([]map[string]any)++ idParam := findParamBySource(params, "id", "path")+ require.NotNil(t, idParam)+ assert.Equal(t, true, idParam["required"])++ schema := idParam["schema"].(map[string]any)+ assert.Equal(t, "string", schema["type"])+ assert.Equal(t, "uuid", schema["format"])+ })++ t.Run("query params have correct types, defaults, and enums", func(t *testing.T) {+ params := pathOp(t, result, "/items/{id}", "get")["parameters"].([]map[string]any)++ pageParam := findParamBySource(params, "page", "query")+ require.NotNil(t, pageParam)+ pageSchema := pageParam["schema"].(map[string]any)+ assert.Equal(t, "integer", pageSchema["type"])+ assert.Equal(t, int64(1), pageSchema["default"])+ assert.Equal(t, int64(1), pageSchema["minimum"])++ statusParam := findParamBySource(params, "status", "query")+ require.NotNil(t, statusParam)+ statusSchema := statusParam["schema"].(map[string]any)+ assert.Equal(t, []string{"active", "inactive", "pending"}, statusSchema["enum"])+ })++ t.Run("header param uses header source", func(t *testing.T) {+ params := pathOp(t, result, "/items/{id}", "put")["parameters"].([]map[string]any)+ hdr := findParamBySource(params, "X-Request-ID", "header")+ require.NotNil(t, hdr)+ assert.Equal(t, "uuid", hdr["schema"].(map[string]any)["format"])+ })++ t.Run("cookie params use cookie source and reflect required flag", func(t *testing.T) {+ params := pathOp(t, result, "/session", "get")["parameters"].([]map[string]any)++ session := findParamBySource(params, "session_id", "cookie")+ require.NotNil(t, session)+ assert.Equal(t, true, session["required"])++ user := findParamBySource(params, "user_id", "cookie")+ require.NotNil(t, user)+ assert.Equal(t, false, user["required"])+ })++ t.Run("request body wires schema with required fields", func(t *testing.T) {+ reqBody := pathOp(t, result, "/items", "post")["requestBody"].(map[string]any)+ schema := reqBody["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)+ assert.Equal(t, "object", schema["type"])++ required := schema["required"].([]string)+ assert.Contains(t, required, "name")+ assert.Contains(t, required, "email")+ assert.Equal(t, "email", schema["properties"].(map[string]any)["email"].(map[string]any)["format"])+ })++ t.Run("response wires schema for declared status", func(t *testing.T) {+ responses := pathOp(t, result, "/items", "post")["responses"].(map[string]any)+ require.Contains(t, responses, "201") // CreatedSimpleResponse has Status() = 201+ schema := responses["201"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)+ assert.Equal(t, "object", schema["type"])+ })++ t.Run("nested object surfaces with enum on nested field", func(t *testing.T) {+ schema := pathOp(t, result, "/orders", "post")["requestBody"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)++ shipping := schema["properties"].(map[string]any)["shippingAddress"].(map[string]any)+ assert.Equal(t, "object", shipping["type"])+ country := shipping["properties"].(map[string]any)["country"].(map[string]any)+ assert.Equal(t, []string{"US", "CA", "UK", "DE"}, country["enum"])+ })++ t.Run("array schema preserves min/max items", func(t *testing.T) {+ schema := pathOp(t, result, "/tagged", "post")["requestBody"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)+ tagsProp := schema["properties"].(map[string]any)["tags"].(map[string]any)+ assert.Equal(t, "array", tagsProp["type"])+ assert.Equal(t, 1, tagsProp["minItems"])+ assert.Equal(t, 5, tagsProp["maxItems"])+ })++ t.Run("pattern, url format, and nullable surface in spec", func(t *testing.T) {+ codeSchema := pathOp(t, result, "/codes", "post")["requestBody"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)+ assert.Equal(t, `^[A-Z]{3}-\d{4}$`, codeSchema["properties"].(map[string]any)["code"].(map[string]any)["pattern"])++ linkSchema := pathOp(t, result, "/links", "post")["requestBody"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)+ assert.Equal(t, "url", linkSchema["properties"].(map[string]any)["website"].(map[string]any)["format"])++ nullSchema := pathOp(t, result, "/nullable", "post")["requestBody"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)+ assert.Equal(t, true, nullSchema["properties"].(map[string]any)["nickname"].(map[string]any)["nullable"])+ })++ t.Run("union surfaces as oneOf with discriminator", func(t *testing.T) {+ schema := pathOp(t, result, "/adopt", "post")["requestBody"].(map[string]any)["content"].(map[string]any)["application/json"].(map[string]any)["schema"].(map[string]any)+ petProp := schema["properties"].(map[string]any)["pet"].(map[string]any)++ oneOf, ok := petProp["oneOf"].([]map[string]any)+ require.True(t, ok, "pet should have oneOf")+ assert.Len(t, oneOf, 2)++ disc := petProp["discriminator"].(map[string]any)+ assert.Equal(t, "type", disc["propertyName"])+ })++ t.Run("operation metadata propagated", func(t *testing.T) {+ op := pathOp(t, result, "/items", "post")+ assert.Equal(t, "Create item", op["summary"])+ assert.Equal(t, "createItem", op["operationId"])+ assert.Equal(t, []string{"Items"}, op["tags"])+ })++ t.Run("delete endpoint has no request body block", func(t *testing.T) {+ _, hasBody := pathOp(t, result, "/items/{id}", "delete")["requestBody"]+ assert.False(t, hasBody, "DELETE with no body fields should not emit requestBody")+ })++ t.Run("spec serializes to valid JSON", func(t *testing.T) {+ b, err := spec.JSONIndent("", " ")+ require.NoError(t, err)++ var parsed map[string]any+ require.NoError(t, json.Unmarshal(b, &parsed))+ assert.Equal(t, "Test API", parsed["info"].(map[string]any)["title"])+ })}diff --git a/backend-go/pkg/api/registry.go b/backend-go/pkg/api/registry.gonew file mode 100644index 0000000000..804cb44c4f--- /dev/null+++ b/backend-go/pkg/api/registry.go@@ -0,0 +1,63 @@+package api++import (+ "maps"+ "sync"+)++// SchemaRegistry collects named schemas for OpenAPI components/schemas output.+// Use the global DefaultRegistry or create your own for testing.+type SchemaRegistry struct {+ mu sync.RWMutex+ schemas map[string]Schema+}++// NewSchemaRegistry creates a new schema registry.+func NewSchemaRegistry() *SchemaRegistry {+ return &SchemaRegistry{+ schemas: make(map[string]Schema),+ }+}++// Register adds a schema to the registry under the given name.+// If a schema with the same name already exists, it is overwritten.+func (r *SchemaRegistry) Register(name string, schema Schema) {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.schemas[name] = schema+}++// Get retrieves a schema by name. Returns nil if not found.+func (r *SchemaRegistry) Get(name string) Schema {+ r.mu.RLock()+ defer r.mu.RUnlock()+ return r.schemas[name]+}++// All returns all registered schemas as a map.+func (r *SchemaRegistry) All() map[string]Schema {+ r.mu.RLock()+ defer r.mu.RUnlock()+ result := make(map[string]Schema, len(r.schemas))+ maps.Copy(result, r.schemas)+ return result+}++// Clear removes all registered schemas (useful for testing).+func (r *SchemaRegistry) Clear() {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.schemas = make(map[string]Schema)+}++// DefaultRegistry is the global schema registry used by Ref() methods.+var DefaultRegistry = NewSchemaRegistry()++// Refable is implemented by schemas that support $ref naming.+type Refable interface {+ Schema+ // RefName returns the registered name, or empty if not a ref.+ RefName() string+ // Definition returns the full schema definition (ignoring ref).+ Definition() map[string]any+}diff --git a/backend-go/pkg/api/router.go b/backend-go/pkg/api/router.goindex b776daada7..b6549364b1 100644--- a/backend-go/pkg/api/router.go+++ b/backend-go/pkg/api/router.go@@ -1,329 +1,261 @@package apiimport (+ "encoding/json""net/http""github.com/go-chi/chi/v5")-// Router wraps chi.Router with endpoint collection for OpenAPI generation-type Router struct {- chi.Router- endpoints []Endpoint- defaultSecurity []Security- defaultTags []string- basePath string-}+// RouterConfig configures the router+type RouterConfig struct {+ // App for typed handler wrapping and error handling+ App *App-// NewRouter creates a new Router-func NewRouter() *Router {- return &Router{- Router: chi.NewRouter(),- }-}--// WithSecurity sets the default security requirements for all endpoints in this router-// Multiple Security entries = OR relationship (any one suffices)-func (r *Router) WithSecurity(security ...Security) *Router {- r.defaultSecurity = security- return r-}--// WithTags sets the default tags for all endpoints in this router-func (r *Router) WithTags(tags ...string) *Router {- r.defaultTags = tags- return r+ // OpenAPI spec configuration+ Spec *OpenAPIConfig}-// Route creates a subrouter with a path prefix-func (r *Router) Route(pattern string, fn func(sub *Router)) {- sub := &Router{- Router: chi.NewRouter(),- defaultSecurity: r.defaultSecurity,- defaultTags: r.defaultTags,- basePath: r.basePath + pattern,- }+// Router wraps chi.Router with typed handlers and OpenAPI generation+type Router struct {+ chi chi.Router+ app *App- fn(sub)+ // OpenAPI+ specConfig *OpenAPIConfig+ endpoints []Endpoint- r.endpoints = append(r.endpoints, sub.endpoints...)+ // Inherited defaults+ basePath string+ defaultSecurity []Security+ defaultTags []string+ defaultResponses []TypedResponse- r.Router.Mount(pattern, sub.Router)+ // Reference to root router for endpoint collection+ root *Router}-// Group creates a route group with shared configuration but no path prefix-func (r *Router) Group(fn func(sub *Router)) {- sub := &Router{- Router: r.Router,- defaultSecurity: r.defaultSecurity,- defaultTags: r.defaultTags,- basePath: r.basePath,+// NewRouter creates a new Router with typed handler support and OpenAPI generation+func NewRouter(config RouterConfig) *Router {+ if config.App == nil {+ config.App = NewApp(AppConfig{})}+ r := &Router{+ chi: chi.NewRouter(),+ app: config.App,+ specConfig: config.Spec,+ }+ r.root = r // root points to itself+ return r+}- fn(sub)+// =============================================================================+// HTTP Methods — New Builder API+// =============================================================================- r.endpoints = append(r.endpoints, sub.endpoints...)+// GET registers a GET endpoint with a typed handler builder+func (r *Router) GET(pattern string, spec EndpointSpec) {+ r.registerEndpoint(http.MethodGet, pattern, spec)}-// Mount attaches a sub-router at a given pattern-func (r *Router) Mount(pattern string, handler http.Handler) {- r.Router.Mount(pattern, handler)+// POST registers a POST endpoint with a typed handler builder+func (r *Router) POST(pattern string, spec EndpointSpec) {+ r.registerEndpoint(http.MethodPost, pattern, spec)+}- if subRouter, ok := handler.(*Router); ok {- for i := range subRouter.endpoints {- ep := subRouter.endpoints[i]- ep.Pattern = pattern + ep.Pattern- // Propagate defaults if endpoint doesn't have its own- if len(ep.Security) == 0 && len(r.defaultSecurity) > 0 {- ep.Security = make([]Security, len(r.defaultSecurity))- copy(ep.Security, r.defaultSecurity)- }- if len(ep.Tags) == 0 && len(r.defaultTags) > 0 {- ep.Tags = make([]string, len(r.defaultTags))- copy(ep.Tags, r.defaultTags)- }- r.endpoints = append(r.endpoints, ep)- }- }+// PUT registers a PUT endpoint with a typed handler builder+func (r *Router) PUT(pattern string, spec EndpointSpec) {+ r.registerEndpoint(http.MethodPut, pattern, spec)}-// Use appends middleware to the router-func (r *Router) Use(middlewares ...func(http.Handler) http.Handler) {- r.Router.Use(middlewares...)+// PATCH registers a PATCH endpoint with a typed handler builder+func (r *Router) PATCH(pattern string, spec EndpointSpec) {+ r.registerEndpoint(http.MethodPatch, pattern, spec)}-// With returns a new router with the given middlewares-func (r *Router) With(middlewares ...func(http.Handler) http.Handler) *Router {- return &Router{- Router: r.Router.With(middlewares...),- endpoints: r.endpoints,- defaultSecurity: r.defaultSecurity,- defaultTags: r.defaultTags,- basePath: r.basePath,- }+// DELETE registers a DELETE endpoint with a typed handler builder+func (r *Router) DELETE(pattern string, spec EndpointSpec) {+ r.registerEndpoint(http.MethodDelete, pattern, spec)}-// Handle registers an endpoint-func (r *Router) Handle(ep Endpoint) { //nolint:gocritic // intentional copy - we modify and store- if len(ep.Security) == 0 && len(r.defaultSecurity) > 0 {- ep.Security = make([]Security, len(r.defaultSecurity))- copy(ep.Security, r.defaultSecurity)- }- if len(ep.Tags) == 0 && len(r.defaultTags) > 0 {- ep.Tags = make([]string, len(r.defaultTags))- copy(ep.Tags, r.defaultTags)- }+// registerEndpoint builds and registers an endpoint from a spec+func (r *Router) registerEndpoint(method, pattern string, spec EndpointSpec) {+ // Collect default responses from router chain + app+ defaults := r.collectDefaultResponses()- // Store original pattern for chi registration (relative to this router)- chiPattern := ep.Pattern- if chiPattern == "" {- chiPattern = "/"- }+ // Build the endpoint+ handler, ep := spec.build(r.basePath, defaults, r.defaultTags, r.defaultSecurity)- // Store full path for OpenAPI- ep.Pattern = r.basePath + ep.Pattern-- r.endpoints = append(r.endpoints, ep)-- switch ep.Method {- case http.MethodGet:- r.Router.Get(chiPattern, ep.Handler)- case http.MethodPost:- r.Router.Post(chiPattern, ep.Handler)- case http.MethodPut:- r.Router.Put(chiPattern, ep.Handler)- case http.MethodPatch:- r.Router.Patch(chiPattern, ep.Handler)- case http.MethodDelete:- r.Router.Delete(chiPattern, ep.Handler)- case http.MethodHead:- r.Head(chiPattern, ep.Handler)- case http.MethodOptions:- r.Options(chiPattern, ep.Handler)- default:- r.Method(ep.Method, chiPattern, ep.Handler)- }-}+ // Set method and pattern+ ep.Method = method+ ep.Pattern = r.basePath + pattern-// Get registers a GET endpoint-func (r *Router) Get(pattern string, handler http.HandlerFunc, opts ...EndpointOption) {- ep := Endpoint{- Method: http.MethodGet,- Pattern: pattern,- Handler: handler,- }- for _, opt := range opts {- opt(&ep)- }- r.Handle(ep)-}+ // Collect endpoint at root+ r.root.endpoints = append(r.root.endpoints, ep)-// Post registers a POST endpoint-func (r *Router) Post(pattern string, handler http.HandlerFunc, opts ...EndpointOption) {- ep := Endpoint{- Method: http.MethodPost,- Pattern: pattern,- Handler: handler,- }- for _, opt := range opts {- opt(&ep)- }- r.Handle(ep)+ // Register with chi+ r.chi.Method(method, pattern, handler)}-// Put registers a PUT endpoint-func (r *Router) Put(pattern string, handler http.HandlerFunc, opts ...EndpointOption) {- ep := Endpoint{- Method: http.MethodPut,- Pattern: pattern,- Handler: handler,- }- for _, opt := range opts {- opt(&ep)- }- r.Handle(ep)-}+// collectDefaultResponses gathers defaults from app and router chain+func (r *Router) collectDefaultResponses() []TypedResponse {+ var defaults []TypedResponse-// Patch registers a PATCH endpoint-func (r *Router) Patch(pattern string, handler http.HandlerFunc, opts ...EndpointOption) {- ep := Endpoint{- Method: http.MethodPatch,- Pattern: pattern,- Handler: handler,- }- for _, opt := range opts {- opt(&ep)+ // App defaults first (lowest precedence)+ if r.app != nil {+ defaults = append(defaults, r.app.DefaultResponses()...)}- r.Handle(ep)-}-// Delete registers a DELETE endpoint-func (r *Router) Delete(pattern string, handler http.HandlerFunc, opts ...EndpointOption) {- ep := Endpoint{- Method: http.MethodDelete,- Pattern: pattern,- Handler: handler,- }- for _, opt := range opts {- opt(&ep)- }- r.Handle(ep)-}+ // Router defaults (higher precedence - will override app defaults by status code)+ defaults = append(defaults, r.defaultResponses...)-// Endpoints returns all registered endpoints (for OpenAPI generation)-func (r *Router) Endpoints() []Endpoint {- return r.endpoints+ return defaults}-// ServeHTTP implements http.Handler-func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {- r.Router.ServeHTTP(w, req)-}+// =============================================================================+// Chi Router Methods+// =============================================================================-// EndpointOption configures an endpoint-type EndpointOption func(*Endpoint)--// WithRequest sets the request schema-func WithRequest(req SchemaProvider) EndpointOption {- return func(e *Endpoint) {- e.Request = req+// Route creates a subrouter with a path prefix+func (r *Router) Route(pattern string, fn func(r *Router)) {+ sub := &Router{+ chi: chi.NewRouter(),+ app: r.app,+ specConfig: r.specConfig,+ basePath: r.basePath + pattern,+ defaultSecurity: r.defaultSecurity,+ defaultTags: r.defaultTags,+ defaultResponses: r.defaultResponses, // Inherit default responses+ root: r.root,}-}-// WithResponse sets the response schema-func WithResponse(resp SchemaProvider) EndpointOption {- return func(e *Endpoint) {- e.Response = resp- }-}+ fn(sub)-// WithResponses sets multiple response schemas by status code-func WithResponses(responses map[int]SchemaProvider) EndpointOption {- return func(e *Endpoint) {- e.Responses = responses- }+ r.chi.Mount(pattern, sub.chi)}-// WithSecurityRequirements sets the security requirements (OR relationship)-func WithSecurityRequirements(security ...Security) EndpointOption {- return func(e *Endpoint) {- e.Security = security+// Group creates a route group with shared middleware but no path prefix+func (r *Router) Group(fn func(r *Router)) {+ sub := &Router{+ chi: r.chi,+ app: r.app,+ specConfig: r.specConfig,+ basePath: r.basePath,+ defaultSecurity: r.defaultSecurity,+ defaultTags: r.defaultTags,+ defaultResponses: r.defaultResponses,+ root: r.root,}++ fn(sub)}-// WithNoAuth explicitly marks endpoint as requiring no authentication-func WithNoAuth() EndpointOption {- return func(e *Endpoint) {- e.Security = []Security{{}}+// Mount attaches another http.Handler at a given pattern+func (r *Router) Mount(pattern string, handler http.Handler) {+ // If mounting another Router, collect its endpoints+ if subRouter, ok := handler.(*Router); ok {+ for i := range subRouter.endpoints {+ ep := subRouter.endpoints[i]+ ep.Pattern = pattern + ep.Pattern+ r.root.endpoints = append(r.root.endpoints, ep)+ }}+ r.chi.Mount(pattern, handler)}-// WithTags sets the tags-func WithTags(tags ...string) EndpointOption {- return func(e *Endpoint) {- e.Tags = tags- }+// Use appends middleware to the router+func (r *Router) Use(middlewares ...func(http.Handler) http.Handler) {+ r.chi.Use(middlewares...)}-// WithSummary sets the summary-func WithSummary(summary string) EndpointOption {- return func(e *Endpoint) {- e.Summary = summary+// With returns a new router context with the middleware applied+func (r *Router) With(middlewares ...func(http.Handler) http.Handler) *Router {+ return &Router{+ chi: r.chi.With(middlewares...),+ app: r.app,+ specConfig: r.specConfig,+ basePath: r.basePath,+ defaultSecurity: r.defaultSecurity,+ defaultTags: r.defaultTags,+ defaultResponses: r.defaultResponses,+ root: r.root,}}-// WithDescription sets the description-func WithDescription(desc string) EndpointOption {- return func(e *Endpoint) {- e.Description = desc+// =============================================================================+// Default Configuration+// =============================================================================++// WithSecurity sets default security for all endpoints in this router/group.+// If the App has a SecurityRegistry configured, this also installs the auth middleware.+// This combines OpenAPI documentation and runtime enforcement in one call.+func (r *Router) WithSecurity(security ...Security) *Router {+ r.defaultSecurity = security++ // Auto-install middleware if registry is available+ if r.app != nil && r.app.securityRegistry != nil {+ r.chi.Use(r.app.securityRegistry.Middleware(security, nil))}++ return r}-// WithOperationID sets the operation ID-func WithOperationID(id string) EndpointOption {- return func(e *Endpoint) {- e.OperationID = id- }+// WithTags sets default tags for all endpoints in this router/group+func (r *Router) WithTags(tags ...string) *Router {+ r.defaultTags = tags+ return r}-// WithDeprecated marks the endpoint as deprecated-func WithDeprecated() EndpointOption {- return func(e *Endpoint) {- e.Deprecated = true- }+// WithDefaultResponses sets default error responses for all endpoints in this router/group.+// These are merged with app-level defaults. Router defaults override app defaults by status code.+func (r *Router) WithDefaultResponses(responses ...TypedResponse) *Router {+ r.defaultResponses = append(r.defaultResponses, responses...)+ return r}-// WithPathParams sets the path parameter schemas-func WithPathParams(params map[string]Schema) EndpointOption {- return func(e *Endpoint) {- e.PathParams = params+// =============================================================================+// OpenAPI+// =============================================================================++// Spec generates the OpenAPI spec from registered endpoints+func (r *Router) Spec() *OpenAPISpec {+ if r.specConfig == nil {+ r.specConfig = &OpenAPIConfig{+ Info: OpenAPIInfo{+ Title: "API",+ Version: "1.0.0",+ },+ }}+ spec := NewOpenAPISpec(r.specConfig)+ spec.AddEndpoints(r.root.endpoints)+ return spec}-// WithQueryParams sets the query parameter schemas-func WithQueryParams(params map[string]Schema) EndpointOption {- return func(e *Endpoint) {- e.QueryParams = params- }+// ServeSpec registers a handler that serves the OpenAPI spec as JSON+func (r *Router) ServeSpec(pattern string) {+ spec := r.Spec()+ r.chi.Get(pattern, func(w http.ResponseWriter, req *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(spec.Generate())+ })}-// WithHeaderParams sets the header parameter schemas-func WithHeaderParams(params map[string]Schema) EndpointOption {- return func(e *Endpoint) {- e.HeaderParams = params- }+// Endpoints returns all registered endpoints+func (r *Router) Endpoints() []Endpoint {+ return r.root.endpoints}-// WithCookieParams sets the cookie parameter schemas-func WithCookieParams(params map[string]Schema) EndpointOption {- return func(e *Endpoint) {- e.CookieParams = params- }+// =============================================================================+// http.Handler+// =============================================================================++// ServeHTTP implements http.Handler+func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {+ r.chi.ServeHTTP(w, req)}-// WithResponseDescriptions sets custom descriptions for response status codes-func WithResponseDescriptions(descriptions map[int]string) EndpointOption {- return func(e *Endpoint) {- e.ResponseDescriptions = descriptions- }+// Chi returns the underlying chi.Router (for advanced use cases)+func (r *Router) Chi() chi.Router {+ return r.chi}diff --git a/backend-go/pkg/api/router_test.go b/backend-go/pkg/api/router_test.goindex da05399798..65771983a4 100644--- a/backend-go/pkg/api/router_test.go+++ b/backend-go/pkg/api/router_test.go@@ -11,23 +11,80 @@ import ("github.com/stretchr/testify/require")-// --- Basic Route Registration ---+// =============================================================================+// Test types for router tests+// =============================================================================-func TestRouter_Get(t *testing.T) {- r := NewRouter()+// EmptyRequest for handlers that don't need request parsing+type EmptyRequest struct{}- called := false- r.Get("/test", func(w http.ResponseWriter, r *http.Request) {- called = true- w.WriteHeader(http.StatusOK)+func (r *EmptyRequest) Schema() *ObjectSchema {+ return Object(map[string]Schema{})+}++// TestOKResponse is a simple 200 response+type TestOKResponse struct {+ Message string `json:"message"`+}++func (r *TestOKResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "message": String(&r.Message).Optional(),+ })+}++func (*TestOKResponse) Status() int { return http.StatusOK }++// TestCreatedResponse is a 201 response+type TestCreatedResponse struct {+ ID string `json:"id"`+}++func (r *TestCreatedResponse) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "id": String(&r.ID).Optional(),})+}++func (*TestCreatedResponse) Status() int { return http.StatusCreated }++// TestNoContent is a 204 response+type TestNoContent struct{}++func (*TestNoContent) Schema() *ObjectSchema { return nil }+func (*TestNoContent) Status() int { return http.StatusNoContent }++// =============================================================================+// Test handlers+// =============================================================================++func testOKHandler(_ context.Context, _ *EmptyRequest) (TestOKResponse, error) {+ return TestOKResponse{Message: "ok"}, nil+}++func testCreatedHandler(_ context.Context, _ *EmptyRequest) (TestCreatedResponse, error) {+ return TestCreatedResponse{ID: "123"}, nil+}++func testNoContentHandler(_ context.Context, _ *EmptyRequest) (TestNoContent, error) {+ return TestNoContent{}, nil+}++// =============================================================================+// Tests+// =============================================================================++func TestRouter_GET(t *testing.T) {+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})++ r.GET("/test", Handler(app, testOKHandler))req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/test", http.NoBody)rec := httptest.NewRecorder()r.ServeHTTP(rec, req)- assert.True(t, called)assert.Equal(t, http.StatusOK, rec.Code)endpoints := r.Endpoints()@@ -36,12 +93,11 @@ func TestRouter_Get(t *testing.T) {assert.Equal(t, "/test", endpoints[0].Pattern)}-func TestRouter_Post(t *testing.T) {- r := NewRouter()+func TestRouter_POST(t *testing.T) {+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})- r.Post("/create", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusCreated)- })+ r.POST("/create", Handler(app, testCreatedHandler))req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/create", http.NoBody)rec := httptest.NewRecorder()@@ -55,57 +111,57 @@ func TestRouter_Post(t *testing.T) {assert.Equal(t, http.MethodPost, endpoints[0].Method)}-func TestRouter_Put(t *testing.T) {- r := NewRouter()+func TestRouter_PUT(t *testing.T) {+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})- r.Put("/update", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- })+ r.PUT("/update", Handler(app, testOKHandler))endpoints := r.Endpoints()require.Len(t, endpoints, 1)assert.Equal(t, http.MethodPut, endpoints[0].Method)}-func TestRouter_Patch(t *testing.T) {- r := NewRouter()+func TestRouter_PATCH(t *testing.T) {+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})- r.Patch("/partial", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- })+ r.PATCH("/partial", Handler(app, testOKHandler))endpoints := r.Endpoints()require.Len(t, endpoints, 1)assert.Equal(t, http.MethodPatch, endpoints[0].Method)}-func TestRouter_Delete(t *testing.T) {- r := NewRouter()+func TestRouter_DELETE(t *testing.T) {+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})- r.Delete("/remove", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusNoContent)- })+ r.DELETE("/remove", Handler(app, testNoContentHandler))++ req := httptest.NewRequestWithContext(context.Background(), http.MethodDelete, "/remove", http.NoBody)+ rec := httptest.NewRecorder()++ r.ServeHTTP(rec, req)++ assert.Equal(t, http.StatusNoContent, rec.Code)endpoints := r.Endpoints()require.Len(t, endpoints, 1)assert.Equal(t, http.MethodDelete, endpoints[0].Method)}-// --- Route with Options ---+func TestRouter_WithBuilderOptions(t *testing.T) {+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})-func TestRouter_WithOptions(t *testing.T) {- r := NewRouter()-- r.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- },- WithSummary("Get user by ID"),- WithDescription("Retrieves a user by their unique ID"),- WithOperationID("getUser"),- WithTags("Users"),- WithSecurityRequirements(NewSecurity("jwt")),- WithDeprecated(),- )+ r.GET("/users/{id}", Handler(app, testOKHandler).+ Summary("Get user by ID").+ Description("Retrieves a user by their unique ID").+ OperationID("getUser").+ Tags("Users").+ Security(NewSecurity("jwt")).+ Deprecated())endpoints := r.Endpoints()require.Len(t, endpoints, 1)@@ -122,31 +178,13 @@ func TestRouter_WithOptions(t *testing.T) {assert.Equal(t, "jwt", reqs[0].Scheme)}-func TestRouter_WithNoAuth(t *testing.T) {- r := NewRouter()-- r.Get("/public", func(w http.ResponseWriter, r *http.Request) {},- WithNoAuth(),- )-- endpoints := r.Endpoints()- require.Len(t, endpoints, 1)- require.Len(t, endpoints[0].Security, 1)- assert.True(t, endpoints[0].Security[0].IsEmpty())-}--// --- Route Groups ----func TestRouter_Route(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})r.Route("/api/v1", func(sub *Router) {- sub.Get("/users", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- })- sub.Post("/users", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusCreated)- })+ sub.GET("/users", Handler(app, testOKHandler))+ sub.POST("/users", Handler(app, testCreatedHandler))})endpoints := r.Endpoints()@@ -162,17 +200,14 @@ func TestRouter_Route(t *testing.T) {}func TestRouter_NestedRoutes(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})r.Route("/api", func(api *Router) {api.Route("/v1", func(v1 *Router) {v1.Route("/users", func(users *Router) {- users.Get("/", func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte("list users"))- })- users.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte("get user"))- })+ users.GET("/", Handler(app, testOKHandler))+ users.GET("/{id}", Handler(app, testOKHandler))})})})@@ -187,19 +222,18 @@ func TestRouter_NestedRoutes(t *testing.T) {rec := httptest.NewRecorder()r.ServeHTTP(rec, req)body, _ := io.ReadAll(rec.Body)- assert.Equal(t, "list users", string(body))+ assert.Contains(t, string(body), "ok")}-// --- Default Security and Tags ----func TestRouter_WithSecurity(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})r.Route("/api", func(api *Router) {api.WithSecurity(NewSecurity("jwt"))- api.Get("/protected", func(w http.ResponseWriter, r *http.Request) {})- api.Post("/protected", func(w http.ResponseWriter, r *http.Request) {})+ api.GET("/protected", Handler(app, testOKHandler))+ api.POST("/protected", Handler(app, testCreatedHandler))})endpoints := r.Endpoints()@@ -214,13 +248,14 @@ func TestRouter_WithSecurity(t *testing.T) {}func TestRouter_WithTags(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})r.Route("/api/users", func(users *Router) {users.WithTags("Users", "Admin")- users.Get("/", func(w http.ResponseWriter, r *http.Request) {})- users.Post("/", func(w http.ResponseWriter, r *http.Request) {})+ users.GET("/", Handler(app, testOKHandler))+ users.POST("/", Handler(app, testCreatedHandler))})endpoints := r.Endpoints()@@ -232,7 +267,8 @@ func TestRouter_WithTags(t *testing.T) {}func TestRouter_InheritedDefaults(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})r.Route("/api", func(api *Router) {api.WithSecurity(NewSecurity("jwt"))@@ -240,7 +276,7 @@ func TestRouter_InheritedDefaults(t *testing.T) {api.Route("/v1", func(v1 *Router) {// Should inherit security and tags from parent- v1.Get("/test", func(w http.ResponseWriter, r *http.Request) {})+ v1.GET("/test", Handler(app, testOKHandler))})})@@ -255,54 +291,18 @@ func TestRouter_InheritedDefaults(t *testing.T) {assert.Equal(t, []string{"API"}, ep.Tags)}-func TestRouter_OverrideDefaults(t *testing.T) {- r := NewRouter()-- r.Route("/api", func(api *Router) {- api.WithSecurity(NewSecurity("jwt"))- api.WithTags("API")-- api.Route("/public", func(pub *Router) {- pub.WithSecurity() // Clear security-- pub.Get("/health", func(w http.ResponseWriter, r *http.Request) {})- })-- api.Get("/protected", func(w http.ResponseWriter, r *http.Request) {})- })-- endpoints := r.Endpoints()- require.Len(t, endpoints, 2)-- // Find public endpoint- var publicEp, protectedEp *Endpoint- for i := range endpoints {- if endpoints[i].Pattern == "/api/public/health" {- publicEp = &endpoints[i]- } else {- protectedEp = &endpoints[i]- }- }-- require.NotNil(t, publicEp)- require.NotNil(t, protectedEp)-- assert.Empty(t, publicEp.Security)- require.Len(t, protectedEp.Security, 1)-}--func TestRouter_EndpointOverridesGroupDefaults(t *testing.T) {- r := NewRouter()+func TestRouter_BuilderOverridesDefaults(t *testing.T) {+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})r.Route("/api", func(api *Router) {api.WithSecurity(NewSecurity("jwt"))api.WithTags("API")// This endpoint overrides both security and tags- api.Get("/special", func(w http.ResponseWriter, r *http.Request) {},- WithSecurityRequirements(NewSecurity("api_key")),- WithTags("Special"),- )+ api.GET("/special", Handler(app, testOKHandler).+ Security(NewSecurity("api_key")).+ Tags("Special"))})endpoints := r.Endpoints()@@ -316,16 +316,15 @@ func TestRouter_EndpointOverridesGroupDefaults(t *testing.T) {assert.Equal(t, []string{"Special"}, ep.Tags)}-// --- Group without path prefix ----func TestRouter_Group(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})r.Group(func(g *Router) {g.WithSecurity(NewSecurity("jwt"))- g.Get("/a", func(w http.ResponseWriter, r *http.Request) {})- g.Get("/b", func(w http.ResponseWriter, r *http.Request) {})+ g.GET("/a", Handler(app, testOKHandler))+ g.GET("/b", Handler(app, testOKHandler))})endpoints := r.Endpoints()@@ -338,38 +337,9 @@ func TestRouter_Group(t *testing.T) {assert.Equal(t, "/b", endpoints[1].Pattern)}-// --- Handle with Endpoint struct -----func TestRouter_Handle(t *testing.T) {- r := NewRouter()-- r.Handle(Endpoint{- Method: http.MethodGet,- Pattern: "/custom",- Handler: func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- },- Summary: "Custom endpoint",- Description: "A custom endpoint",- Tags: []string{"Custom"},- Security: []Security{NewSecurity("bearer")},- })-- endpoints := r.Endpoints()- require.Len(t, endpoints, 1)-- ep := endpoints[0]- assert.Equal(t, http.MethodGet, ep.Method)- assert.Equal(t, "/custom", ep.Pattern)- assert.Equal(t, "Custom endpoint", ep.Summary)- assert.Equal(t, "A custom endpoint", ep.Description)- assert.Equal(t, []string{"Custom"}, ep.Tags)-}--// --- Middleware ----func TestRouter_Use(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})middlewareCalled := falser.Use(func(next http.Handler) http.Handler {@@ -379,9 +349,7 @@ func TestRouter_Use(t *testing.T) {})})- r.Get("/test", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- })+ r.GET("/test", Handler(app, testOKHandler))req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/test", http.NoBody)rec := httptest.NewRecorder()@@ -393,7 +361,8 @@ func TestRouter_Use(t *testing.T) {}func TestRouter_With(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})middlewareCalled := falsewithRouter := r.With(func(next http.Handler) http.Handler {@@ -404,14 +373,10 @@ func TestRouter_With(t *testing.T) {})// Original router- r.Get("/original", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- })+ r.GET("/original", Handler(app, testOKHandler))// Router with middleware- withRouter.Get("/with-middleware", func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusOK)- })+ withRouter.GET("/with-middleware", Handler(app, testOKHandler))// Test original - middleware should NOT be calledreq := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/original", http.NoBody)@@ -426,15 +391,12 @@ func TestRouter_With(t *testing.T) {assert.True(t, middlewareCalled)}-// --- Mount ----func TestRouter_Mount(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})- sub := NewRouter()- sub.Get("/users", func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte("users"))- })+ sub := NewRouter(RouterConfig{App: app})+ sub.GET("/users", Handler(app, testOKHandler))r.Mount("/api/v1", sub)@@ -442,8 +404,7 @@ func TestRouter_Mount(t *testing.T) {req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/v1/users", http.NoBody)rec := httptest.NewRecorder()r.ServeHTTP(rec, req)- body, _ := io.ReadAll(rec.Body)- assert.Equal(t, "users", string(body))+ assert.Equal(t, http.StatusOK, rec.Code)// Check endpoints are collected with prefixendpoints := r.Endpoints()@@ -451,150 +412,31 @@ func TestRouter_Mount(t *testing.T) {assert.Equal(t, "/api/v1/users", endpoints[0].Pattern)}-// --- Path Parameters -----func TestRouter_PathParams(t *testing.T) {- r := NewRouter()-- r.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {- _ = r.PathValue("id")- w.WriteHeader(http.StatusOK)- }, WithPathParams(map[string]Schema{- "id": String(new(string)).Required().UUID(),- }))-- endpoints := r.Endpoints()- require.Len(t, endpoints, 1)-- ep := endpoints[0]- require.Contains(t, ep.PathParams, "id")-}--// --- Query Parameters -----func TestRouter_QueryParams(t *testing.T) {- r := NewRouter()-- r.Get("/search", func(w http.ResponseWriter, r *http.Request) {},- WithQueryParams(map[string]Schema{- "q": String(new(string)).Required().MinLength(1),- "limit": Int(new(int)).Optional().Min(1).Max(100),- "offset": Int(new(int)).Optional().Min(0),- }),- )-- endpoints := r.Endpoints()- require.Len(t, endpoints, 1)-- ep := endpoints[0]- require.Len(t, ep.QueryParams, 3)- assert.Contains(t, ep.QueryParams, "q")- assert.Contains(t, ep.QueryParams, "limit")- assert.Contains(t, ep.QueryParams, "offset")-}--// --- Header and Cookie Parameters ---+func TestRouter_WithDefaultResponses(t *testing.T) {+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})-func TestRouter_HeaderParams(t *testing.T) {- r := NewRouter()-- r.Get("/test", func(w http.ResponseWriter, r *http.Request) {},- WithHeaderParams(map[string]Schema{- "X-Request-ID": String(new(string)).Required().UUID(),- }),- )-- endpoints := r.Endpoints()- require.Len(t, endpoints, 1)- require.Contains(t, endpoints[0].HeaderParams, "X-Request-ID")-}--func TestRouter_CookieParams(t *testing.T) {- r := NewRouter()-- r.Get("/test", func(w http.ResponseWriter, r *http.Request) {},- WithCookieParams(map[string]Schema{- "session": String(new(string)).Required(),- }),- )-- endpoints := r.Endpoints()- require.Len(t, endpoints, 1)- require.Contains(t, endpoints[0].CookieParams, "session")-}--// --- Request and Response Schemas -----type TestRequest struct {- Name string-}--func (r *TestRequest) Schema() *ObjectSchema {- return Object(map[string]Schema{- "name": String(&r.Name).Required(),- })-}--type TestResponse struct {- ID string- Name string-}+ // Create a router with default responses+ r.Route("/api", func(api *Router) {+ api.WithDefaultResponses()-func (r *TestResponse) Schema() *ObjectSchema {- return Object(map[string]Schema{- "id": String(&r.ID).Required(),- "name": String(&r.Name).Required(),+ api.GET("/test", Handler(app, testOKHandler))})-}--func TestRouter_WithRequestResponse(t *testing.T) {- r := NewRouter()-- r.Post("/users", func(w http.ResponseWriter, r *http.Request) {},- WithRequest(&TestRequest{}),- WithResponse(&TestResponse{}),- )-- endpoints := r.Endpoints()- require.Len(t, endpoints, 1)-- ep := endpoints[0]- require.NotNil(t, ep.Request)- require.NotNil(t, ep.Response)-}--func TestRouter_WithResponses(t *testing.T) {- r := NewRouter()-- r.Post("/users", func(w http.ResponseWriter, r *http.Request) {},- WithResponses(map[int]SchemaProvider{- 201: &TestResponse{},- 400: nil,- }),- )endpoints := r.Endpoints()require.Len(t, endpoints, 1)- require.Len(t, endpoints[0].Responses, 2)+ // The responses should include the handler's response+ assert.NotNil(t, endpoints[0].Responses)}-// --- Multiple Methods Same Path ----func TestRouter_MultipleMethods(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})- r.Get("/resource", func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte("GET"))- })- r.Post("/resource", func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte("POST"))- })- r.Put("/resource", func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte("PUT"))- })- r.Delete("/resource", func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte("DELETE"))- })+ r.GET("/resource", Handler(app, testOKHandler))+ r.POST("/resource", Handler(app, testCreatedHandler))+ r.PUT("/resource", Handler(app, testOKHandler))+ r.DELETE("/resource", Handler(app, testNoContentHandler))endpoints := r.Endpoints()require.Len(t, endpoints, 4)@@ -610,16 +452,12 @@ func TestRouter_MultipleMethods(t *testing.T) {assert.True(t, methods[http.MethodDelete])}-// --- Security with Scopes ----func TestRouter_SecurityWithScopes(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})- r.Get("/admin", func(w http.ResponseWriter, r *http.Request) {},- WithSecurityRequirements(- NewSecurity("oauth2", "read:admin", "write:admin"),- ),- )+ r.GET("/admin", Handler(app, testOKHandler).+ Security(NewSecurity("oauth2", "read:admin", "write:admin")))endpoints := r.Endpoints()require.Len(t, endpoints, 1)@@ -633,14 +471,11 @@ func TestRouter_SecurityWithScopes(t *testing.T) {}func TestRouter_MultipleSecurityOptions(t *testing.T) {- r := NewRouter()+ app := NewApp(AppConfig{})+ r := NewRouter(RouterConfig{App: app})- r.Get("/flexible", func(w http.ResponseWriter, r *http.Request) {},- WithSecurityRequirements(- NewSecurity("jwt"),- NewSecurity("api_key"),- ),- )+ r.GET("/flexible", Handler(app, testOKHandler).+ Security(NewSecurity("jwt"), NewSecurity("api_key")))endpoints := r.Endpoints()require.Len(t, endpoints, 1)@@ -648,55 +483,3 @@ func TestRouter_MultipleSecurityOptions(t *testing.T) {ep := endpoints[0]require.Len(t, ep.Security, 2)}--func TestRouter_Mount_PropagatesDefaults(t *testing.T) {- parent := NewRouter()- parent.WithSecurity(NewSecurity("jwt"))- parent.WithTags("api", "v1")-- child := NewRouter()- child.Handle(Endpoint{- Method: http.MethodGet,- Pattern: "/users",- Handler: func(w http.ResponseWriter, r *http.Request) {},- })-- parent.Mount("/api", child)-- endpoints := parent.Endpoints()- require.Len(t, endpoints, 1)-- ep := endpoints[0]- assert.Equal(t, "/api/users", ep.Pattern)-- // Verify defaults propagated- require.Len(t, ep.Security, 1)- assert.Equal(t, "jwt", ep.Security[0].Requirements()[0].Scheme)- assert.Equal(t, []string{"api", "v1"}, ep.Tags)-}--func TestRouter_Mount_DoesNotOverrideExplicit(t *testing.T) {- parent := NewRouter()- parent.WithSecurity(NewSecurity("jwt"))- parent.WithTags("parent-tag")-- child := NewRouter()- child.Handle(Endpoint{- Method: http.MethodGet,- Pattern: "/secure",- Handler: func(w http.ResponseWriter, r *http.Request) {},- Security: []Security{NewSecurity("apikey")}, // explicit- Tags: []string{"child-tag"}, // explicit- })-- parent.Mount("/api", child)-- endpoints := parent.Endpoints()- require.Len(t, endpoints, 1)-- ep := endpoints[0]- // Explicit values should NOT be overwritten- require.Len(t, ep.Security, 1)- assert.Equal(t, "apikey", ep.Security[0].Requirements()[0].Scheme)- assert.Equal(t, []string{"child-tag"}, ep.Tags)-}diff --git a/backend-go/pkg/api/schema.go b/backend-go/pkg/api/schema.goindex 183c568617..651f97c92c 100644--- a/backend-go/pkg/api/schema.go+++ b/backend-go/pkg/api/schema.go@@ -575,6 +575,7 @@ func (s *IntSchema) IsPresent() bool {return s.ptr != nil || s.ptr64 != nil}+//nolint:unparam // bool used for interface consistencyfunc (s *IntSchema) value() (int64, bool) {if s.ptr != nil {return int64(*s.ptr), truediff --git a/backend-go/pkg/api/schema_composite.go b/backend-go/pkg/api/schema_composite.goindex 6ff53f1930..63b4ada267 100644--- a/backend-go/pkg/api/schema_composite.go+++ b/backend-go/pkg/api/schema_composite.go@@ -23,6 +23,7 @@ type ObjectSchema struct {writeOnly booldiscriminator stringdiscriminatorMap map[string]string+ refName string// For root-level unions (body IS the union)bodyUnion *bodyUnionConfig@@ -186,7 +187,33 @@ func (s *ObjectSchema) Validate() []ValidationError {return errs}+// Ref registers this schema in the default registry and makes OpenAPI() return a $ref.+// Use this for reusable schemas that should appear in components/schemas.+func (s *ObjectSchema) Ref(name string) *ObjectSchema {+ s.refName = name+ DefaultRegistry.Register(name, s)+ return s+}++// RefName returns the registered ref name, or empty if not a ref.+func (s *ObjectSchema) RefName() string {+ return s.refName+}++// Definition returns the full schema definition, ignoring any ref.+// Use this when you need the actual schema structure (e.g., for components/schemas).+func (s *ObjectSchema) Definition() map[string]any {+ return s.definition()+}+func (s *ObjectSchema) OpenAPI() map[string]any {+ if s.refName != "" {+ return map[string]any{"$ref": "#/components/schemas/" + s.refName}+ }+ return s.definition()+}++func (s *ObjectSchema) definition() map[string]any {schema := map[string]any{"type": "object"}if len(s.properties) > 0 {@@ -264,6 +291,7 @@ type ArraySchema struct {nullable boolreadOnly boolwriteOnly bool+ refName stringvalidateFn func() []ValidationErrorisPresentFn func() bool@@ -365,7 +393,31 @@ func (s *ArraySchema) Validate() []ValidationError {return nil}+// Ref registers this schema in the default registry and makes OpenAPI() return a $ref.+func (s *ArraySchema) Ref(name string) *ArraySchema {+ s.refName = name+ DefaultRegistry.Register(name, s)+ return s+}++// RefName returns the registered ref name, or empty if not a ref.+func (s *ArraySchema) RefName() string {+ return s.refName+}++// Definition returns the full schema definition, ignoring any ref.+func (s *ArraySchema) Definition() map[string]any {+ return s.definition()+}+func (s *ArraySchema) OpenAPI() map[string]any {+ if s.refName != "" {+ return map[string]any{"$ref": "#/components/schemas/" + s.refName}+ }+ return s.definition()+}++func (s *ArraySchema) definition() map[string]any {schema := map[string]any{"type": "array"}if s.items != nil {diff --git a/backend-go/pkg/api/union.go b/backend-go/pkg/api/union.goindex e5fe486392..359c0da788 100644--- a/backend-go/pkg/api/union.go+++ b/backend-go/pkg/api/union.go@@ -589,7 +589,6 @@ type BodyUnionBuilder[T Union] struct {rawPtr *json.RawMessagetargetPtr *Tparser UnionDef[T]- fields map[string]Schema}// BodyUnion creates an ObjectSchema where the request body IS a union.diff --git a/backend-go/pkg/api/union_helpers_test.go b/backend-go/pkg/api/union_helpers_test.goindex 79ad6bc2b4..e6df20e501 100644--- a/backend-go/pkg/api/union_helpers_test.go+++ b/backend-go/pkg/api/union_helpers_test.go@@ -8,72 +8,7 @@ import ("github.com/stretchr/testify/require")-// --- ParseUnionField Tests -----func TestParseUnionField_ValidDog(t *testing.T) {- raw := json.RawMessage(`{"type": "dog", "breed": "Labrador"}`)- var animal Animal-- err := ParseUnionField(raw, &animal, AnimalParser)- require.NoError(t, err)- require.NotNil(t, animal)-- dog, ok := animal.(*Dog)- require.True(t, ok)- assert.Equal(t, "dog", dog.Type)- assert.Equal(t, "Labrador", dog.Breed)-}--func TestParseUnionField_ValidCat(t *testing.T) {- raw := json.RawMessage(`{"type": "cat", "color": "orange"}`)- var animal Animal-- err := ParseUnionField(raw, &animal, AnimalParser)- require.NoError(t, err)- require.NotNil(t, animal)-- cat, ok := animal.(*Cat)- require.True(t, ok)- assert.Equal(t, "cat", cat.Type)- assert.Equal(t, "orange", cat.Color)-}--func TestParseUnionField_Null(t *testing.T) {- raw := json.RawMessage(`null`)- var animal Animal-- err := ParseUnionField(raw, &animal, AnimalParser)- require.NoError(t, err)- assert.Nil(t, animal)-}--func TestParseUnionField_Empty(t *testing.T) {- var raw json.RawMessage- var animal Animal-- err := ParseUnionField(raw, &animal, AnimalParser)- require.NoError(t, err)- assert.Nil(t, animal)-}--func TestParseUnionField_UnknownType(t *testing.T) {- raw := json.RawMessage(`{"type": "bird", "wingspan": 2}`)- var animal Animal-- err := ParseUnionField(raw, &animal, AnimalParser)- require.Error(t, err)- assert.Contains(t, err.Error(), "bird")-}--func TestParseUnionField_InvalidJSON(t *testing.T) {- raw := json.RawMessage(`{invalid}`)- var animal Animal-- err := ParseUnionField(raw, &animal, AnimalParser)- require.Error(t, err)-}--// --- Request with json.RawMessage pattern ---+// --- ParseUnionField Integration Tests (json.RawMessage in request struct) ---type PetRequest struct {Name string `json:"name"`@@ -108,10 +43,7 @@ func TestParseUnionField_InRequest(t *testing.T) {}func TestParseUnionField_InRequest_NullPet(t *testing.T) {- data := []byte(`{- "name": "NoPet",- "pet": null- }`)+ data := []byte(`{"name": "NoPet", "pet": null}`)var req PetRequesterr := json.Unmarshal(data, &req)@@ -122,9 +54,7 @@ func TestParseUnionField_InRequest_NullPet(t *testing.T) {}func TestParseUnionField_InRequest_MissingPet(t *testing.T) {- data := []byte(`{- "name": "NoPet"- }`)+ data := []byte(`{"name": "NoPet"}`)var req PetRequesterr := json.Unmarshal(data, &req)@@ -136,7 +66,6 @@ func TestParseUnionField_InRequest_MissingPet(t *testing.T) {// --- NestedUnionDef Tests ----// Test types for nested uniontype NestedAuthMethod interface {UnionnestedAuthMarker()@@ -181,119 +110,85 @@ var NestedAuthParser = NestedUnionDef[NestedAuthMethod]{},}-func TestNestedUnionDef_Parse_Password(t *testing.T) {- data := json.RawMessage(`{- "method": "password",- "payload": {"username": "john", "password": "secret123"}- }`)-- auth, err := NestedAuthParser.Parse(data)- require.NoError(t, err)- require.NotNil(t, auth)-- pwd, ok := auth.(*PasswordPayload)- require.True(t, ok)- assert.Equal(t, "john", pwd.Username)- assert.Equal(t, "secret123", pwd.Password)-}--func TestNestedUnionDef_Parse_OAuth(t *testing.T) {- data := json.RawMessage(`{- "method": "oauth",- "payload": {"provider": "github", "accessToken": "gho_xxx"}- }`)-- auth, err := NestedAuthParser.Parse(data)- require.NoError(t, err)- require.NotNil(t, auth)-- oauth, ok := auth.(*OAuthPayload)- require.True(t, ok)- assert.Equal(t, "github", oauth.Provider)- assert.Equal(t, "gho_xxx", oauth.AccessToken)-}--func TestNestedUnionDef_Parse_Null(t *testing.T) {- data := json.RawMessage(`null`)-- auth, err := NestedAuthParser.Parse(data)- require.NoError(t, err)- assert.Nil(t, auth)-}--func TestNestedUnionDef_Parse_Empty(t *testing.T) {- var data json.RawMessage-- auth, err := NestedAuthParser.Parse(data)- require.NoError(t, err)- assert.Nil(t, auth)-}--func TestNestedUnionDef_Parse_MissingDiscriminator(t *testing.T) {- data := json.RawMessage(`{- "payload": {"username": "john", "password": "secret123"}- }`)-- _, err := NestedAuthParser.Parse(data)- require.Error(t, err)- assert.Contains(t, err.Error(), "method")-}--func TestNestedUnionDef_Parse_MissingPayload(t *testing.T) {- data := json.RawMessage(`{- "method": "password"- }`)-- _, err := NestedAuthParser.Parse(data)- require.Error(t, err)- assert.Contains(t, err.Error(), "payload")-}--func TestNestedUnionDef_Parse_UnknownType(t *testing.T) {- data := json.RawMessage(`{- "method": "saml",- "payload": {"assertion": "..."}- }`)-- _, err := NestedAuthParser.Parse(data)- require.Error(t, err)- assert.Contains(t, err.Error(), "saml")-}--func TestNestedUnionDef_Parse_InvalidJSON(t *testing.T) {- data := json.RawMessage(`{invalid}`)+func TestNestedUnionDef_Parse(t *testing.T) {+ tests := []struct {+ name string+ data json.RawMessage+ wantNil bool+ wantErr bool+ errContains string+ verify func(t *testing.T, auth NestedAuthMethod)+ }{+ {+ name: "password",+ data: json.RawMessage(`{"method": "password", "payload": {"username": "john", "password": "secret123"}}`),+ verify: func(t *testing.T, auth NestedAuthMethod) {+ pwd, ok := auth.(*PasswordPayload)+ require.True(t, ok)+ assert.Equal(t, "john", pwd.Username)+ },+ },+ {+ name: "oauth",+ data: json.RawMessage(`{"method": "oauth", "payload": {"provider": "github", "accessToken": "gho_xxx"}}`),+ verify: func(t *testing.T, auth NestedAuthMethod) {+ oauth, ok := auth.(*OAuthPayload)+ require.True(t, ok)+ assert.Equal(t, "github", oauth.Provider)+ },+ },+ {name: "null", data: json.RawMessage(`null`), wantNil: true},+ {name: "empty", data: nil, wantNil: true},+ {name: "missing discriminator", data: json.RawMessage(`{"payload": {}}`), wantErr: true, errContains: "method"},+ {name: "missing payload", data: json.RawMessage(`{"method": "password"}`), wantErr: true, errContains: "payload"},+ {name: "unknown type", data: json.RawMessage(`{"method": "saml", "payload": {}}`), wantErr: true, errContains: "saml"},+ {name: "invalid json", data: json.RawMessage(`{invalid}`), wantErr: true},+ }- _, err := NestedAuthParser.Parse(data)- require.Error(t, err)+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ auth, err := NestedAuthParser.Parse(tt.data)+ if tt.wantErr {+ require.Error(t, err)+ if tt.errContains != "" {+ assert.Contains(t, err.Error(), tt.errContains)+ }+ return+ }+ require.NoError(t, err)+ if tt.wantNil {+ assert.Nil(t, auth)+ return+ }+ require.NotNil(t, auth)+ if tt.verify != nil {+ tt.verify(t, auth)+ }+ })+ }}func TestNestedUnionDef_ParseWithType(t *testing.T) {- payload := json.RawMessage(`{"username": "jane", "password": "password123"}`)-- auth, err := NestedAuthParser.ParseWithType("password", payload)- require.NoError(t, err)- require.NotNil(t, auth)-- pwd, ok := auth.(*PasswordPayload)- require.True(t, ok)- assert.Equal(t, "jane", pwd.Username)-}--func TestNestedUnionDef_ParseWithType_UnknownType(t *testing.T) {- payload := json.RawMessage(`{"data": "..."}`)-- _, err := NestedAuthParser.ParseWithType("unknown", payload)- require.Error(t, err)- assert.Contains(t, err.Error(), "unknown")-}+ t.Run("valid", func(t *testing.T) {+ payload := json.RawMessage(`{"username": "jane", "password": "password123"}`)+ auth, err := NestedAuthParser.ParseWithType("password", payload)+ require.NoError(t, err)+ pwd, ok := auth.(*PasswordPayload)+ require.True(t, ok)+ assert.Equal(t, "jane", pwd.Username)+ })-func TestNestedUnionDef_ParseWithType_Null(t *testing.T) {- payload := json.RawMessage(`null`)+ t.Run("unknown type", func(t *testing.T) {+ _, err := NestedAuthParser.ParseWithType("unknown", json.RawMessage(`{}`))+ require.Error(t, err)+ assert.Contains(t, err.Error(), "unknown")+ })- // Null payload should error since OpenAPI marks it as required- _, err := NestedAuthParser.ParseWithType("password", payload)- require.Error(t, err)- assert.Contains(t, err.Error(), "missing")+ t.Run("null payload", func(t *testing.T) {+ _, err := NestedAuthParser.ParseWithType("password", json.RawMessage(`null`))+ require.Error(t, err)+ assert.Contains(t, err.Error(), "missing")+ })}func TestNestedUnionDef_OpenAPI(t *testing.T) {@@ -301,33 +196,22 @@ func TestNestedUnionDef_OpenAPI(t *testing.T) {assert.Equal(t, "object", openapi["type"])- props, ok := openapi["properties"].(map[string]any)- require.True(t, ok)-- // Check discriminator field- methodProp, ok := props["method"].(map[string]any)- require.True(t, ok)+ props := openapi["properties"].(map[string]any)+ methodProp := props["method"].(map[string]any)assert.Equal(t, "string", methodProp["type"])+ assert.Contains(t, methodProp["enum"].([]string), "password")+ assert.Contains(t, methodProp["enum"].([]string), "oauth")- enumVals, ok := methodProp["enum"].([]string)- require.True(t, ok)- assert.Contains(t, enumVals, "password")- assert.Contains(t, enumVals, "oauth")-- // Check payload field has oneOf- payloadProp, ok := props["payload"].(map[string]any)- require.True(t, ok)+ payloadProp := props["payload"].(map[string]any)_, hasOneOf := payloadProp["oneOf"]assert.True(t, hasOneOf)- // Check required fields- required, ok := openapi["required"].([]string)- require.True(t, ok)+ required := openapi["required"].([]string)assert.Contains(t, required, "method")assert.Contains(t, required, "payload")}-// --- ParseNestedUnionField Tests ---+// --- ParseNestedUnionField Integration Tests ---type NestedLoginRequest struct {ClientID string `json:"clientId"`@@ -361,70 +245,106 @@ func TestParseNestedUnionField_InRequest(t *testing.T) {pwd, ok := req.Auth.(*PasswordPayload)require.True(t, ok)assert.Equal(t, "john", pwd.Username)- assert.Equal(t, "secret123", pwd.Password)}-func TestParseNestedUnionField_NullDiscriminator(t *testing.T) {- data := []byte(`{- "clientId": "app-123",- "method": null,- "payload": {"username": "john", "password": "secret123"}- }`)+func TestParseNestedUnionField_NullOrMissingDiscriminator(t *testing.T) {+ tests := []struct {+ name string+ data []byte+ }{+ {"null", []byte(`{"clientId": "app", "method": null, "payload": {}}`)},+ {"missing", []byte(`{"clientId": "app", "payload": {}}`)},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ var req NestedLoginRequest+ err := json.Unmarshal(tt.data, &req)+ require.NoError(t, err)+ assert.Nil(t, req.Auth)+ })+ }+}- var req NestedLoginRequest- err := json.Unmarshal(data, &req)- require.NoError(t, err)+// --- DefaultVariant Tests ---- assert.Nil(t, req.Auth) // Discriminator is null, so no auth+type DogWithDefault struct {+ UnionBase+ Type string `json:"type"`+ Breed string `json:"breed"`}-func TestParseNestedUnionField_MissingDiscriminator(t *testing.T) {- data := []byte(`{- "clientId": "app-123",- "payload": {"username": "john", "password": "secret123"}- }`)+func (d *DogWithDefault) Schema() *ObjectSchema {+ return Object(map[string]Schema{+ "type": Const("dog"),+ "breed": String(&d.Breed).Required().Default("Unknown"),+ })+}- var req NestedLoginRequest- err := json.Unmarshal(data, &req)- require.NoError(t, err)+func (d *DogWithDefault) animalMarker() {}- assert.Nil(t, req.Auth) // Discriminator missing, so no auth+var AnimalWithDefaultParser = UnionDef[Animal]{+ Discriminator: "type",+ Variants: map[string]func() Animal{+ "dog": func() Animal { return &DogWithDefault{} },+ "cat": func() Animal { return &Cat{} },+ },}-// --- Multiple Union Fields Test ---+func TestUnionFromSchema_DefaultVariant(t *testing.T) {+ t.Run("applied when absent", func(t *testing.T) {+ var raw json.RawMessage+ var animal Animal+ schema := UnionFrom(&raw, &animal, AnimalWithDefaultParser).DefaultVariant("dog")-type MultiUnionRequestHelper struct {- PetRaw json.RawMessage `json:"pet"`- AuthRaw json.RawMessage `json:"auth"`- Pet Animal `json:"-"`- Auth NestedAuthMethod `json:"-"`-}+ errs := schema.Validate()+ assert.Empty(t, errs)+ require.NotNil(t, animal)-func (r *MultiUnionRequestHelper) UnmarshalJSON(data []byte) error {- type Plain MultiUnionRequestHelper- if err := json.Unmarshal(data, (*Plain)(r)); err != nil {- return err- }+ dog, ok := animal.(*DogWithDefault)+ require.True(t, ok)+ assert.Equal(t, "Unknown", dog.Breed)+ })- if err := ParseUnionField(r.PetRaw, &r.Pet, AnimalParser); err != nil {- return err- }+ t.Run("overridden by present value", func(t *testing.T) {+ raw := json.RawMessage(`{"type": "cat", "color": "black"}`)+ var animal Animal+ schema := UnionFrom(&raw, &animal, AnimalWithDefaultParser).DefaultVariant("dog")- return nil-}+ errs := schema.Validate()+ assert.Empty(t, errs)-func TestMultipleUnionFields_Helper(t *testing.T) {- data := []byte(`{- "pet": {"type": "cat", "color": "black"},- "auth": null- }`)+ cat, ok := animal.(*Cat)+ require.True(t, ok)+ assert.Equal(t, "black", cat.Color)+ })- var req MultiUnionRequestHelper- err := json.Unmarshal(data, &req)- require.NoError(t, err)+ t.Run("invalid name errors", func(t *testing.T) {+ var raw json.RawMessage+ var animal Animal+ schema := UnionFrom(&raw, &animal, AnimalWithDefaultParser).DefaultVariant("fish")- require.NotNil(t, req.Pet)- cat, ok := req.Pet.(*Cat)- require.True(t, ok)- assert.Equal(t, "black", cat.Color)+ errs := schema.Validate()+ require.Len(t, errs, 1)+ assert.Equal(t, "invalid_default", errs[0].Code)+ })++ t.Run("openapi includes default", func(t *testing.T) {+ var raw json.RawMessage+ var animal Animal+ schema := UnionFrom(&raw, &animal, AnimalWithDefaultParser).DefaultVariant("dog")++ openapi := schema.OpenAPI()+ defaultVal := openapi["default"].(map[string]any)+ assert.Equal(t, "dog", defaultVal["type"])+ })+}++func TestUnionFromSchema_Required_NoDefault_Fails(t *testing.T) {+ var raw json.RawMessage+ var animal Animal+ schema := UnionFrom(&raw, &animal, AnimalParser).Required()++ errs := schema.Validate()+ require.Len(t, errs, 1)+ assert.Equal(t, "required", errs[0].Code)}diff --git a/backend-go/pkg/example/main.go b/backend-go/pkg/example/main.goindex 2a43cd5bcc..4ded94632d 100644--- a/backend-go/pkg/example/main.go+++ b/backend-go/pkg/example/main.go@@ -5,16 +5,56 @@ package mainimport ("context""encoding/json"+ "errors""log"+ "log/slog""net/http"+ "os""time"- "github.com/go-chi/chi/v5""github.com/go-chi/chi/v5/middleware""github.com/google/uuid""github.com/infisical/api/pkg/api")+// =============================================================================+// Shared Schema Components (registered via .Ref() for OpenAPI $ref)+// =============================================================================++// ErrorResponse is a shared error schema registered as a component.+// Use api.Ref("ErrorResponse") to reference it in other schemas.+type ErrorResponse struct {+ api.StatusBadRequest+ StatusCode int `json:"statusCode"`+ Message string `json:"message"`+ Error string `json:"error"`+}++func (r *ErrorResponse) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "statusCode": api.Int(&r.StatusCode).Required(),+ "message": api.String(&r.Message).Required(),+ "error": api.String(&r.Error).Required(),+ }).Ref("ErrorResponse") // Registers in components/schemas+}++// User is a shared user schema for reuse across endpoints.+type User struct {+ ID uuid.UUID `json:"id"`+ Email string `json:"email"`+ Name string `json:"name"`+ Role string `json:"role"`+}++func (u *User) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "id": api.UUID(&u.ID).Required(),+ "email": api.String(&u.Email).Required().Email(),+ "name": api.String(&u.Name).Required(),+ "role": api.String(&u.Role).Required().Enum("admin", "member", "viewer"),+ }).Ref("User") // Registers in components/schemas+}+// =============================================================================// Union Types for Webhook Targets// =============================================================================@@ -254,18 +294,6 @@ func (r *LoginRequest) Schema() *api.ObjectSchema {})}-type ErrorResponse struct {- Error string `json:"error"`- Code string `json:"code"`-}--func (r *ErrorResponse) Schema() *api.ObjectSchema {- return api.Object(map[string]api.Schema{- "error": api.String(&r.Error).Required(),- "code": api.String(&r.Code).Required(),- })-}-// =============================================================================// Auth Validators// =============================================================================@@ -290,43 +318,116 @@ func (v *APIKeyValidator) Validate(ctx context.Context, r *http.Request) (any, e}// =============================================================================-// Handlers+// Response Types (typed responses with Status() and Schema())// =============================================================================-func listUsersHandler(w http.ResponseWriter, r *http.Request) {- var req ListUsersRequest- if err := api.ParseAndValidate(r, &req); err != nil {- writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", err.Error())- return- }- writeJSON(w, http.StatusOK, map[string]any{- "users": []any{},- "page": req.Page,- "pageSize": req.PageSize,+// ListUsersResponse for paginated user list+type ListUsersResponse struct {+ api.StatusOK // embed mixin instead of writing Status()+ Users []any `json:"users"`+ Page int `json:"page"`+ PageSize int `json:"pageSize"`+}++func (r *ListUsersResponse) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "users": api.Array((&User{}).Schema()).Required(), // Auto-registers User, returns $ref+ "page": api.Int(&r.Page).Required(),+ "pageSize": api.Int(&r.PageSize).Required(),})}-func createUserHandler(w http.ResponseWriter, r *http.Request) {- var req CreateUserRequest- if err := api.ParseAndValidate(r, &req); err != nil {- writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", err.Error())- return- }- writeJSON(w, http.StatusCreated, map[string]any{- "id": uuid.New(),- "email": req.Email,- "name": req.Name,- "role": req.Role,+// UserResponse for created/updated user+type UserResponse struct {+ api.StatusCreated // 201+ ID uuid.UUID `json:"id"`+ Email string `json:"email"`+ Name string `json:"name"`+ Role string `json:"role"`+}++func (r *UserResponse) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "id": api.UUID(&r.ID).Required(),+ "email": api.String(&r.Email).Required(),+ "name": api.String(&r.Name).Required(),+ "role": api.String(&r.Role).Required(),+ })+}++// UpdateUserResponse for patch response+type UpdateUserResponse struct {+ api.StatusOK+ Changes map[string]any `json:"changes"`+}++func (r *UpdateUserResponse) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "changes": api.Map(api.Object(nil)).Required(),+ })+}++// WebhookResponse for created webhook+type WebhookResponse struct {+ ID uuid.UUID `json:"id"`+ Name string `json:"name"`+ Target WebhookTarget `json:"target"`+ Enabled bool `json:"enabled"`+}++func (r *WebhookResponse) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "id": api.UUID(&r.ID).Required(),+ "name": api.String(&r.Name).Required(),+ "target": api.UnionField(&r.Target, WebhookTargetParser).Required(),+ "enabled": api.Bool(&r.Enabled).Required(),+ })+}++func (*WebhookResponse) Status() int { return http.StatusCreated }++// LoginResponse for successful login+type LoginResponse struct {+ Token string `json:"token"`+ ExpiresAt time.Time `json:"expiresAt"`+}++func (r *LoginResponse) Schema() *api.ObjectSchema {+ return api.Object(map[string]api.Schema{+ "token": api.String(&r.Token).Required(),+ "expiresAt": api.String(nil).Required().Format("date-time"),})}-func updateUserHandler(w http.ResponseWriter, r *http.Request) {- var req UpdateUserRequest- if err := api.ParseAndValidate(r, &req); err != nil {- writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", err.Error())- return+func (*LoginResponse) Status() int { return http.StatusOK }++// =============================================================================+// Typed Handlers (return value types, not pointers)+// =============================================================================++func listUsers(_ context.Context, req *ListUsersRequest) (ListUsersResponse, error) {+ return ListUsersResponse{+ Users: []any{},+ Page: req.Page,+ PageSize: req.PageSize,+ }, nil+}++func createUser(_ context.Context, req *CreateUserRequest) (UserResponse, error) {+ // Example: check for conflict+ if req.Email == "[email protected]" {+ return UserResponse{}, api.Conflict("user %s already exists", req.Email)}+ return UserResponse{+ ID: uuid.New(),+ Email: req.Email,+ Name: req.Name,+ Role: req.Role,+ }, nil+}++func updateUser(_ context.Context, req *UpdateUserRequest) (UpdateUserResponse, error) {// Tri-state PATCH handlingchanges := map[string]any{}if req.Name.IsSet() {@@ -340,16 +441,10 @@ func updateUserHandler(w http.ResponseWriter, r *http.Request) {changes["role"] = req.Role.Value}- writeJSON(w, http.StatusOK, map[string]any{"changes": changes})+ return UpdateUserResponse{Changes: changes}, nil}-func createWebhookHandler(w http.ResponseWriter, r *http.Request) {- var req CreateWebhookRequest- if err := api.ParseAndValidate(r, &req); err != nil {- writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", err.Error())- return- }-+func createWebhook(_ context.Context, req *CreateWebhookRequest) (WebhookResponse, error) {// req.Target is already parsed and validated by UnionFrom!switch t := req.Target.(type) {case *HTTPTarget:@@ -360,21 +455,15 @@ func createWebhookHandler(w http.ResponseWriter, r *http.Request) {log.Printf("Creating Discord webhook")}- writeJSON(w, http.StatusCreated, map[string]any{- "id": uuid.New(),- "name": req.Name,- "target": req.Target,- "enabled": req.Enabled,- })+ return WebhookResponse{+ ID: uuid.New(),+ Name: req.Name,+ Target: req.Target,+ Enabled: req.Enabled,+ }, nil}-func loginHandler(w http.ResponseWriter, r *http.Request) {- var req LoginRequest- if err := api.ParseAndValidate(r, &req); err != nil {- writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", err.Error())- return- }-+func login(_ context.Context, req *LoginRequest) (LoginResponse, error) {// req.Auth is already parsed and validated by UnionFrom!switch auth := req.Auth.(type) {case *PasswordAuth:@@ -385,31 +474,68 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {log.Printf("OIDC login: redirect=%s", auth.RedirectURI)}- writeJSON(w, http.StatusOK, map[string]any{- "token": "jwt-token",- "expiresAt": time.Now().Add(24 * time.Hour),- })-}--func openAPIHandler(spec *api.OpenAPISpec) http.HandlerFunc {- return func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "application/json")- json.NewEncoder(w).Encode(spec.Generate())- }+ return LoginResponse{+ Token: "jwt-token",+ ExpiresAt: time.Now().Add(24 * time.Hour),+ }, nil}// =============================================================================-// Helpers+// Error Handler (centralized)// =============================================================================-func writeJSON(w http.ResponseWriter, status int, v any) {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(status)- json.NewEncoder(w).Encode(v)-}+func newErrorHandler(logger *slog.Logger) api.ErrorHandler {+ return func(ctx context.Context, err error) *api.ErrorBody {+ // Check for api.Error+ var apiErr *api.Error+ if errors.As(err, &apiErr) {+ if apiErr.Status >= 500 {+ logger.ErrorContext(ctx, "server error",+ slog.String("name", apiErr.Name),+ slog.Int("status", apiErr.Status),+ slog.String("message", apiErr.Message),+ slog.Any("cause", apiErr.Err),+ )+ return &api.ErrorBody{+ StatusCode: apiErr.Status,+ Message: "Something went wrong",+ Error: apiErr.Name,+ }+ }-func writeError(w http.ResponseWriter, status int, code, msg string) {- writeJSON(w, status, ErrorResponse{Error: msg, Code: code})+ logger.WarnContext(ctx, "api error",+ slog.String("name", apiErr.Name),+ slog.Int("status", apiErr.Status),+ slog.String("message", apiErr.Message),+ )+ return &api.ErrorBody{+ StatusCode: apiErr.Status,+ Message: apiErr.Message,+ Error: apiErr.Name,+ Details: apiErr.Details,+ }+ }++ // Check for validation errors from ParseAndValidate+ var validationErrs api.ValidationErrors+ if errors.As(err, &validationErrs) {+ logger.WarnContext(ctx, "validation error", slog.Int("count", len(validationErrs)))+ return &api.ErrorBody{+ StatusCode: 400,+ Message: "Validation failed",+ Error: "ValidationError",+ Details: validationErrs,+ }+ }++ // Unknown error+ logger.ErrorContext(ctx, "unhandled error", slog.Any("err", err))+ return &api.ErrorBody{+ StatusCode: 500,+ Message: "Something went wrong",+ Error: "InternalServerError",+ }+ }}// =============================================================================@@ -417,112 +543,85 @@ func writeError(w http.ResponseWriter, status int, code, msg string) {// =============================================================================func main() {- // Security- security := api.NewSecurityRegistry()- security.MustRegister("bearer", api.HTTPBearerJWT(), &JWTValidator{})- security.MustRegister("apiKey", api.APIKeyHeader("X-API-Key"), &APIKeyValidator{})-- // Users router- users := api.NewRouter()- users.WithSecurity(api.NewSecurity("bearer"), api.NewSecurity("apiKey"))- users.WithTags("users")-- users.Handle(api.Endpoint{- Method: http.MethodGet,- Pattern: "/users",- Handler: listUsersHandler,- Summary: "List users",- OperationID: "listUsers",- Request: &ListUsersRequest{},- })- users.Handle(api.Endpoint{- Method: http.MethodPost,- Pattern: "/users",- Handler: createUserHandler,- Summary: "Create user",- OperationID: "createUser",- Request: &CreateUserRequest{},- })- users.Handle(api.Endpoint{- Method: http.MethodPatch,- Pattern: "/users/{userId}",- Handler: updateUserHandler,- Summary: "Update user (PATCH with tri-state)",- OperationID: "updateUser",- Request: &UpdateUserRequest{},+ // Logger+ logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))++ // Security registry+ securityRegistry := api.NewSecurityRegistry()+ securityRegistry.MustRegister("bearer", api.HTTPBearerJWT(), &JWTValidator{})+ securityRegistry.MustRegister("apiKey", api.APIKeyHeader("X-API-Key"), &APIKeyValidator{})++ // App with centralized error handler and security registry+ // SecurityRegistry enables WithSecurity to auto-install auth middleware+ app := api.NewApp(api.AppConfig{+ ErrorHandler: newErrorHandler(logger),+ SecurityRegistry: securityRegistry,})- // Webhooks router- webhooks := api.NewRouter()- webhooks.WithSecurity(api.NewSecurity("bearer"))- webhooks.WithTags("webhooks")-- webhooks.Handle(api.Endpoint{- Method: http.MethodPost,- Pattern: "/webhooks",- Handler: createWebhookHandler,- Summary: "Create webhook (union: http|slack|discord)",- OperationID: "createWebhook",- Request: &CreateWebhookRequest{},+ // Create the main router with OpenAPI configuration+ r := api.NewRouter(api.RouterConfig{+ App: app,+ Spec: &api.OpenAPIConfig{+ Info: api.OpenAPIInfo{+ Title: "Example API",+ Description: "Demonstrates unions, tri-state PATCH, typed handlers, and centralized error handling",+ Version: "1.0.0",+ },+ Servers: []api.Server{{URL: "http://localhost:8080"}},+ SecuritySchemes: securityRegistry.Schemes(),+ Tags: []api.OpenAPITag{+ {Name: "auth", Description: "Authentication (password, SAML, OIDC)"},+ {Name: "users", Description: "User management"},+ {Name: "webhooks", Description: "Webhooks (HTTP, Slack, Discord)"},+ },+ },})- // Auth router (no auth required)- auth := api.NewRouter()- auth.WithTags("auth")-- auth.Handle(api.Endpoint{- Method: http.MethodPost,- Pattern: "/login",- Handler: loginHandler,- Summary: "Login (union: password|saml|oidc)",- OperationID: "login",- Request: &LoginRequest{},- Security: []api.Security{}, // No auth+ // Add chi middlewares+ r.Use(middleware.Logger)+ r.Use(middleware.Recoverer)++ // Auth routes (no auth required)+ r.Route("/auth/{orgSlug}", func(auth *api.Router) {+ auth.WithTags("auth")++ auth.POST("/login", api.Handler(app, login).+ Summary("Login (union: password|saml|oidc)").+ OperationID("login").+ Security(api.Security{})) // No auth required (empty security)})- // Main router- root := api.NewRouter()- root.Mount("/orgs/{orgId}", users)- root.Mount("/projects/{projectId}", webhooks)- root.Mount("/auth/{orgSlug}", auth)-- // OpenAPI spec- spec := api.NewOpenAPISpec(&api.OpenAPIConfig{- Info: api.OpenAPIInfo{- Title: "Example API",- Description: "Demonstrates unions, tri-state PATCH, validation, and OpenAPI generation",- Version: "1.0.0",- },- Servers: []api.Server{{URL: "http://localhost:8080"}},- SecuritySchemes: security.Schemes(),- Tags: []api.OpenAPITag{- {Name: "auth", Description: "Authentication (password, SAML, OIDC)"},- {Name: "users", Description: "User management"},- {Name: "webhooks", Description: "Webhooks (HTTP, Slack, Discord)"},- },+ // Protected routes - WithSecurity auto-installs middleware when registry is configured+ r.Route("/orgs/{orgId}", func(orgs *api.Router) {+ orgs.WithSecurity(api.NewSecurity("bearer"), api.NewSecurity("apiKey"))+ orgs.WithTags("users")++ orgs.GET("/users", api.Handler(app, listUsers).+ Summary("List users").+ OperationID("listUsers"))++ orgs.POST("/users", api.Handler(app, createUser).+ Summary("Create user").+ OperationID("createUser"))++ orgs.PATCH("/users/{userId}", api.Handler(app, updateUser).+ Summary("Update user (PATCH with tri-state)").+ OperationID("updateUser"))})- spec.AddEndpoints(root.Endpoints())- // Chi router- r := chi.NewRouter()- r.Use(middleware.Logger)- r.Use(middleware.Recoverer)+ // Webhooks routes+ r.Route("/projects/{projectId}", func(projects *api.Router) {+ projects.WithSecurity(api.NewSecurity("bearer"))+ projects.WithTags("webhooks")- r.Get("/openapi.json", openAPIHandler(spec))- r.Post("/auth/{orgSlug}/login", loginHandler)-- r.Group(func(r chi.Router) {- r.Use(security.Middleware(- []api.Security{api.NewSecurity("bearer"), api.NewSecurity("apiKey")},- nil,- ))- for _, ep := range root.Endpoints() {- if len(ep.Security) > 0 {- r.Method(ep.Method, ep.Pattern, ep.Handler)- }- }+ projects.POST("/webhooks", api.Handler(app, createWebhook).+ Summary("Create webhook (union: http|slack|discord)").+ OperationID("createWebhook"))})+ // Serve OpenAPI spec+ r.ServeSpec("/openapi.json")+log.Println("Server: http://localhost:8080")log.Println("OpenAPI: http://localhost:8080/openapi.json")log.Println("")@@ -536,6 +635,10 @@ func main() {log.Println("")log.Println(` curl -X PATCH localhost:8080/orgs/$(uuidgen)/users/$(uuidgen) -H "Authorization: Bearer x" \`)log.Println(` -H "Content-Type: application/json" -d '{"name":"New Name","role":null}'`)+ log.Println("")+ log.Println(` # Test conflict error:`)+ log.Println(` curl -X POST localhost:8080/orgs/$(uuidgen)/users -H "Authorization: Bearer x" \`)+ log.Println(` -H "Content-Type: application/json" -d '{"email":"[email protected]","name":"Test","role":"member"}'`)log.Fatal(http.ListenAndServe(":8080", r))}