Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: first bare server

=14c7c8e7659b
diff --git a/backend-go/pkg/api/README.md b/backend-go/pkg/api/README.md
new file mode 100644
index 0000000000..d65b65e985
--- /dev/null
+++ b/backend-go/pkg/api/README.md
@@ -0,0 +1,356 @@
+# pkg/api
+
+Type-safe API framework with pointer-binding schemas. Single source of truth for validation AND OpenAPI generation. No runtime reflection.
+
+## Quick Start
+
+```go
+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()
+
+// Generate OpenAPI
+openapi := req.Schema().OpenAPI()
+```
+
+## Schema Types
+
+### Primitives
+
+```go
+api.String(&s).Required().MinLength(1).MaxLength(100).Pattern(`^\w+$`).Enum("a","b").Email().UUID()
+api.Int(&i).Required().Min(0).Max(100)
+api.Float(&f).Required().Min(0.0).Max(1.0)
+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
+// Object
+api.Object(map[string]api.Schema{...}).Required()
+
+// Array
+api.Array(api.String(new(string))).Required().MinItems(1).MaxItems(10)
+
+// Map (string keys)
+api.Map(api.String(new(string))).Required()
+
+// Reference
+api.Ref("#/components/schemas/User")
+
+// Const
+api.Const("fixed-value")
+```
+
+## Union Types
+
+### Flat Discriminated Union
+
+```json
+{"type": "dog", "breed": "Labrador"}
+```
+
+```go
+// 1. Define interface + variants
+type Animal interface {
+ api.Union
+ animalMarker()
+}
+
+type Dog struct {
+ Type 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) animalMarker() {}
+
+// 2. Define parser
+var AnimalParser = api.UnionDef[Animal]{
+ Discriminator: "type",
+ Variants: map[string]func() Animal{
+ "dog": func() Animal { return &Dog{} },
+ "cat": func() Animal { return &Cat{} },
+ },
+}
+
+// 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)
+}
+
+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)
+```
+
+### 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(),
+)
+```
+
+## 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
+}
+
+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
+}
+
+// 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)
+```
+
+### Security Relationships
+
+```go
+// OR - any one succeeds
+[]api.Security{
+ api.NewSecurity("jwt"),
+ api.NewSecurity("apiKey"),
+}
+
+// AND - both must pass
+[]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
+
+```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
+
+```go
+api.HTTPBearer()
+api.HTTPBearerJWT()
+api.HTTPBasic()
+api.APIKeyHeader(name)
+api.APIKeyQuery(name)
+api.APIKeyCookie(name)
+api.OpenIDConnect(discoveryURL)
+api.OAuth2Implicit(authURL, scopes)
+api.OAuth2Password(tokenURL, scopes)
+api.OAuth2ClientCredentials(tokenURL, scopes)
+api.OAuth2AuthorizationCode(authURL, tokenURL, scopes)
+```
+
+## JsonNullable for Optional Fields
+
+Distinguish between absent, null, and present values:
+
+```go
+type Request struct {
+ Count api.JsonNullable[int] `json:"count"`
+}
+
+// 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
+
+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
+}
+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:
+
+```go
+decoder := json.NewDecoder(r.Body)
+decoder.DisallowUnknownFields()
+if err := decoder.Decode(&req); err != nil { ... }
+```
+
+## Common Chainable Methods
+
+All schemas support:
+```go
+.Required()
+.Optional()
+.Title(string)
+.Description(string)
+.Example(any)
+.Deprecated()
+.Nullable()
+.ReadOnly()
+.WriteOnly()
+.Default(value)
+```
diff --git a/backend-go/pkg/api/REVIEW.md b/backend-go/pkg/api/REVIEW.md
new file mode 100644
index 0000000000..b95629f3cd
--- /dev/null
+++ b/backend-go/pkg/api/REVIEW.md
@@ -0,0 +1,130 @@
+# 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.md
new file mode 100644
index 0000000000..996cd652af
--- /dev/null
+++ b/backend-go/pkg/api/REVIEW_TEST.md
@@ -0,0 +1,141 @@
+# 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.go
new file mode 100644
index 0000000000..5f967b661e
--- /dev/null
+++ b/backend-go/pkg/api/auth.go
@@ -0,0 +1,678 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "strings"
+ "sync"
+)
+
+// ErrSkipToNextAuth is returned by a validator to indicate that authentication
+// should continue with the next security scheme. If all schemes return this error,
+// the request is unauthorized.
+var ErrSkipToNextAuth = errors.New("skip to next auth")
+
+// authResultContextKey is the context key for AuthResult
+type authResultContextKey struct{}
+
+// AuthResult contains the result of successful authentication.
+// Retrieved from context via GetAuthResult().
+type AuthResult struct {
+ // Schemes lists which security schemes passed (in order, for AND relationships)
+ Schemes []string
+ // Claims maps scheme name to its claims (for AND relationships, all are present)
+ Claims map[string]any
+}
+
+// GetClaims returns claims for the first scheme that passed.
+// Use GetClaimsByScheme for AND relationships where you need specific claims.
+func (r *AuthResult) GetClaims() any {
+ if r == nil || len(r.Schemes) == 0 {
+ return nil
+ }
+ return r.Claims[r.Schemes[0]]
+}
+
+// GetClaimsByScheme returns claims for a specific scheme name.
+func (r *AuthResult) GetClaimsByScheme(scheme string) any {
+ if r == nil || r.Claims == nil {
+ return nil
+ }
+ return r.Claims[scheme]
+}
+
+// GetAuthResult retrieves the AuthResult from the request context.
+// Returns nil if no authentication was performed or failed.
+func GetAuthResult(ctx context.Context) *AuthResult {
+ if result, ok := ctx.Value(authResultContextKey{}).(*AuthResult); ok {
+ return result
+ }
+ return nil
+}
+
+// setAuthResult stores the AuthResult in the context.
+func setAuthResult(ctx context.Context, result *AuthResult) context.Context {
+ return context.WithValue(ctx, authResultContextKey{}, result)
+}
+
+// Validator is the interface that auth validators must implement.
+// Implement this interface with your dependencies (db, keystore, etc.)
+// injected via the struct.
+type Validator interface {
+ // Validate authenticates the request and returns claims on success.
+ // Return ErrSkipToNextAuth to try the next security scheme.
+ // Return any other error to immediately reject the request.
+ // Return (claims, nil) on successful authentication.
+ Validate(ctx context.Context, r *http.Request) (claims any, err error)
+}
+
+// ValidatorFunc is an adapter to allow ordinary functions to be used as Validators.
+type ValidatorFunc func(ctx context.Context, r *http.Request) (any, error)
+
+// Validate calls the underlying function.
+func (f ValidatorFunc) Validate(ctx context.Context, r *http.Request) (any, error) {
+ return f(ctx, r)
+}
+
+// SecurityScheme defines an OpenAPI security scheme.
+// This is purely metadata for OpenAPI generation - validators are registered separately.
+type SecurityScheme struct {
+ // Type is the security scheme type: "http", "apiKey", "oauth2", "openIdConnect"
+ Type string
+
+ // Scheme is the HTTP auth scheme (for type "http"): "bearer", "basic", "digest", etc.
+ Scheme string
+
+ // BearerFormat hints at the token format (for scheme "bearer"): "JWT", etc.
+ BearerFormat string
+
+ // In specifies where the API key is sent (for type "apiKey"): "header", "query", "cookie"
+ In string
+
+ // Name is the name of the header, query parameter, or cookie (for type "apiKey")
+ Name string
+
+ // Description describes the security scheme
+ Description string
+
+ // OpenIDConnectURL is the OpenID Connect discovery URL (for type "openIdConnect")
+ OpenIDConnectURL string
+
+ // Flows defines OAuth2 flows (for type "oauth2")
+ Flows *OAuthFlows
+}
+
+// OAuthFlows defines OAuth2 flow configurations
+type OAuthFlows struct {
+ Implicit *OAuthFlow
+ Password *OAuthFlow
+ ClientCredentials *OAuthFlow
+ AuthorizationCode *OAuthFlow
+}
+
+// OAuthFlow defines an OAuth2 flow
+type OAuthFlow struct {
+ AuthorizationURL string
+ TokenURL string
+ RefreshURL string
+ Scopes map[string]string
+}
+
+// --- SecurityScheme Builders (return pointer for chaining) ---
+
+// HTTPBearer creates an HTTP bearer token security scheme
+func HTTPBearer() *SecurityScheme {
+ return &SecurityScheme{
+ Type: "http",
+ Scheme: "bearer",
+ }
+}
+
+// HTTPBearerJWT creates an HTTP bearer token security scheme with JWT format
+func HTTPBearerJWT() *SecurityScheme {
+ return &SecurityScheme{
+ Type: "http",
+ Scheme: "bearer",
+ BearerFormat: "JWT",
+ }
+}
+
+// HTTPBasic creates an HTTP basic auth security scheme
+func HTTPBasic() *SecurityScheme {
+ return &SecurityScheme{
+ Type: "http",
+ Scheme: "basic",
+ }
+}
+
+// APIKeyHeader creates an API key in header security scheme
+func APIKeyHeader(name string) *SecurityScheme {
+ return &SecurityScheme{
+ Type: "apiKey",
+ In: "header",
+ Name: name,
+ }
+}
+
+// APIKeyQuery creates an API key in query parameter security scheme
+func APIKeyQuery(name string) *SecurityScheme {
+ return &SecurityScheme{
+ Type: "apiKey",
+ In: "query",
+ Name: name,
+ }
+}
+
+// APIKeyCookie creates an API key in cookie security scheme
+func APIKeyCookie(name string) *SecurityScheme {
+ return &SecurityScheme{
+ Type: "apiKey",
+ In: "cookie",
+ Name: name,
+ }
+}
+
+// OpenIDConnect creates an OpenID Connect security scheme
+func OpenIDConnect(discoveryURL string) *SecurityScheme {
+ return &SecurityScheme{
+ Type: "openIdConnect",
+ OpenIDConnectURL: discoveryURL,
+ }
+}
+
+// OAuth2Implicit creates an OAuth2 implicit flow security scheme
+func OAuth2Implicit(authURL string, scopes map[string]string) *SecurityScheme {
+ return &SecurityScheme{
+ Type: "oauth2",
+ Flows: &OAuthFlows{
+ Implicit: &OAuthFlow{
+ AuthorizationURL: authURL,
+ Scopes: scopes,
+ },
+ },
+ }
+}
+
+// OAuth2Password creates an OAuth2 password flow security scheme
+func OAuth2Password(tokenURL string, scopes map[string]string) *SecurityScheme {
+ return &SecurityScheme{
+ Type: "oauth2",
+ Flows: &OAuthFlows{
+ Password: &OAuthFlow{
+ TokenURL: tokenURL,
+ Scopes: scopes,
+ },
+ },
+ }
+}
+
+// OAuth2ClientCredentials creates an OAuth2 client credentials flow security scheme
+func OAuth2ClientCredentials(tokenURL string, scopes map[string]string) *SecurityScheme {
+ return &SecurityScheme{
+ Type: "oauth2",
+ Flows: &OAuthFlows{
+ ClientCredentials: &OAuthFlow{
+ TokenURL: tokenURL,
+ Scopes: scopes,
+ },
+ },
+ }
+}
+
+// OAuth2AuthorizationCode creates an OAuth2 authorization code flow security scheme
+func OAuth2AuthorizationCode(authURL, tokenURL string, scopes map[string]string) *SecurityScheme {
+ return &SecurityScheme{
+ Type: "oauth2",
+ Flows: &OAuthFlows{
+ AuthorizationCode: &OAuthFlow{
+ AuthorizationURL: authURL,
+ TokenURL: tokenURL,
+ Scopes: scopes,
+ },
+ },
+ }
+}
+
+// --- SecurityScheme Chainable Methods ---
+
+// WithDescription sets the description for this security scheme.
+func (s *SecurityScheme) WithDescription(desc string) *SecurityScheme {
+ s.Description = desc
+ return s
+}
+
+// WithBearerFormat sets the bearer format (e.g., "JWT") for HTTP bearer schemes.
+func (s *SecurityScheme) WithBearerFormat(format string) *SecurityScheme {
+ s.BearerFormat = format
+ return s
+}
+
+// --- SecurityScheme OpenAPI Generation ---
+
+// OpenAPI returns the OpenAPI representation of the security scheme.
+func (s *SecurityScheme) OpenAPI() map[string]any {
+ if s == nil {
+ return nil
+ }
+
+ result := map[string]any{
+ "type": s.Type,
+ }
+
+ if s.Description != "" {
+ result["description"] = s.Description
+ }
+
+ switch s.Type {
+ case "http":
+ result["scheme"] = s.Scheme
+ if s.BearerFormat != "" {
+ result["bearerFormat"] = s.BearerFormat
+ }
+
+ case "apiKey":
+ result["in"] = s.In
+ result["name"] = s.Name
+
+ case "openIdConnect":
+ result["openIdConnectUrl"] = s.OpenIDConnectURL
+
+ case "oauth2":
+ if s.Flows != nil {
+ result["flows"] = s.Flows.OpenAPI()
+ }
+ }
+
+ return result
+}
+
+// OpenAPI returns the OpenAPI representation of OAuth flows
+func (f *OAuthFlows) OpenAPI() map[string]any {
+ flows := make(map[string]any)
+
+ if f.Implicit != nil {
+ flows["implicit"] = f.Implicit.OpenAPI()
+ }
+ if f.Password != nil {
+ flows["password"] = f.Password.OpenAPI()
+ }
+ if f.ClientCredentials != nil {
+ flows["clientCredentials"] = f.ClientCredentials.OpenAPI()
+ }
+ if f.AuthorizationCode != nil {
+ flows["authorizationCode"] = f.AuthorizationCode.OpenAPI()
+ }
+
+ return flows
+}
+
+// OpenAPI returns the OpenAPI representation of an OAuth flow
+func (f *OAuthFlow) OpenAPI() map[string]any {
+ result := make(map[string]any)
+
+ if f.AuthorizationURL != "" {
+ result["authorizationUrl"] = f.AuthorizationURL
+ }
+ if f.TokenURL != "" {
+ result["tokenUrl"] = f.TokenURL
+ }
+ if f.RefreshURL != "" {
+ result["refreshUrl"] = f.RefreshURL
+ }
+ if f.Scopes != nil {
+ result["scopes"] = f.Scopes
+ } else {
+ result["scopes"] = map[string]string{}
+ }
+
+ return result
+}
+
+// --- Security Requirement ---
+
+// SecurityRequirement is a single scheme + scopes pair.
+type SecurityRequirement struct {
+ Scheme string
+ Scopes []string
+}
+
+// Security represents a security requirement for an endpoint.
+// Multiple schemes in one Security = AND (all required, validated in order)
+// Multiple Security entries on endpoint = OR (any one suffices)
+type Security struct {
+ requirements []SecurityRequirement
+}
+
+// NewSecurity creates a security requirement for a scheme with optional scopes
+func NewSecurity(scheme string, scopes ...string) Security {
+ return Security{
+ requirements: []SecurityRequirement{{Scheme: scheme, Scopes: scopes}},
+ }
+}
+
+// And adds another scheme requirement (AND relationship - both must pass).
+// Schemes are validated in the order they are added.
+func (s Security) And(scheme string, scopes ...string) Security {
+ s.requirements = append(s.requirements, SecurityRequirement{Scheme: scheme, Scopes: scopes})
+ return s
+}
+
+// IsEmpty returns true if no schemes are required (allows unauthenticated access)
+func (s Security) IsEmpty() bool {
+ return len(s.requirements) == 0
+}
+
+// Requirements returns the ordered list of security requirements.
+func (s Security) Requirements() []SecurityRequirement {
+ return s.requirements
+}
+
+// ToMap converts to OpenAPI security requirement format (map of scheme to scopes).
+func (s Security) ToMap() map[string][]string {
+ result := make(map[string][]string, len(s.requirements))
+ for _, req := range s.requirements {
+ scopes := req.Scopes
+ if scopes == nil {
+ scopes = []string{} // OpenAPI requires array, not null
+ }
+ result[req.Scheme] = scopes
+ }
+ return result
+}
+
+// --- Security Registry ---
+
+// registeredScheme pairs a security scheme with its validator
+type registeredScheme struct {
+ scheme *SecurityScheme
+ validator Validator
+}
+
+// SecurityRegistry holds registered security schemes and their validators.
+// Thread-safe for reads after startup. Register all schemes during initialization
+// before starting the server.
+type SecurityRegistry struct {
+ mu sync.RWMutex
+ schemes map[string]*registeredScheme
+}
+
+// NewSecurityRegistry creates a new security registry
+func NewSecurityRegistry() *SecurityRegistry {
+ return &SecurityRegistry{
+ schemes: make(map[string]*registeredScheme),
+ }
+}
+
+// MustRegister registers a security scheme with its validator.
+// Panics if:
+// - A scheme with the same name is already registered
+// - The validator is nil
+//
+// Call this at startup to fail fast if auth is misconfigured.
+// Note: All registration should happen before starting the server.
+func (r *SecurityRegistry) MustRegister(name string, scheme *SecurityScheme, validator Validator) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ if _, exists := r.schemes[name]; exists {
+ panic("api: security scheme already registered: " + name)
+ }
+ if validator == nil {
+ panic("api: validator is nil for security scheme: " + name)
+ }
+ if scheme == nil {
+ panic("api: scheme is nil for security scheme: " + name)
+ }
+
+ r.schemes[name] = &registeredScheme{
+ scheme: scheme,
+ validator: validator,
+ }
+}
+
+// Register is like MustRegister but returns an error instead of panicking.
+// Note: All registration should happen before starting the server.
+func (r *SecurityRegistry) Register(name string, scheme *SecurityScheme, validator Validator) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ if _, exists := r.schemes[name]; exists {
+ return errors.New("api: security scheme already registered: " + name)
+ }
+ if validator == nil {
+ return errors.New("api: validator is nil for security scheme: " + name)
+ }
+ if scheme == nil {
+ return errors.New("api: scheme is nil for security scheme: " + name)
+ }
+
+ r.schemes[name] = &registeredScheme{
+ scheme: scheme,
+ validator: validator,
+ }
+ return nil
+}
+
+// GetScheme returns the SecurityScheme for a given name, or nil if not found.
+func (r *SecurityRegistry) GetScheme(name string) *SecurityScheme {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ if reg, ok := r.schemes[name]; ok {
+ return reg.scheme
+ }
+ return nil
+}
+
+// GetValidator returns the Validator for a given name, or nil if not found.
+func (r *SecurityRegistry) GetValidator(name string) Validator {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ if reg, ok := r.schemes[name]; ok {
+ return reg.validator
+ }
+ return nil
+}
+
+// Schemes returns all registered security schemes (for OpenAPI generation).
+func (r *SecurityRegistry) Schemes() map[string]*SecurityScheme {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ result := make(map[string]*SecurityScheme, len(r.schemes))
+ for name, reg := range r.schemes {
+ result[name] = reg.scheme
+ }
+ return result
+}
+
+// ValidateSecurityRequirements checks that all schemes referenced in security
+// requirements are registered. Returns an error listing any missing schemes.
+// Call this at startup to fail fast.
+func (r *SecurityRegistry) ValidateSecurityRequirements(security []Security) error {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ var missing []string
+
+ for _, sec := range security {
+ for _, req := range sec.requirements {
+ if _, ok := r.schemes[req.Scheme]; !ok {
+ missing = append(missing, req.Scheme)
+ }
+ }
+ }
+
+ if len(missing) > 0 {
+ return errors.New("api: unregistered security schemes: " + strings.Join(missing, ", "))
+ }
+
+ return nil
+}
+
+// --- Authentication Middleware ---
+
+// AuthErrorHandler is called when authentication fails.
+// Use this to customize error responses (JSON, headers, etc.)
+type AuthErrorHandler func(w http.ResponseWriter, r *http.Request, err error)
+
+// Middleware creates authentication middleware for the given security requirements.
+//
+// Security requirements use OR relationship - first successful auth wins.
+// Within a Security entry, schemes use AND relationship - all must pass in order.
+//
+// Behavior:
+// - If security is empty or contains only empty Security{}, allows unauthenticated access
+// - Tries each Security entry until one succeeds
+// - On success, stores AuthResult in context (retrieve via GetAuthResult)
+// - On failure, calls errorHandler or returns 401 with WWW-Authenticate header
+func (r *SecurityRegistry) Middleware(security []Security, errorHandler AuthErrorHandler) func(http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ // No security requirements = allow through
+ if len(security) == 0 {
+ next.ServeHTTP(w, req)
+ return
+ }
+
+ // Check for explicitly optional auth (empty Security{})
+ for _, sec := range security {
+ if sec.IsEmpty() {
+ next.ServeHTTP(w, req)
+ return
+ }
+ }
+
+ // Try each Security entry (OR relationship)
+ var lastErr error
+ for _, sec := range security {
+ result, err := r.trySecurityRequirement(req, sec)
+ if err == nil {
+ // Success - store result in context and continue
+ ctx := setAuthResult(req.Context(), result)
+ next.ServeHTTP(w, req.WithContext(ctx))
+ return
+ }
+
+ lastErr = err
+
+ // If not ErrSkipToNextAuth, stop trying other schemes
+ if !errors.Is(err, ErrSkipToNextAuth) {
+ break
+ }
+ }
+
+ // All security requirements failed
+ if errorHandler != nil {
+ errorHandler(w, req, lastErr)
+ } else {
+ // RFC 7235: 401 responses SHOULD include WWW-Authenticate
+ // (omit for apiKey-only routes where no standard challenge exists)
+ if challenge := r.buildWWWAuthenticate(security); challenge != "" {
+ w.Header().Set("WWW-Authenticate", challenge)
+ }
+ http.Error(w, "Unauthorized", http.StatusUnauthorized)
+ }
+ })
+ }
+}
+
+// trySecurityRequirement attempts to authenticate using a Security entry.
+// All schemes in the entry must pass (AND relationship), in order.
+// Claims from all schemes are accumulated in AuthResult.
+func (r *SecurityRegistry) trySecurityRequirement(req *http.Request, sec Security) (*AuthResult, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ requirements := sec.Requirements()
+ if len(requirements) == 0 {
+ return nil, ErrSkipToNextAuth
+ }
+
+ result := &AuthResult{
+ Schemes: make([]string, 0, len(requirements)),
+ Claims: make(map[string]any, len(requirements)),
+ }
+
+ for _, requirement := range requirements {
+ registered, ok := r.schemes[requirement.Scheme]
+ if !ok {
+ return nil, errors.New("api: unregistered security scheme: " + requirement.Scheme)
+ }
+
+ claims, 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) {
+ return nil, ErrSkipToNextAuth
+ }
+ // Any other error (invalid token, expired, etc.) is a hard failure
+ return nil, err
+ }
+
+ // Accumulate claims from each scheme
+ result.Schemes = append(result.Schemes, requirement.Scheme)
+ result.Claims[requirement.Scheme] = claims
+ }
+
+ return result, nil
+}
+
+// buildWWWAuthenticate constructs the WWW-Authenticate header value.
+// Lists all unique auth schemes from the security requirements.
+func (r *SecurityRegistry) buildWWWAuthenticate(security []Security) string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ seen := make(map[string]bool)
+ var challenges []string
+
+ for _, sec := range security {
+ for _, req := range sec.Requirements() {
+ if seen[req.Scheme] {
+ continue
+ }
+ seen[req.Scheme] = true
+
+ registered, ok := r.schemes[req.Scheme]
+ if !ok {
+ continue
+ }
+
+ challenge := r.formatChallenge(registered.scheme)
+ if challenge != "" {
+ challenges = append(challenges, challenge)
+ }
+ }
+ }
+
+ if len(challenges) == 0 {
+ // No standard challenges (e.g., apiKey-only routes)
+ // Return empty - caller should omit WWW-Authenticate header
+ return ""
+ }
+ return strings.Join(challenges, ", ")
+}
+
+// formatChallenge formats a single WWW-Authenticate challenge for a scheme.
+func (r *SecurityRegistry) formatChallenge(scheme *SecurityScheme) string {
+ switch scheme.Type {
+ case "http":
+ switch scheme.Scheme {
+ case "bearer":
+ return "Bearer"
+ case "basic":
+ return "Basic"
+ default:
+ return scheme.Scheme
+ }
+ case "apiKey":
+ return ""
+ default:
+ return ""
+ }
+}
diff --git a/backend-go/pkg/api/auth_test.go b/backend-go/pkg/api/auth_test.go
new file mode 100644
index 0000000000..21fab20dc4
--- /dev/null
+++ b/backend-go/pkg/api/auth_test.go
@@ -0,0 +1,951 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// --- 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",
+ }
+ 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",
+ }
+ 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)
+}
+
+// --- SecurityScheme.OpenAPI ---
+
+func TestSecurityScheme_OpenAPI_HTTP(t *testing.T) {
+ scheme := HTTPBearerJWT().WithDescription("JWT auth")
+
+ openapi := scheme.OpenAPI()
+
+ assert.Equal(t, "http", openapi["type"])
+ assert.Equal(t, "bearer", openapi["scheme"])
+ assert.Equal(t, "JWT", openapi["bearerFormat"])
+ assert.Equal(t, "JWT auth", openapi["description"])
+}
+
+func TestSecurityScheme_OpenAPI_APIKey(t *testing.T) {
+ scheme := APIKeyHeader("X-API-Key").WithDescription("API key")
+
+ openapi := scheme.OpenAPI()
+
+ assert.Equal(t, "apiKey", openapi["type"])
+ assert.Equal(t, "header", openapi["in"])
+ assert.Equal(t, "X-API-Key", openapi["name"])
+}
+
+func TestSecurityScheme_OpenAPI_OpenIDConnect(t *testing.T) {
+ scheme := OpenIDConnect("https://example.com/.well-known/openid").
+ WithDescription("OIDC")
+
+ openapi := scheme.OpenAPI()
+
+ assert.Equal(t, "openIdConnect", openapi["type"])
+ assert.Equal(t, "https://example.com/.well-known/openid", openapi["openIdConnectUrl"])
+}
+
+func TestSecurityScheme_OpenAPI_OAuth2(t *testing.T) {
+ scheme := &SecurityScheme{
+ Type: "oauth2",
+ Description: "OAuth2 all flows",
+ Flows: &OAuthFlows{
+ Implicit: &OAuthFlow{
+ AuthorizationURL: "https://example.com/auth",
+ Scopes: map[string]string{"read": "Read"},
+ },
+ Password: &OAuthFlow{
+ TokenURL: "https://example.com/token",
+ Scopes: map[string]string{"write": "Write"},
+ },
+ ClientCredentials: &OAuthFlow{
+ TokenURL: "https://example.com/token",
+ Scopes: map[string]string{"admin": "Admin"},
+ },
+ AuthorizationCode: &OAuthFlow{
+ AuthorizationURL: "https://example.com/auth",
+ TokenURL: "https://example.com/token",
+ RefreshURL: "https://example.com/refresh",
+ Scopes: map[string]string{"all": "All access"},
+ },
+ },
+ }
+
+ openapi := scheme.OpenAPI()
+
+ assert.Equal(t, "oauth2", openapi["type"])
+
+ flows, ok := openapi["flows"].(map[string]any)
+ require.True(t, ok)
+
+ implicit, ok := flows["implicit"].(map[string]any)
+ require.True(t, ok)
+ assert.Equal(t, "https://example.com/auth", implicit["authorizationUrl"])
+
+ password, ok := flows["password"].(map[string]any)
+ require.True(t, ok)
+ assert.Equal(t, "https://example.com/token", password["tokenUrl"])
+
+ clientCreds, ok := flows["clientCredentials"].(map[string]any)
+ require.True(t, ok)
+ assert.Equal(t, "https://example.com/token", clientCreds["tokenUrl"])
+
+ authCode, ok := flows["authorizationCode"].(map[string]any)
+ require.True(t, ok)
+ assert.Equal(t, "https://example.com/auth", authCode["authorizationUrl"])
+ assert.Equal(t, "https://example.com/token", authCode["tokenUrl"])
+ assert.Equal(t, "https://example.com/refresh", authCode["refreshUrl"])
+}
+
+func TestSecurityScheme_OpenAPI_Nil(t *testing.T) {
+ var scheme *SecurityScheme
+ assert.Nil(t, scheme.OpenAPI())
+}
+
+// --- OAuthFlow.OpenAPI ---
+
+func TestOAuthFlow_OpenAPI(t *testing.T) {
+ flow := OAuthFlow{
+ AuthorizationURL: "https://example.com/auth",
+ TokenURL: "https://example.com/token",
+ RefreshURL: "https://example.com/refresh",
+ Scopes: map[string]string{
+ "read": "Read access",
+ "write": "Write access",
+ },
+ }
+
+ openapi := flow.OpenAPI()
+
+ assert.Equal(t, "https://example.com/auth", openapi["authorizationUrl"])
+ assert.Equal(t, "https://example.com/token", openapi["tokenUrl"])
+ assert.Equal(t, "https://example.com/refresh", openapi["refreshUrl"])
+
+ scopes, ok := openapi["scopes"].(map[string]string)
+ require.True(t, ok)
+ assert.Equal(t, "Read access", scopes["read"])
+ assert.Equal(t, "Write access", scopes["write"])
+}
+
+func TestOAuthFlow_OpenAPI_EmptyScopes(t *testing.T) {
+ flow := OAuthFlow{
+ TokenURL: "https://example.com/token",
+ }
+
+ openapi := flow.OpenAPI()
+
+ scopes, ok := openapi["scopes"].(map[string]string)
+ require.True(t, ok)
+ assert.Empty(t, scopes)
+}
+
+// --- Security (requirement) ---
+
+func TestNewSecurity(t *testing.T) {
+ sec := NewSecurity("jwt")
+
+ reqs := sec.Requirements()
+ require.Len(t, reqs, 1)
+ assert.Equal(t, "jwt", reqs[0].Scheme)
+ assert.Empty(t, reqs[0].Scopes)
+}
+
+func TestNewSecurity_WithScopes(t *testing.T) {
+ sec := NewSecurity("oauth2", "read", "write")
+
+ reqs := sec.Requirements()
+ require.Len(t, reqs, 1)
+ assert.Equal(t, "oauth2", reqs[0].Scheme)
+ assert.Equal(t, []string{"read", "write"}, reqs[0].Scopes)
+}
+
+func TestSecurity_And(t *testing.T) {
+ sec := NewSecurity("jwt").And("api_key")
+
+ reqs := sec.Requirements()
+ require.Len(t, reqs, 2)
+ assert.Equal(t, "jwt", reqs[0].Scheme)
+ assert.Equal(t, "api_key", reqs[1].Scheme)
+}
+
+func TestSecurity_And_WithScopes(t *testing.T) {
+ sec := NewSecurity("oauth2", "read").And("jwt")
+
+ reqs := sec.Requirements()
+ require.Len(t, reqs, 2)
+ assert.Equal(t, "oauth2", reqs[0].Scheme)
+ assert.Equal(t, []string{"read"}, reqs[0].Scopes)
+ assert.Equal(t, "jwt", reqs[1].Scheme)
+ assert.Empty(t, reqs[1].Scopes)
+}
+
+func TestSecurity_IsEmpty(t *testing.T) {
+ empty := Security{}
+ assert.True(t, empty.IsEmpty())
+
+ notEmpty := NewSecurity("jwt")
+ assert.False(t, notEmpty.IsEmpty())
+}
+
+func TestSecurity_ToMap(t *testing.T) {
+ sec := NewSecurity("oauth2", "read").And("jwt")
+
+ m := sec.ToMap()
+ assert.Equal(t, []string{"read"}, m["oauth2"])
+ assert.Empty(t, m["jwt"])
+}
+
+// --- OAuthFlows.OpenAPI ---
+
+func TestOAuthFlows_OpenAPI(t *testing.T) {
+ flows := &OAuthFlows{
+ Implicit: &OAuthFlow{
+ AuthorizationURL: "https://example.com/auth",
+ Scopes: map[string]string{},
+ },
+ }
+
+ openapi := flows.OpenAPI()
+
+ _, hasImplicit := openapi["implicit"]
+ assert.True(t, hasImplicit)
+}
+
+func TestOAuthFlows_OpenAPI_AllFlows(t *testing.T) {
+ flows := &OAuthFlows{
+ Implicit: &OAuthFlow{Scopes: map[string]string{}},
+ Password: &OAuthFlow{Scopes: map[string]string{}},
+ ClientCredentials: &OAuthFlow{Scopes: map[string]string{}},
+ AuthorizationCode: &OAuthFlow{Scopes: map[string]string{}},
+ }
+
+ openapi := flows.OpenAPI()
+
+ assert.Contains(t, openapi, "implicit")
+ assert.Contains(t, openapi, "password")
+ assert.Contains(t, openapi, "clientCredentials")
+ assert.Contains(t, openapi, "authorizationCode")
+}
+
+// --- Validator Interface ---
+
+type mockValidator struct {
+ claims any
+ err error
+}
+
+func (m *mockValidator) Validate(ctx context.Context, r *http.Request) (any, error) {
+ return m.claims, m.err
+}
+
+func TestValidatorFunc(t *testing.T) {
+ called := false
+ expectedClaims := map[string]string{"user": "test"}
+
+ vf := ValidatorFunc(func(ctx context.Context, r *http.Request) (any, error) {
+ called = true
+ return expectedClaims, nil
+ })
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ claims, err := vf.Validate(context.Background(), req)
+
+ assert.True(t, called)
+ assert.NoError(t, err)
+ assert.Equal(t, expectedClaims, claims)
+}
+
+// --- Security Registry ---
+
+func TestSecurityRegistry_MustRegister(t *testing.T) {
+ reg := NewSecurityRegistry()
+ scheme := HTTPBearerJWT()
+ validator := &mockValidator{claims: "test"}
+
+ reg.MustRegister("jwt", scheme, validator)
+
+ assert.Equal(t, scheme, reg.GetScheme("jwt"))
+ assert.Equal(t, validator, reg.GetValidator("jwt"))
+}
+
+func TestSecurityRegistry_MustRegister_PanicOnDuplicate(t *testing.T) {
+ reg := NewSecurityRegistry()
+ scheme := HTTPBearerJWT()
+ validator := &mockValidator{}
+
+ reg.MustRegister("jwt", scheme, validator)
+
+ assert.Panics(t, func() {
+ reg.MustRegister("jwt", scheme, validator)
+ })
+}
+
+func TestSecurityRegistry_MustRegister_PanicOnNilValidator(t *testing.T) {
+ reg := NewSecurityRegistry()
+ scheme := HTTPBearerJWT()
+
+ assert.Panics(t, func() {
+ reg.MustRegister("jwt", scheme, nil)
+ })
+}
+
+func TestSecurityRegistry_MustRegister_PanicOnNilScheme(t *testing.T) {
+ reg := NewSecurityRegistry()
+ validator := &mockValidator{}
+
+ assert.Panics(t, func() {
+ reg.MustRegister("jwt", nil, validator)
+ })
+}
+
+func TestSecurityRegistry_Register(t *testing.T) {
+ reg := NewSecurityRegistry()
+ scheme := HTTPBearerJWT()
+ validator := &mockValidator{}
+
+ err := reg.Register("jwt", scheme, validator)
+ assert.NoError(t, err)
+
+ err = reg.Register("jwt", scheme, validator)
+ assert.Error(t, err)
+}
+
+func TestSecurityRegistry_Schemes(t *testing.T) {
+ reg := NewSecurityRegistry()
+ scheme1 := HTTPBearerJWT()
+ scheme2 := APIKeyHeader("X-API-Key")
+
+ reg.MustRegister("jwt", scheme1, &mockValidator{})
+ reg.MustRegister("apikey", scheme2, &mockValidator{})
+
+ schemes := reg.Schemes()
+
+ assert.Len(t, schemes, 2)
+ assert.Equal(t, scheme1, schemes["jwt"])
+ assert.Equal(t, scheme2, schemes["apikey"])
+}
+
+func TestSecurityRegistry_GetScheme_NotFound(t *testing.T) {
+ reg := NewSecurityRegistry()
+ assert.Nil(t, reg.GetScheme("nonexistent"))
+}
+
+func TestSecurityRegistry_GetValidator_NotFound(t *testing.T) {
+ reg := NewSecurityRegistry()
+ assert.Nil(t, reg.GetValidator("nonexistent"))
+}
+
+func TestSecurityRegistry_ValidateSecurityRequirements(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{})
+ reg.MustRegister("apikey", APIKeyHeader("X-Key"), &mockValidator{})
+
+ // All schemes registered
+ err := reg.ValidateSecurityRequirements([]Security{
+ NewSecurity("jwt"),
+ NewSecurity("apikey"),
+ })
+ assert.NoError(t, err)
+
+ // Missing scheme
+ err = reg.ValidateSecurityRequirements([]Security{
+ NewSecurity("jwt"),
+ NewSecurity("missing"),
+ })
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), "missing")
+}
+
+// --- Authentication Middleware ---
+
+func TestMiddleware_NoSecurityRequirements(t *testing.T) {
+ reg := NewSecurityRegistry()
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware(nil, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusOK, rec.Code)
+}
+
+func TestMiddleware_EmptySecurityAllowsAccess(t *testing.T) {
+ reg := NewSecurityRegistry()
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ // Empty Security{} means explicitly optional auth
+ middleware := reg.Middleware([]Security{{}}, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusOK, rec.Code)
+}
+
+func TestMiddleware_SuccessfulAuth(t *testing.T) {
+ reg := NewSecurityRegistry()
+ expectedClaims := map[string]string{"userID": "123"}
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{claims: expectedClaims})
+
+ var capturedAuthResult *AuthResult
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ capturedAuthResult = GetAuthResult(r.Context())
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{NewSecurity("jwt")}, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusOK, rec.Code)
+ require.NotNil(t, capturedAuthResult)
+ require.Len(t, capturedAuthResult.Schemes, 1)
+ assert.Equal(t, "jwt", capturedAuthResult.Schemes[0])
+ assert.Equal(t, expectedClaims, capturedAuthResult.GetClaims())
+ assert.Equal(t, expectedClaims, capturedAuthResult.Claims["jwt"])
+}
+
+func TestMiddleware_FailedAuth_DefaultHandler(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{err: ErrSkipToNextAuth})
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{NewSecurity("jwt")}, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusUnauthorized, rec.Code)
+}
+
+func TestMiddleware_FailedAuth_CustomHandler(t *testing.T) {
+ reg := NewSecurityRegistry()
+ customErr := errors.New("invalid token")
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{err: customErr})
+
+ var capturedErr error
+
+ errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
+ capturedErr = err
+ w.WriteHeader(http.StatusForbidden)
+ }
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{NewSecurity("jwt")}, errorHandler)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusForbidden, rec.Code)
+ assert.Equal(t, customErr, capturedErr)
+}
+
+func TestMiddleware_ORRelationship_FirstSucceeds(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{claims: "jwt-claims"})
+ reg.MustRegister("apikey", APIKeyHeader("X-Key"), &mockValidator{claims: "apikey-claims"})
+
+ var capturedAuthResult *AuthResult
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ capturedAuthResult = GetAuthResult(r.Context())
+ w.WriteHeader(http.StatusOK)
+ })
+
+ // OR relationship: jwt OR apikey
+ middleware := reg.Middleware([]Security{
+ NewSecurity("jwt"),
+ NewSecurity("apikey"),
+ }, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusOK, rec.Code)
+ require.NotNil(t, capturedAuthResult)
+ require.Len(t, capturedAuthResult.Schemes, 1)
+ assert.Equal(t, "jwt", capturedAuthResult.Schemes[0]) // First one succeeds
+}
+
+func TestMiddleware_ORRelationship_FallbackToSecond(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{err: ErrSkipToNextAuth})
+ reg.MustRegister("apikey", APIKeyHeader("X-Key"), &mockValidator{claims: "apikey-claims"})
+
+ var capturedAuthResult *AuthResult
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ capturedAuthResult = GetAuthResult(r.Context())
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{
+ NewSecurity("jwt"),
+ NewSecurity("apikey"),
+ }, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusOK, rec.Code)
+ require.NotNil(t, capturedAuthResult)
+ require.Len(t, capturedAuthResult.Schemes, 1)
+ assert.Equal(t, "apikey", capturedAuthResult.Schemes[0]) // Falls back to second
+}
+
+func TestMiddleware_ORRelationship_AllFail(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{err: ErrSkipToNextAuth})
+ reg.MustRegister("apikey", APIKeyHeader("X-Key"), &mockValidator{err: ErrSkipToNextAuth})
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{
+ NewSecurity("jwt"),
+ NewSecurity("apikey"),
+ }, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusUnauthorized, rec.Code)
+}
+
+func TestMiddleware_HardError_StopsTrying(t *testing.T) {
+ reg := NewSecurityRegistry()
+ hardErr := errors.New("token expired") // Not ErrSkipToNextAuth
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{err: hardErr})
+ reg.MustRegister("apikey", APIKeyHeader("X-Key"), &mockValidator{claims: "should-not-reach"})
+
+ var capturedErr error
+
+ errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
+ capturedErr = err
+ w.WriteHeader(http.StatusUnauthorized)
+ }
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{
+ NewSecurity("jwt"),
+ NewSecurity("apikey"),
+ }, errorHandler)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusUnauthorized, rec.Code)
+ assert.Equal(t, hardErr, capturedErr) // Hard error, didn't try apikey
+}
+
+func TestMiddleware_ANDRelationship(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{claims: "jwt-claims"})
+ reg.MustRegister("mfa", APIKeyHeader("X-MFA"), &mockValidator{claims: "mfa-claims"})
+
+ var capturedAuthResult *AuthResult
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ capturedAuthResult = GetAuthResult(r.Context())
+ w.WriteHeader(http.StatusOK)
+ })
+
+ // AND relationship: jwt AND mfa (both must pass)
+ middleware := reg.Middleware([]Security{
+ NewSecurity("jwt").And("mfa"),
+ }, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusOK, rec.Code)
+ require.NotNil(t, capturedAuthResult)
+ // Both schemes should be in the list (in order)
+ require.Len(t, capturedAuthResult.Schemes, 2)
+ assert.Equal(t, "jwt", capturedAuthResult.Schemes[0])
+ assert.Equal(t, "mfa", capturedAuthResult.Schemes[1])
+ // Both claims should be accumulated
+ assert.Equal(t, "jwt-claims", capturedAuthResult.Claims["jwt"])
+ assert.Equal(t, "mfa-claims", capturedAuthResult.Claims["mfa"])
+ // GetClaims returns first scheme's claims
+ assert.Equal(t, "jwt-claims", capturedAuthResult.GetClaims())
+ // GetClaimsByScheme returns specific scheme's claims
+ assert.Equal(t, "mfa-claims", capturedAuthResult.GetClaimsByScheme("mfa"))
+}
+
+func TestMiddleware_ANDRelationship_OneFails(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{claims: "jwt-claims"})
+ reg.MustRegister("mfa", APIKeyHeader("X-MFA"), &mockValidator{err: ErrSkipToNextAuth})
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{
+ NewSecurity("jwt").And("mfa"),
+ }, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusUnauthorized, rec.Code)
+}
+
+func TestMiddleware_UnregisteredScheme(t *testing.T) {
+ reg := NewSecurityRegistry()
+
+ var capturedErr error
+
+ errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
+ capturedErr = err
+ w.WriteHeader(http.StatusInternalServerError)
+ }
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{
+ NewSecurity("unregistered"),
+ }, errorHandler)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusInternalServerError, rec.Code)
+ assert.Contains(t, capturedErr.Error(), "unregistered")
+}
+
+// --- GetAuthResult ---
+
+func TestGetAuthResult_NotSet(t *testing.T) {
+ ctx := context.Background()
+ assert.Nil(t, GetAuthResult(ctx))
+}
+
+func TestGetAuthResult_Set(t *testing.T) {
+ ctx := context.Background()
+ result := &AuthResult{
+ Schemes: []string{"jwt"},
+ Claims: map[string]any{"jwt": "test"},
+ }
+ ctx = setAuthResult(ctx, result)
+
+ retrieved := GetAuthResult(ctx)
+ require.NotNil(t, retrieved)
+ require.Len(t, retrieved.Schemes, 1)
+ assert.Equal(t, "jwt", retrieved.Schemes[0])
+ assert.Equal(t, "test", retrieved.GetClaims())
+}
+
+func TestAuthResult_GetClaims_Nil(t *testing.T) {
+ var result *AuthResult
+ assert.Nil(t, result.GetClaims())
+
+ result = &AuthResult{}
+ assert.Nil(t, result.GetClaims())
+}
+
+func TestAuthResult_GetClaimsByScheme_Nil(t *testing.T) {
+ var result *AuthResult
+ assert.Nil(t, result.GetClaimsByScheme("jwt"))
+
+ result = &AuthResult{}
+ assert.Nil(t, result.GetClaimsByScheme("jwt"))
+}
+
+// --- WWW-Authenticate Header Tests ---
+
+func TestMiddleware_WWWAuthenticate_BearerScheme(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{err: ErrSkipToNextAuth})
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{NewSecurity("jwt")}, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusUnauthorized, rec.Code)
+ assert.Equal(t, "Bearer", rec.Header().Get("WWW-Authenticate"))
+}
+
+func TestMiddleware_WWWAuthenticate_BasicScheme(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("basic", HTTPBasic(), &mockValidator{err: ErrSkipToNextAuth})
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{NewSecurity("basic")}, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusUnauthorized, rec.Code)
+ assert.Equal(t, "Basic", rec.Header().Get("WWW-Authenticate"))
+}
+
+func TestMiddleware_WWWAuthenticate_ApiKeyOnly_NoHeader(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("apikey", APIKeyHeader("X-API-Key"), &mockValidator{err: ErrSkipToNextAuth})
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ middleware := reg.Middleware([]Security{NewSecurity("apikey")}, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusUnauthorized, rec.Code)
+ // apiKey-only routes should NOT have WWW-Authenticate (no standard challenge)
+ assert.Empty(t, rec.Header().Get("WWW-Authenticate"))
+}
+
+func TestMiddleware_WWWAuthenticate_MultipleSchemes(t *testing.T) {
+ reg := NewSecurityRegistry()
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{err: ErrSkipToNextAuth})
+ reg.MustRegister("basic", HTTPBasic(), &mockValidator{err: ErrSkipToNextAuth})
+
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ // OR relationship - either jwt or basic
+ middleware := reg.Middleware([]Security{NewSecurity("jwt"), NewSecurity("basic")}, nil)
+ wrapped := middleware(handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ wrapped.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusUnauthorized, rec.Code)
+ wwwAuth := rec.Header().Get("WWW-Authenticate")
+ assert.Contains(t, wwwAuth, "Bearer")
+ assert.Contains(t, wwwAuth, "Basic")
+}
+
+func TestSecurityRegistry_ConcurrentAccess(t *testing.T) {
+ reg := NewSecurityRegistry()
+
+ // Pre-register one scheme
+ reg.MustRegister("jwt", HTTPBearerJWT(), &mockValidator{claims: map[string]string{"ok": "true"}})
+
+ var wg sync.WaitGroup
+ const goroutines = 10
+ const iterations = 100
+
+ // Concurrent reads via middleware
+ for range goroutines {
+ wg.Go(func() {
+ for range iterations {
+ middleware := reg.Middleware([]Security{NewSecurity("jwt")}, nil)
+ handler := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/", http.NoBody)
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, req)
+ }
+ })
+ }
+
+ wg.Wait()
+ // If we get here without data race, the mutex is working
+}
diff --git a/backend-go/pkg/api/endpoint.go b/backend-go/pkg/api/endpoint.go
new file mode 100644
index 0000000000..0a6d65c60b
--- /dev/null
+++ b/backend-go/pkg/api/endpoint.go
@@ -0,0 +1,123 @@
+package api
+
+import (
+ "net/http"
+)
+
+// Endpoint represents an API endpoint with all its metadata
+type Endpoint struct {
+ // HTTP method (GET, POST, PUT, PATCH, DELETE, etc.)
+ Method string
+
+ // URL pattern (e.g., "/users/{id}")
+ Pattern string
+
+ // Handler function
+ Handler http.HandlerFunc
+
+ // Request body schema (nil for no body)
+ Request SchemaProvider
+
+ // Default response schema (200 status)
+ Response SchemaProvider
+
+ // Response schemas by status code
+ Responses map[int]SchemaProvider
+
+ // Response descriptions by status code (optional, defaults based on status)
+ ResponseDescriptions map[int]string
+
+ // Security requirements (OR relationship - any one suffices)
+ // Use nil or empty for no auth, []Security{{}} for explicitly optional
+ Security []Security
+
+ // OpenAPI tags
+ Tags []string
+
+ // OpenAPI summary (short description)
+ Summary string
+
+ // OpenAPI description (detailed)
+ Description string
+
+ // OpenAPI operation ID
+ OperationID string
+
+ // Mark endpoint as deprecated
+ Deprecated bool
+
+ // Path parameters
+ PathParams map[string]Schema
+
+ // Query parameters
+ QueryParams map[string]Schema
+
+ // Header parameters
+ HeaderParams map[string]Schema
+
+ // Cookie parameters
+ CookieParams map[string]Schema
+
+ // Content type for request body (default: application/json)
+ RequestContentType string
+
+ // Content type for response body (default: application/json)
+ ResponseContentType string
+
+ // External documentation URL
+ ExternalDocsURL string
+
+ // External documentation description
+ ExternalDocsDesc string
+
+ // Callbacks for webhooks (OpenAPI 3.0+)
+ Callbacks map[string]any
+
+ // Server overrides for this endpoint
+ Servers []Server
+
+ // Custom extensions (x-* properties)
+ Extensions map[string]any
+}
+
+// Server represents an OpenAPI server definition
+type Server struct {
+ URL string
+ Description string
+ Variables map[string]ServerVariable
+}
+
+// ServerVariable represents a server URL variable
+type ServerVariable struct {
+ Default string
+ Enum []string
+ Description string
+}
+
+// OpenAPIPath returns the OpenAPI-formatted path (converts {param} format)
+func (e *Endpoint) OpenAPIPath() string {
+ return e.Pattern
+}
+
+// ExtractPathParams extracts parameter names from the pattern.
+// Strips chi regex constraints (e.g., {id:[0-9]+} → id).
+func (e *Endpoint) ExtractPathParams() []string {
+ return ExtractPathParams(e.Pattern)
+}
+
+// RequiredSchemes returns all unique scheme names referenced by this endpoint's security
+func (e *Endpoint) RequiredSchemes() []string {
+ seen := make(map[string]struct{})
+ var schemes []string
+
+ for _, sec := range e.Security {
+ for _, req := range sec.Requirements() {
+ if _, ok := seen[req.Scheme]; !ok {
+ seen[req.Scheme] = struct{}{}
+ schemes = append(schemes, req.Scheme)
+ }
+ }
+ }
+
+ return schemes
+}
diff --git a/backend-go/pkg/api/integration_test.go b/backend-go/pkg/api/integration_test.go
new file mode 100644
index 0000000000..e7d4a10e2e
--- /dev/null
+++ b/backend-go/pkg/api/integration_test.go
@@ -0,0 +1,665 @@
+package api
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// Integration tests verifying that schema definitions produce
+// BOTH correct validation AND correct OpenAPI output (single source of truth).
+
+// --- Simple Request with Validation + OpenAPI ---
+
+type CreateProjectRequest struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ IsPublic bool `json:"isPublic"`
+}
+
+func (r *CreateProjectRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "name": String(&r.Name).Required().MinLength(1).MaxLength(100).Description("Project name"),
+ "description": String(&r.Description).Optional().MaxLength(500).Description("Project description"),
+ "isPublic": Bool(&r.IsPublic).Optional().Default(false).Description("Whether project is public"),
+ }).Title("CreateProjectRequest").Description("Request to create a new project")
+}
+
+func TestIntegration_SimpleRequest_ValidationAndOpenAPI(t *testing.T) {
+ // Test 1: Validation works correctly
+ t.Run("validation_empty_name", func(t *testing.T) {
+ req := &CreateProjectRequest{Name: "", Description: "desc"}
+ errs := req.Schema().Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "name", errs[0].Field)
+ assert.Equal(t, "required", errs[0].Code)
+ })
+
+ t.Run("validation_name_too_long", func(t *testing.T) {
+ req := &CreateProjectRequest{Name: string(make([]byte, 101))}
+ errs := req.Schema().Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "name", errs[0].Field)
+ assert.Equal(t, "max_length", errs[0].Code)
+ })
+
+ t.Run("validation_valid_request", func(t *testing.T) {
+ req := &CreateProjectRequest{Name: "My Project", Description: "A great project"}
+ errs := req.Schema().Validate()
+ assert.Empty(t, errs)
+ })
+
+ // Test 2: Same schema produces correct OpenAPI
+ t.Run("openapi_output", func(t *testing.T) {
+ req := &CreateProjectRequest{}
+ openapi := req.Schema().OpenAPI()
+
+ assert.Equal(t, "object", openapi["type"])
+ assert.Equal(t, "CreateProjectRequest", openapi["title"])
+ assert.Equal(t, "Request to create a new project", openapi["description"])
+
+ props := openapi["properties"].(map[string]any)
+
+ // name property
+ nameProp := props["name"].(map[string]any)
+ assert.Equal(t, "string", nameProp["type"])
+ assert.Equal(t, 1, nameProp["minLength"])
+ assert.Equal(t, 100, nameProp["maxLength"])
+ assert.Equal(t, "Project name", nameProp["description"])
+
+ // description property
+ descProp := props["description"].(map[string]any)
+ assert.Equal(t, "string", descProp["type"])
+ assert.Equal(t, 500, descProp["maxLength"])
+
+ // isPublic property
+ publicProp := props["isPublic"].(map[string]any)
+ assert.Equal(t, "boolean", publicProp["type"])
+ assert.Equal(t, false, publicProp["default"])
+
+ // Required fields
+ required := openapi["required"].([]string)
+ assert.Contains(t, required, "name")
+ assert.NotContains(t, required, "description")
+ assert.NotContains(t, required, "isPublic")
+ })
+}
+
+// --- Nested Object with Validation + OpenAPI ---
+
+type Address struct {
+ Street string `json:"street"`
+ City string `json:"city"`
+ ZipCode string `json:"zipCode"`
+}
+
+func (a *Address) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "street": String(&a.Street).Required().MinLength(1),
+ "city": String(&a.City).Required().MinLength(1),
+ "zipCode": String(&a.ZipCode).Required().Pattern(`^\d{5}$`),
+ })
+}
+
+type CreateUserWithAddressRequest struct {
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Address Address `json:"address"`
+}
+
+func (r *CreateUserWithAddressRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "name": String(&r.Name).Required().MinLength(1),
+ "email": String(&r.Email).Required().Email(),
+ "address": r.Address.Schema().Required(),
+ })
+}
+
+func TestIntegration_NestedObject_ValidationAndOpenAPI(t *testing.T) {
+ t.Run("validation_nested_errors", func(t *testing.T) {
+ req := &CreateUserWithAddressRequest{
+ Name: "John",
+ Email: "invalid-email",
+ Address: Address{
+ Street: "",
+ City: "NYC",
+ ZipCode: "invalid",
+ },
+ }
+ errs := req.Schema().Validate()
+
+ // Should have errors for: email format, street required, zipCode pattern
+ require.GreaterOrEqual(t, len(errs), 2)
+
+ fieldErrors := make(map[string]bool)
+ for _, e := range errs {
+ fieldErrors[e.Field] = true
+ }
+ assert.True(t, fieldErrors["email"] || fieldErrors["address"])
+ })
+
+ t.Run("validation_valid_nested", func(t *testing.T) {
+ req := &CreateUserWithAddressRequest{
+ Name: "John",
+ Email: "[email protected]",
+ Address: Address{
+ Street: "123 Main St",
+ City: "NYC",
+ ZipCode: "10001",
+ },
+ }
+ errs := req.Schema().Validate()
+ assert.Empty(t, errs)
+ })
+
+ t.Run("openapi_nested_structure", func(t *testing.T) {
+ req := &CreateUserWithAddressRequest{}
+ openapi := req.Schema().OpenAPI()
+
+ props := openapi["properties"].(map[string]any)
+ addressProp := props["address"].(map[string]any)
+
+ assert.Equal(t, "object", addressProp["type"])
+
+ addressProps := addressProp["properties"].(map[string]any)
+ assert.Contains(t, addressProps, "street")
+ assert.Contains(t, addressProps, "city")
+ assert.Contains(t, addressProps, "zipCode")
+
+ zipCodeProp := addressProps["zipCode"].(map[string]any)
+ assert.Equal(t, `^\d{5}$`, zipCodeProp["pattern"])
+ })
+}
+
+// --- Union Type with Validation + OpenAPI ---
+
+type Provider interface {
+ Union
+ providerMarker()
+}
+
+type SqlDatabaseProvider struct {
+ Type string `json:"type"`
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Database string `json:"database"`
+ Username string `json:"username"`
+}
+
+func (p *SqlDatabaseProvider) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "type": String(&p.Type).Required(),
+ "host": String(&p.Host).Required().MinLength(1).Description("Database host"),
+ "port": Int(&p.Port).Required().Min(1).Max(65535).Description("Database port"),
+ "database": String(&p.Database).Required().MinLength(1).Description("Database name"),
+ "username": String(&p.Username).Required().MinLength(1).Description("Database username"),
+ }).Title("SqlDatabaseProvider")
+}
+
+func (p *SqlDatabaseProvider) unionMarker() {}
+func (p *SqlDatabaseProvider) providerMarker() {}
+
+type AwsIamProvider struct {
+ Type string `json:"type"`
+ Region string `json:"region"`
+ AccountID string `json:"accountId"`
+ RoleArn string `json:"roleArn"`
+}
+
+func (p *AwsIamProvider) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "type": String(&p.Type).Required(),
+ "region": String(&p.Region).Required().Pattern(`^[a-z]{2}-[a-z]+-\d$`).Description("AWS region"),
+ "accountId": String(&p.AccountID).Required().Pattern(`^\d{12}$`).Description("AWS account ID"),
+ "roleArn": String(&p.RoleArn).Required().MinLength(1).Description("IAM role ARN"),
+ }).Title("AwsIamProvider")
+}
+
+func (p *AwsIamProvider) unionMarker() {}
+func (p *AwsIamProvider) providerMarker() {}
+
+type RedisProvider struct {
+ Type string `json:"type"`
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Password string `json:"password"`
+}
+
+func (p *RedisProvider) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "type": String(&p.Type).Required(),
+ "host": String(&p.Host).Required().MinLength(1),
+ "port": Int(&p.Port).Required().Min(1).Max(65535),
+ "password": String(&p.Password).Optional().WriteOnly(),
+ }).Title("RedisProvider")
+}
+
+func (p *RedisProvider) unionMarker() {}
+func (p *RedisProvider) providerMarker() {}
+
+var ProviderParser = UnionDef[Provider]{
+ Discriminator: "type",
+ Variants: map[string]func() Provider{
+ "sql-database": func() Provider { return &SqlDatabaseProvider{} },
+ "aws-iam": func() Provider { return &AwsIamProvider{} },
+ "redis": func() Provider { return &RedisProvider{} },
+ },
+}
+
+type CreateDynamicSecretRequest struct {
+ Name string `json:"name"`
+ Provider Provider `json:"-"`
+}
+
+func (r *CreateDynamicSecretRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "name": String(&r.Name).Required().MinLength(1).MaxLength(64).Pattern(`^[a-zA-Z0-9_-]+$`),
+ "provider": UnionField(&r.Provider, ProviderParser).Required().Description("Provider configuration"),
+ }).Title("CreateDynamicSecretRequest")
+}
+
+func (r *CreateDynamicSecretRequest) UnmarshalJSON(data []byte) error {
+ type Plain CreateDynamicSecretRequest
+ if err := json.Unmarshal(data, (*Plain)(r)); err != nil {
+ return err
+ }
+ return ParseUnions(data,
+ U("provider", &r.Provider, ProviderParser),
+ )
+}
+
+func TestIntegration_Union_ValidationAndOpenAPI(t *testing.T) {
+ t.Run("parse_sql_database_provider", func(t *testing.T) {
+ data := []byte(`{
+ "name": "my-secret",
+ "provider": {
+ "type": "sql-database",
+ "host": "localhost",
+ "port": 5432,
+ "database": "mydb",
+ "username": "admin"
+ }
+ }`)
+
+ var req CreateDynamicSecretRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Equal(t, "my-secret", req.Name)
+ require.NotNil(t, req.Provider)
+
+ sqlProvider, ok := req.Provider.(*SqlDatabaseProvider)
+ require.True(t, ok)
+ assert.Equal(t, "localhost", sqlProvider.Host)
+ assert.Equal(t, 5432, sqlProvider.Port)
+ assert.Equal(t, "mydb", sqlProvider.Database)
+ })
+
+ t.Run("parse_aws_iam_provider", func(t *testing.T) {
+ data := []byte(`{
+ "name": "aws-secret",
+ "provider": {
+ "type": "aws-iam",
+ "region": "us-east-1",
+ "accountId": "123456789012",
+ "roleArn": "arn:aws:iam::123456789012:role/MyRole"
+ }
+ }`)
+
+ var req CreateDynamicSecretRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ awsProvider, ok := req.Provider.(*AwsIamProvider)
+ require.True(t, ok)
+ assert.Equal(t, "us-east-1", awsProvider.Region)
+ assert.Equal(t, "123456789012", awsProvider.AccountID)
+ })
+
+ t.Run("parse_unknown_provider_type", func(t *testing.T) {
+ data := []byte(`{
+ "name": "test",
+ "provider": {
+ "type": "unknown-type"
+ }
+ }`)
+
+ var req CreateDynamicSecretRequest
+ err := json.Unmarshal(data, &req)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "unknown type value")
+ })
+
+ t.Run("validation_provider_required", func(t *testing.T) {
+ req := &CreateDynamicSecretRequest{
+ Name: "test",
+ Provider: nil,
+ }
+ errs := req.Schema().Validate()
+ require.NotEmpty(t, errs)
+
+ hasProviderError := false
+ for _, e := range errs {
+ if e.Field == "provider" {
+ hasProviderError = true
+ break
+ }
+ }
+ assert.True(t, hasProviderError)
+ })
+
+ t.Run("validation_provider_fields", func(t *testing.T) {
+ req := &CreateDynamicSecretRequest{
+ Name: "test",
+ Provider: &SqlDatabaseProvider{
+ Type: "sql-database",
+ Host: "", // Invalid - required
+ Port: 99999, // Invalid - max 65535
+ Database: "db",
+ Username: "user",
+ },
+ }
+ errs := req.Schema().Validate()
+ require.NotEmpty(t, errs)
+ })
+
+ t.Run("validation_valid_request", func(t *testing.T) {
+ req := &CreateDynamicSecretRequest{
+ Name: "my-secret",
+ Provider: &SqlDatabaseProvider{
+ Type: "sql-database",
+ Host: "localhost",
+ Port: 5432,
+ Database: "mydb",
+ Username: "admin",
+ },
+ }
+ errs := req.Schema().Validate()
+ assert.Empty(t, errs)
+ })
+
+ t.Run("openapi_union_structure", func(t *testing.T) {
+ req := &CreateDynamicSecretRequest{}
+ openapi := req.Schema().OpenAPI()
+
+ props := openapi["properties"].(map[string]any)
+ providerProp := props["provider"].(map[string]any)
+
+ // Should have oneOf for discriminated union
+ oneOf, ok := providerProp["oneOf"].([]map[string]any)
+ require.True(t, ok)
+ assert.Len(t, oneOf, 3) // 3 providers
+
+ // Should have discriminator
+ disc, ok := providerProp["discriminator"].(map[string]any)
+ require.True(t, ok)
+ assert.Equal(t, "type", disc["propertyName"])
+ // mapping is omitted for inline schemas
+ _, hasMapping := disc["mapping"]
+ assert.False(t, hasMapping)
+ })
+
+ t.Run("openapi_variant_schemas", func(t *testing.T) {
+ // Verify each variant produces correct OpenAPI
+ sqlProvider := &SqlDatabaseProvider{}
+ sqlOpenAPI := sqlProvider.Schema().OpenAPI()
+
+ assert.Equal(t, "SqlDatabaseProvider", sqlOpenAPI["title"])
+ props := sqlOpenAPI["properties"].(map[string]any)
+
+ hostProp := props["host"].(map[string]any)
+ assert.Equal(t, "string", hostProp["type"])
+ assert.Equal(t, "Database host", hostProp["description"])
+
+ portProp := props["port"].(map[string]any)
+ assert.Equal(t, "integer", portProp["type"])
+ assert.Equal(t, int64(1), portProp["minimum"])
+ assert.Equal(t, int64(65535), portProp["maximum"])
+ })
+}
+
+// --- Array with Item Validation + OpenAPI ---
+
+type BatchCreateRequest struct {
+ Items []CreateProjectRequest `json:"items"`
+}
+
+func (r *BatchCreateRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "items": Array((&CreateProjectRequest{}).Schema()).
+ Required().
+ MinItems(1).
+ MaxItems(100).
+ Description("List of projects to create"),
+ })
+}
+
+func TestIntegration_Array_ValidationAndOpenAPI(t *testing.T) {
+ t.Run("openapi_array_with_items", func(t *testing.T) {
+ req := &BatchCreateRequest{}
+ openapi := req.Schema().OpenAPI()
+
+ props := openapi["properties"].(map[string]any)
+ itemsProp := props["items"].(map[string]any)
+
+ assert.Equal(t, "array", itemsProp["type"])
+ assert.Equal(t, 1, itemsProp["minItems"])
+ assert.Equal(t, 100, itemsProp["maxItems"])
+ assert.Equal(t, "List of projects to create", itemsProp["description"])
+
+ // Items schema should be the project schema
+ items := itemsProp["items"].(map[string]any)
+ assert.Equal(t, "object", items["type"])
+ assert.Equal(t, "CreateProjectRequest", items["title"])
+ })
+}
+
+// --- Full OpenAPI Spec Generation with Endpoints ---
+
+func TestIntegration_FullOpenAPISpec(t *testing.T) {
+ config := &OpenAPIConfig{
+ OpenAPIVersion: "3.0.3",
+ Info: OpenAPIInfo{
+ Title: "Dynamic Secrets API",
+ Version: "1.0.0",
+ Description: "API for managing dynamic secrets",
+ },
+ SecuritySchemes: map[string]*SecurityScheme{
+ "bearerAuth": HTTPBearerJWT().WithDescription("JWT authentication"),
+ "apiKey": APIKeyHeader("X-API-Key").WithDescription("API key authentication"),
+ },
+ Tags: []OpenAPITag{
+ {Name: "Dynamic Secrets", Description: "Manage dynamic secrets"},
+ },
+ }
+
+ spec := NewOpenAPISpec(config)
+
+ // Add schemas
+ spec.AddSchema("CreateDynamicSecretRequest", &CreateDynamicSecretRequest{})
+ spec.AddSchema("SqlDatabaseProvider", &SqlDatabaseProvider{})
+ spec.AddSchema("AwsIamProvider", &AwsIamProvider{})
+ spec.AddSchema("RedisProvider", &RedisProvider{})
+
+ // Add endpoints
+ spec.AddEndpoints([]Endpoint{
+ {
+ Method: "POST",
+ Pattern: "/api/v1/dynamic-secrets",
+ Summary: "Create dynamic secret",
+ Description: "Creates a new dynamic secret with the specified provider",
+ Tags: []string{"Dynamic Secrets"},
+ Request: &CreateDynamicSecretRequest{},
+ Responses: map[int]SchemaProvider{
+ 201: &CreateDynamicSecretRequest{}, // Simplified for test
+ },
+ Security: []Security{
+ NewSecurity("bearerAuth"),
+ NewSecurity("apiKey"),
+ },
+ QueryParams: map[string]Schema{
+ "projectId": String(new(string)).Required().UUID().Description("Project ID"),
+ },
+ },
+ })
+
+ result := spec.Generate()
+
+ // Verify structure
+ assert.Equal(t, "3.0.3", result["openapi"])
+
+ info := result["info"].(map[string]any)
+ assert.Equal(t, "Dynamic Secrets API", info["title"])
+
+ // Verify security schemes
+ components := result["components"].(map[string]any)
+ secSchemes := components["securitySchemes"].(map[string]any)
+ assert.Contains(t, secSchemes, "bearerAuth")
+ assert.Contains(t, secSchemes, "apiKey")
+
+ // Verify schemas
+ schemas := components["schemas"].(map[string]any)
+ assert.Contains(t, schemas, "CreateDynamicSecretRequest")
+ assert.Contains(t, schemas, "SqlDatabaseProvider")
+
+ // Verify paths
+ paths := result["paths"].(map[string]any)
+ dsPath := paths["/api/v1/dynamic-secrets"].(map[string]any)
+ postOp := dsPath["post"].(map[string]any)
+
+ assert.Equal(t, "Create dynamic secret", postOp["summary"])
+ assert.Equal(t, []string{"Dynamic Secrets"}, postOp["tags"])
+
+ // Verify request body references the schema
+ reqBody := postOp["requestBody"].(map[string]any)
+ assert.NotNil(t, reqBody["content"])
+
+ // Verify security
+ security := postOp["security"].([]map[string][]string)
+ assert.Len(t, security, 2)
+
+ // Verify query params
+ params := postOp["parameters"].([]map[string]any)
+ require.Len(t, params, 1)
+ assert.Equal(t, "projectId", params[0]["name"])
+ assert.Equal(t, "query", params[0]["in"])
+ assert.Equal(t, true, params[0]["required"])
+
+ // Verify it serializes to valid JSON
+ jsonBytes, err := spec.JSONIndent("", " ")
+ 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)
+}
+
+// --- UUID Field Integration ---
+
+type ResourceRequest struct {
+ ID uuid.UUID `json:"id"`
+ ParentID uuid.UUID `json:"parentId"`
+ Name string `json:"name"`
+}
+
+func (r *ResourceRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "id": UUID(&r.ID).Required().Description("Resource ID"),
+ "parentId": UUID(&r.ParentID).Optional().Nullable().Description("Parent resource ID"),
+ "name": String(&r.Name).Required().MinLength(1),
+ })
+}
+
+func TestIntegration_UUID_ValidationAndOpenAPI(t *testing.T) {
+ t.Run("validation_uuid_required", func(t *testing.T) {
+ req := &ResourceRequest{
+ ID: uuid.Nil,
+ Name: "test",
+ }
+ errs := req.Schema().Validate()
+ require.NotEmpty(t, errs)
+ assert.Equal(t, "id", errs[0].Field)
+ })
+
+ t.Run("validation_uuid_optional_nil", func(t *testing.T) {
+ req := &ResourceRequest{
+ ID: uuid.New(),
+ ParentID: uuid.Nil, // Optional, should be fine
+ Name: "test",
+ }
+ errs := req.Schema().Validate()
+ assert.Empty(t, errs)
+ })
+
+ t.Run("openapi_uuid_format", func(t *testing.T) {
+ req := &ResourceRequest{}
+ openapi := req.Schema().OpenAPI()
+
+ props := openapi["properties"].(map[string]any)
+
+ idProp := props["id"].(map[string]any)
+ assert.Equal(t, "string", idProp["type"])
+ assert.Equal(t, "uuid", idProp["format"])
+
+ parentProp := props["parentId"].(map[string]any)
+ assert.Equal(t, "string", parentProp["type"])
+ assert.Equal(t, "uuid", parentProp["format"])
+ assert.Equal(t, true, parentProp["nullable"])
+ })
+}
+
+// --- Enum Validation + OpenAPI ---
+
+type StatusRequest struct {
+ Status string `json:"status"`
+ Level int `json:"level"`
+}
+
+func (r *StatusRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "status": String(&r.Status).Required().Enum("active", "inactive", "pending").Description("Resource status"),
+ "level": Int(&r.Level).Required().Enum(1, 2, 3, 4, 5).Description("Priority level"),
+ })
+}
+
+func TestIntegration_Enum_ValidationAndOpenAPI(t *testing.T) {
+ t.Run("validation_string_enum_invalid", func(t *testing.T) {
+ req := &StatusRequest{Status: "unknown", Level: 1}
+ errs := req.Schema().Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "status", errs[0].Field)
+ assert.Equal(t, "enum", errs[0].Code)
+ })
+
+ t.Run("validation_int_enum_invalid", func(t *testing.T) {
+ req := &StatusRequest{Status: "active", Level: 10}
+ errs := req.Schema().Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "level", errs[0].Field)
+ assert.Equal(t, "enum", errs[0].Code)
+ })
+
+ t.Run("validation_enum_valid", func(t *testing.T) {
+ req := &StatusRequest{Status: "active", Level: 3}
+ errs := req.Schema().Validate()
+ assert.Empty(t, errs)
+ })
+
+ t.Run("openapi_enum_values", func(t *testing.T) {
+ req := &StatusRequest{}
+ openapi := req.Schema().OpenAPI()
+
+ props := openapi["properties"].(map[string]any)
+
+ statusProp := props["status"].(map[string]any)
+ assert.Equal(t, []string{"active", "inactive", "pending"}, statusProp["enum"])
+
+ levelProp := props["level"].(map[string]any)
+ assert.Equal(t, []int64{1, 2, 3, 4, 5}, levelProp["enum"])
+ })
+}
diff --git a/backend-go/pkg/api/ispresent_test.go b/backend-go/pkg/api/ispresent_test.go
new file mode 100644
index 0000000000..42d2a5beb6
--- /dev/null
+++ b/backend-go/pkg/api/ispresent_test.go
@@ -0,0 +1,347 @@
+package api
+
+import (
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "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())
+ })
+}
+
+// --- IsPresent Tests for Composite Types ---
+
+func TestObjectSchema_IsPresent(t *testing.T) {
+ t.Run("no properties present", func(t *testing.T) {
+ name := ""
+ schema := Object(map[string]Schema{
+ "name": String(&name),
+ })
+ // name is empty string = not present for string
+ assert.False(t, schema.IsPresent())
+ })
+
+ t.Run("one property present", func(t *testing.T) {
+ name := "John"
+ schema := Object(map[string]Schema{
+ "name": String(&name),
+ })
+ assert.True(t, schema.IsPresent())
+ })
+
+ t.Run("multiple properties some 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
+ })
+}
+
+func TestArraySchema_IsPresent(t *testing.T) {
+ t.Run("no isPresentFn", func(t *testing.T) {
+ schema := Array(String(new(string)))
+ assert.False(t, schema.IsPresent()) // Default is false
+ })
+
+ t.Run("with isPresentFn returning false", func(t *testing.T) {
+ items := []string{}
+ 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) {
+ items := []string{"a", "b"}
+ 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) {
+ schema := Map(String(new(string)))
+ assert.False(t, schema.IsPresent())
+ })
+
+ t.Run("with isPresentFn returning true", func(t *testing.T) {
+ m := map[string]string{"key": "value"}
+ 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("one schema present", func(t *testing.T) {
+ strVal := "hello"
+ schema := OneOfSchemas(
+ String(&strVal),
+ )
+ assert.True(t, schema.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("one schema present", func(t *testing.T) {
+ strVal := "hello"
+ schema := AnyOf(
+ String(&strVal),
+ )
+ assert.True(t, schema.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("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())
+ })
+}
diff --git a/backend-go/pkg/api/nullable.go b/backend-go/pkg/api/nullable.go
new file mode 100644
index 0000000000..b3c16dde3c
--- /dev/null
+++ b/backend-go/pkg/api/nullable.go
@@ -0,0 +1,204 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+)
+
+// JsonNullable distinguishes between absent, null, and present JSON values.
+// Use this for optional request bodies or fields where you need to tell apart:
+// - Field not present in JSON (Present=false, Null=false)
+// - Field explicitly set to null (Present=true, Null=true)
+// - Field has a value (Present=true, Null=false, Value populated)
+type JsonNullable[T any] struct {
+ Value T
+ Present bool // true if the key existed in JSON (even if value was null)
+ Null bool // true if the value was explicitly "null"
+}
+
+// IsSet returns true if a non-null value was provided
+func (j JsonNullable[T]) IsSet() bool {
+ return j.Present && !j.Null
+}
+
+// UnmarshalJSON implements json.Unmarshaler
+func (j *JsonNullable[T]) UnmarshalJSON(data []byte) error {
+ j.Present = true
+ if bytes.Equal(data, []byte("null")) {
+ j.Null = true
+ return nil
+ }
+ return json.Unmarshal(data, &j.Value)
+}
+
+// MarshalJSON implements json.Marshaler
+func (j JsonNullable[T]) MarshalJSON() ([]byte, error) {
+ if !j.Present || j.Null {
+ return []byte("null"), nil
+ }
+ return json.Marshal(j.Value)
+}
+
+// Ptr returns a pointer to the value if set, nil otherwise.
+// Useful for passing to schema validators.
+func (j *JsonNullable[T]) Ptr() *T {
+ if j.IsSet() {
+ return &j.Value
+ }
+ return nil
+}
+
+// Set creates a JsonNullable with a value
+func Set[T any](value T) JsonNullable[T] {
+ return JsonNullable[T]{
+ Value: value,
+ Present: true,
+ Null: false,
+ }
+}
+
+// Null creates a JsonNullable that is explicitly null
+func Null[T any]() JsonNullable[T] {
+ return JsonNullable[T]{
+ Present: true,
+ Null: true,
+ }
+}
+
+// Absent creates a JsonNullable that represents an absent field
+func Absent[T any]() JsonNullable[T] {
+ return JsonNullable[T]{
+ Present: false,
+ Null: false,
+ }
+}
+
+// NullableSchema wraps any schema to handle the absent/null/present tri-state.
+// Use this for PATCH semantics where you need to distinguish:
+// - Field absent → don't update
+// - Field null → clear/unset the value
+// - Field present → update with value
+//
+// Usage:
+//
+// type UpdateRequest struct {
+// Name JsonNullable[string] `json:"name"`
+// }
+//
+// func (r *UpdateRequest) Schema() *ObjectSchema {
+// return Object(map[string]Schema{
+// "name": Nullable(&r.Name, String(&r.Name.Value).MinLength(1)).Optional(),
+// })
+// }
+type NullableSchema[T any] struct {
+ ptr *JsonNullable[T]
+ inner Schema
+ required bool
+ title string
+ description string
+ deprecated bool
+ example any
+}
+
+// Nullable creates a NullableSchema wrapping an inner schema.
+// The inner schema should bind to the JsonNullable's Value field.
+func Nullable[T any](ptr *JsonNullable[T], inner Schema) *NullableSchema[T] {
+ return &NullableSchema[T]{
+ ptr: ptr,
+ inner: inner,
+ }
+}
+
+func (s *NullableSchema[T]) Required() *NullableSchema[T] {
+ s.required = true
+ return s
+}
+
+func (s *NullableSchema[T]) Optional() *NullableSchema[T] {
+ s.required = false
+ return s
+}
+
+func (s *NullableSchema[T]) Title(val string) *NullableSchema[T] {
+ s.title = val
+ return s
+}
+
+func (s *NullableSchema[T]) Description(val string) *NullableSchema[T] {
+ s.description = val
+ return s
+}
+
+func (s *NullableSchema[T]) Deprecated() *NullableSchema[T] {
+ s.deprecated = true
+ return s
+}
+
+func (s *NullableSchema[T]) Example(val any) *NullableSchema[T] {
+ s.example = val
+ return s
+}
+
+func (s *NullableSchema[T]) IsRequired() bool {
+ return s.required
+}
+
+func (s *NullableSchema[T]) GetSource() ParamSource {
+ return s.inner.GetSource()
+}
+
+// IsPresent returns true if a non-null value was provided
+func (s *NullableSchema[T]) IsPresent() bool {
+ return s.ptr != nil && s.ptr.Present && !s.ptr.Null
+}
+
+// IsNull returns true if the field was explicitly set to null
+func (s *NullableSchema[T]) IsNull() bool {
+ return s.ptr != nil && s.ptr.Present && s.ptr.Null
+}
+
+// IsAbsent returns true if the field was not present in the JSON
+func (s *NullableSchema[T]) IsAbsent() bool {
+ return s.ptr == nil || !s.ptr.Present
+}
+
+func (s *NullableSchema[T]) Validate() []ValidationError {
+ if s.ptr == nil || !s.ptr.Present {
+ // Field absent
+ if s.required {
+ return []ValidationError{{Code: "required", Message: "is required"}}
+ }
+ return nil
+ }
+
+ if s.ptr.Null {
+ // Explicitly null
+ if s.required {
+ return []ValidationError{{Code: "required", Message: "cannot be null"}}
+ }
+ return nil
+ }
+
+ // Present with value - validate inner schema (skip its required check)
+ return s.inner.Validate()
+}
+
+func (s *NullableSchema[T]) OpenAPI() map[string]any {
+ schema := s.inner.OpenAPI()
+ schema["nullable"] = true
+
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+
+ return schema
+}
diff --git a/backend-go/pkg/api/nullable_test.go b/backend-go/pkg/api/nullable_test.go
new file mode 100644
index 0000000000..6464133f1f
--- /dev/null
+++ b/backend-go/pkg/api/nullable_test.go
@@ -0,0 +1,284 @@
+package api
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestJsonNullable_UnmarshalJSON_Value(t *testing.T) {
+ type Request struct {
+ Name JsonNullable[string] `json:"name"`
+ }
+
+ data := []byte(`{"name": "John"}`)
+ var req Request
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.True(t, req.Name.Present)
+ assert.False(t, req.Name.Null)
+ assert.Equal(t, "John", req.Name.Value)
+ assert.True(t, req.Name.IsSet())
+}
+
+func TestJsonNullable_UnmarshalJSON_Null(t *testing.T) {
+ type Request struct {
+ Name JsonNullable[string] `json:"name"`
+ }
+
+ data := []byte(`{"name": null}`)
+ var req Request
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.True(t, req.Name.Present)
+ assert.True(t, req.Name.Null)
+ assert.Equal(t, "", req.Name.Value) // zero value
+ assert.False(t, req.Name.IsSet())
+}
+
+func TestJsonNullable_UnmarshalJSON_Absent(t *testing.T) {
+ type Request struct {
+ Name JsonNullable[string] `json:"name"`
+ }
+
+ data := []byte(`{}`)
+ var req Request
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.False(t, req.Name.Present)
+ assert.False(t, req.Name.Null)
+ assert.Equal(t, "", req.Name.Value)
+ assert.False(t, req.Name.IsSet())
+}
+
+func TestJsonNullable_UnmarshalJSON_ComplexType(t *testing.T) {
+ type Address struct {
+ Street string `json:"street"`
+ City string `json:"city"`
+ }
+
+ type Request struct {
+ Address JsonNullable[Address] `json:"address"`
+ }
+
+ data := []byte(`{"address": {"street": "123 Main St", "city": "NYC"}}`)
+ var req Request
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.True(t, req.Address.Present)
+ assert.False(t, req.Address.Null)
+ assert.Equal(t, "123 Main St", req.Address.Value.Street)
+ assert.Equal(t, "NYC", req.Address.Value.City)
+}
+
+func TestJsonNullable_MarshalJSON_Value(t *testing.T) {
+ val := Set("hello")
+ data, err := json.Marshal(val)
+ require.NoError(t, err)
+ assert.Equal(t, `"hello"`, string(data))
+}
+
+func TestJsonNullable_MarshalJSON_Null(t *testing.T) {
+ val := Null[string]()
+ data, err := json.Marshal(val)
+ require.NoError(t, err)
+ assert.Equal(t, `null`, string(data))
+}
+
+func TestJsonNullable_MarshalJSON_Absent(t *testing.T) {
+ val := Absent[string]()
+ data, err := json.Marshal(val)
+ require.NoError(t, err)
+ assert.Equal(t, `null`, string(data)) // absent marshals as null
+}
+
+func TestJsonNullable_Ptr_Set(t *testing.T) {
+ val := Set(42)
+ ptr := val.Ptr()
+ require.NotNil(t, ptr)
+ assert.Equal(t, 42, *ptr)
+}
+
+func TestJsonNullable_Ptr_Null(t *testing.T) {
+ val := Null[int]()
+ ptr := val.Ptr()
+ assert.Nil(t, ptr)
+}
+
+func TestJsonNullable_Ptr_Absent(t *testing.T) {
+ val := Absent[int]()
+ ptr := val.Ptr()
+ assert.Nil(t, ptr)
+}
+
+func TestJsonNullable_WithSchema(t *testing.T) {
+ type Request struct {
+ Count JsonNullable[int] `json:"count"`
+ }
+
+ t.Run("value provided", func(t *testing.T) {
+ data := []byte(`{"count": 0}`) // 0 is a valid value
+ var req Request
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ // Use Ptr() to get pointer for schema
+ schema := Int(req.Count.Ptr()).Required()
+ errs := schema.Validate()
+ assert.Empty(t, errs) // 0 is valid
+ })
+
+ t.Run("value absent", func(t *testing.T) {
+ data := []byte(`{}`)
+ var req Request
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ // Ptr() returns nil for absent
+ schema := Int(req.Count.Ptr()).Required()
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+ })
+
+ t.Run("value null", func(t *testing.T) {
+ data := []byte(`{"count": null}`)
+ var req Request
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ // Ptr() returns nil for null
+ schema := Int(req.Count.Ptr()).Required()
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+ })
+}
+
+func TestNullableSchema_TriState(t *testing.T) {
+ type UpdateRequest struct {
+ Name JsonNullable[string] `json:"name"`
+ }
+
+ t.Run("value present - valid", func(t *testing.T) {
+ data := []byte(`{"name": "John"}`)
+ var req UpdateRequest
+ require.NoError(t, json.Unmarshal(data, &req))
+
+ schema := Nullable(&req.Name, String(&req.Name.Value).MinLength(1)).Required()
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+ assert.True(t, schema.IsPresent())
+ assert.False(t, schema.IsNull())
+ assert.False(t, schema.IsAbsent())
+ })
+
+ t.Run("value present - invalid pattern", func(t *testing.T) {
+ data := []byte(`{"name": "invalid-email"}`)
+ var req UpdateRequest
+ require.NoError(t, json.Unmarshal(data, &req))
+
+ schema := Nullable(&req.Name, String(&req.Name.Value).Email()).Required()
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "format", errs[0].Code)
+ })
+
+ t.Run("value null - required fails", func(t *testing.T) {
+ data := []byte(`{"name": null}`)
+ var req UpdateRequest
+ require.NoError(t, json.Unmarshal(data, &req))
+
+ schema := Nullable(&req.Name, String(&req.Name.Value)).Required()
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+ assert.Contains(t, errs[0].Message, "null")
+ assert.False(t, schema.IsPresent())
+ assert.True(t, schema.IsNull())
+ })
+
+ t.Run("value null - optional ok", func(t *testing.T) {
+ data := []byte(`{"name": null}`)
+ var req UpdateRequest
+ require.NoError(t, json.Unmarshal(data, &req))
+
+ schema := Nullable(&req.Name, String(&req.Name.Value)).Optional()
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+ assert.True(t, schema.IsNull())
+ })
+
+ t.Run("value absent - required fails", func(t *testing.T) {
+ data := []byte(`{}`)
+ var req UpdateRequest
+ require.NoError(t, json.Unmarshal(data, &req))
+
+ schema := Nullable(&req.Name, String(&req.Name.Value)).Required()
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+ assert.True(t, schema.IsAbsent())
+ })
+
+ t.Run("value absent - optional ok", func(t *testing.T) {
+ data := []byte(`{}`)
+ var req UpdateRequest
+ require.NoError(t, json.Unmarshal(data, &req))
+
+ schema := Nullable(&req.Name, String(&req.Name.Value)).Optional()
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+ assert.True(t, schema.IsAbsent())
+ })
+}
+
+func TestNullableSchema_OpenAPI(t *testing.T) {
+ var name JsonNullable[string]
+ schema := Nullable(&name, String(&name.Value).MinLength(1).MaxLength(100)).
+ Description("User name").
+ Example("John")
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "string", openapi["type"])
+ assert.Equal(t, true, openapi["nullable"])
+ assert.Equal(t, 1, openapi["minLength"])
+ assert.Equal(t, 100, openapi["maxLength"])
+ assert.Equal(t, "User name", openapi["description"])
+ assert.Equal(t, "John", openapi["example"])
+}
+
+func TestNullableSchema_IntType(t *testing.T) {
+ type Request struct {
+ Count JsonNullable[int] `json:"count"`
+ }
+
+ t.Run("zero is valid value", func(t *testing.T) {
+ data := []byte(`{"count": 0}`)
+ var req Request
+ require.NoError(t, json.Unmarshal(data, &req))
+
+ schema := Nullable(&req.Count, Int(&req.Count.Value).Min(0)).Required()
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+ assert.True(t, schema.IsPresent())
+ })
+
+ t.Run("negative fails min", func(t *testing.T) {
+ data := []byte(`{"count": -5}`)
+ var req Request
+ require.NoError(t, json.Unmarshal(data, &req))
+
+ schema := Nullable(&req.Count, Int(&req.Count.Value).Min(0)).Required()
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "minimum", errs[0].Code)
+ })
+}
diff --git a/backend-go/pkg/api/oneof_anyof_test.go b/backend-go/pkg/api/oneof_anyof_test.go
new file mode 100644
index 0000000000..113afc385b
--- /dev/null
+++ b/backend-go/pkg/api/oneof_anyof_test.go
@@ -0,0 +1,388 @@
+package api
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// --- OneOfSchemas Validation Tests ---
+
+func TestOneOfSchemas_Validate_NonePresent_Required(t *testing.T) {
+ strVal := ""
+ var intPtr *int
+
+ schema := OneOfSchemas(
+ String(&strVal),
+ Int(intPtr),
+ ).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "oneOf", errs[0].Code)
+ assert.Contains(t, errs[0].Message, "exactly one")
+}
+
+func TestOneOfSchemas_Validate_NonePresent_Optional(t *testing.T) {
+ strVal := ""
+ var intPtr *int
+
+ schema := OneOfSchemas(
+ String(&strVal),
+ Int(intPtr),
+ ).Optional()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestOneOfSchemas_Validate_OnePresent(t *testing.T) {
+ strVal := "hello"
+ var intPtr *int
+
+ schema := OneOfSchemas(
+ String(&strVal).MinLength(1),
+ Int(intPtr),
+ ).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestOneOfSchemas_Validate_MultiplePresent(t *testing.T) {
+ strVal := "hello"
+ intVal := 42
+
+ schema := OneOfSchemas(
+ String(&strVal),
+ Int(&intVal),
+ ).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "oneOf", errs[0].Code)
+ assert.Contains(t, errs[0].Message, "only one")
+}
+
+func TestOneOfSchemas_Validate_PresentButInvalid(t *testing.T) {
+ strVal := "hi" // Too short for minLength(5)
+
+ schema := OneOfSchemas(
+ String(&strVal).MinLength(5),
+ ).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "min_length", errs[0].Code)
+}
+
+func TestOneOfSchemas_Validate_WithObjects(t *testing.T) {
+ // Simulate: either plaintext OR reference
+ type SecretReference struct {
+ SecretID string
+ Version int
+ }
+
+ plaintext := ""
+ ref := SecretReference{SecretID: "abc-123", Version: 1}
+
+ schema := OneOfSchemas(
+ String(&plaintext).Description("Raw value"),
+ Object(map[string]Schema{
+ "secretId": String(&ref.SecretID).Required(),
+ "version": Int(&ref.Version).Required(),
+ }).Description("Reference"),
+ ).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs) // Object is present (secretId is non-empty)
+}
+
+func TestOneOfSchemas_OpenAPI(t *testing.T) {
+ strVal := ""
+ intVal := 0
+
+ schema := OneOfSchemas(
+ String(&strVal).Description("String option"),
+ Int(&intVal).Description("Int option"),
+ ).Title("FlexValue").Description("Either string or int")
+
+ openapi := schema.OpenAPI()
+
+ oneOf, ok := openapi["oneOf"].([]map[string]any)
+ require.True(t, ok)
+ assert.Len(t, oneOf, 2)
+
+ assert.Equal(t, "FlexValue", openapi["title"])
+ assert.Equal(t, "Either string or int", openapi["description"])
+
+ // Should NOT have discriminator for simple oneOf
+ _, hasDiscriminator := openapi["discriminator"]
+ assert.False(t, hasDiscriminator)
+}
+
+// --- AnyOf Validation Tests ---
+
+func TestAnyOf_Validate_NonePresent_Required(t *testing.T) {
+ email := ""
+ slack := ""
+
+ schema := AnyOf(
+ String(&email),
+ String(&slack),
+ ).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "anyOf", errs[0].Code)
+ assert.Contains(t, errs[0].Message, "at least one")
+}
+
+func TestAnyOf_Validate_NonePresent_Optional(t *testing.T) {
+ email := ""
+ slack := ""
+
+ schema := AnyOf(
+ String(&email),
+ String(&slack),
+ ).Optional()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestAnyOf_Validate_OnePresent(t *testing.T) {
+ email := "[email protected]"
+ slack := ""
+
+ schema := AnyOf(
+ String(&email).Email(),
+ String(&slack),
+ ).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestAnyOf_Validate_MultiplePresent(t *testing.T) {
+ email := "[email protected]"
+ slack := "#channel"
+
+ schema := AnyOf(
+ String(&email).Email(),
+ String(&slack).MinLength(1),
+ ).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs) // Multiple present is OK for anyOf
+}
+
+func TestAnyOf_Validate_MultiplePresent_OneInvalid(t *testing.T) {
+ email := "invalid-email" // Invalid email format
+ slack := "#channel"
+
+ schema := AnyOf(
+ String(&email).Email(),
+ String(&slack).MinLength(1),
+ ).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "format", errs[0].Code) // Email validation failed
+}
+
+func TestAnyOf_Validate_WithObjects(t *testing.T) {
+ type EmailConfig struct {
+ To string
+ Subject string
+ }
+ type SlackConfig struct {
+ Channel string
+ }
+
+ email := EmailConfig{To: "[email protected]", Subject: "Alert"}
+ slack := SlackConfig{} // Empty
+
+ schema := AnyOf(
+ Object(map[string]Schema{
+ "to": String(&email.To).Required().Email(),
+ "subject": String(&email.Subject).Required(),
+ }),
+ Object(map[string]Schema{
+ "channel": String(&slack.Channel).Required(),
+ }),
+ ).Required()
+
+ errs := schema.Validate()
+ // Email object is present (to is non-empty)
+ // Slack object validation will have errors but email is valid
+ // Actually, let me think about this...
+ // Both objects are validated if present
+ // Email is present (to is non-empty)
+ // Slack is NOT present (channel is empty)
+ // So only email is validated
+ assert.Empty(t, errs)
+}
+
+func TestAnyOf_OpenAPI(t *testing.T) {
+ email := ""
+ slack := ""
+
+ schema := AnyOf(
+ String(&email).Description("Email config"),
+ String(&slack).Description("Slack config"),
+ ).Title("NotificationConfig").Description("At least one channel")
+
+ openapi := schema.OpenAPI()
+
+ anyOf, ok := openapi["anyOf"].([]map[string]any)
+ require.True(t, ok)
+ assert.Len(t, anyOf, 2)
+
+ assert.Equal(t, "NotificationConfig", openapi["title"])
+ assert.Equal(t, "At least one channel", openapi["description"])
+}
+
+// --- AllOf Validation Tests (unchanged, but verify) ---
+
+func TestAllOf_Validate_AllValid(t *testing.T) {
+ name := "John"
+ age := 25
+
+ schema := AllOf(
+ Object(map[string]Schema{
+ "name": String(&name).Required().MinLength(1),
+ }),
+ Object(map[string]Schema{
+ "age": Int(&age).Required().Min(0),
+ }),
+ )
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestAllOf_Validate_OneInvalid(t *testing.T) {
+ name := "" // Invalid - required
+ age := 25
+
+ schema := AllOf(
+ Object(map[string]Schema{
+ "name": String(&name).Required().MinLength(1),
+ }),
+ Object(map[string]Schema{
+ "age": Int(&age).Required().Min(0),
+ }),
+ )
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "name", errs[0].Field)
+}
+
+func TestAllOf_Validate_MultipleInvalid(t *testing.T) {
+ name := "" // Invalid
+ age := -10 // Invalid - min 0
+
+ schema := AllOf(
+ Object(map[string]Schema{
+ "name": String(&name).Required().MinLength(1),
+ }),
+ Object(map[string]Schema{
+ "age": Int(&age).Required().Min(0),
+ }),
+ )
+
+ errs := schema.Validate()
+ assert.Len(t, errs, 2)
+}
+
+// --- Real-world Use Case Tests ---
+
+func TestOneOf_SecretValue_UsCase(t *testing.T) {
+ // Use case: Secret value can be plaintext OR reference, not both
+ type SecretValue struct {
+ Plaintext *string
+ Reference *struct {
+ SecretID string
+ Version int
+ }
+ }
+
+ t.Run("plaintext provided", func(t *testing.T) {
+ plaintext := "my-secret-value"
+ sv := SecretValue{Plaintext: &plaintext}
+
+ schema := OneOfSchemas(
+ String(sv.Plaintext),
+ // Reference would be nil, so its object properties wouldn't be present
+ ).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+ })
+
+ t.Run("neither provided", func(t *testing.T) {
+ var plaintext string
+ schema := OneOfSchemas(
+ String(&plaintext), // Empty string
+ ).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "oneOf", errs[0].Code)
+ })
+}
+
+func TestAnyOf_NotificationConfig_UseCase(t *testing.T) {
+ // Use case: Notification config - at least one channel required
+ type NotificationConfig struct {
+ Email *string
+ Slack *string
+ Webhook *string
+ }
+
+ t.Run("one channel configured", func(t *testing.T) {
+ email := "[email protected]"
+ nc := NotificationConfig{Email: &email}
+
+ schema := AnyOf(
+ String(nc.Email).Email(),
+ String(nc.Slack),
+ String(nc.Webhook),
+ ).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+ })
+
+ t.Run("multiple channels configured", func(t *testing.T) {
+ email := "[email protected]"
+ slack := "#alerts"
+ nc := NotificationConfig{Email: &email, Slack: &slack}
+
+ schema := AnyOf(
+ String(nc.Email).Email(),
+ String(nc.Slack).MinLength(1),
+ String(nc.Webhook),
+ ).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs) // Both present and valid is OK
+ })
+
+ t.Run("no channels configured", func(t *testing.T) {
+ nc := NotificationConfig{}
+
+ schema := AnyOf(
+ String(nc.Email),
+ String(nc.Slack),
+ String(nc.Webhook),
+ ).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "anyOf", errs[0].Code)
+ })
+}
diff --git a/backend-go/pkg/api/openapi.go b/backend-go/pkg/api/openapi.go
new file mode 100644
index 0000000000..4f23d3ff4a
--- /dev/null
+++ b/backend-go/pkg/api/openapi.go
@@ -0,0 +1,634 @@
+package api
+
+import (
+ "encoding/json"
+ "maps"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// OpenAPIInfo contains API metadata
+type OpenAPIInfo struct {
+ Title string
+ Description string
+ Version string
+ TermsOfService string
+ Contact *OpenAPIContact
+ License *OpenAPILicense
+}
+
+// OpenAPIContact contains contact information
+type OpenAPIContact struct {
+ Name string
+ URL string
+ Email string
+}
+
+// OpenAPILicense contains license information
+type OpenAPILicense struct {
+ Name string
+ URL string
+}
+
+// OpenAPIExternalDocs contains external documentation info
+type OpenAPIExternalDocs struct {
+ Description string
+ URL string
+}
+
+// OpenAPITag defines an API tag with description
+type OpenAPITag struct {
+ Name string
+ Description string
+ ExternalDocs *OpenAPIExternalDocs
+}
+
+// OpenAPIConfig contains all configuration for OpenAPI generation
+type OpenAPIConfig struct {
+ // OpenAPI version (default: "3.0.3")
+ OpenAPIVersion string
+
+ // API info
+ Info OpenAPIInfo
+
+ // Server definitions
+ Servers []Server
+
+ // Security schemes available in this API
+ SecuritySchemes map[string]*SecurityScheme
+
+ // Global security requirements (applied to all endpoints unless overridden)
+ Security []Security
+
+ // Tag definitions with descriptions
+ Tags []OpenAPITag
+
+ // External documentation
+ ExternalDocs *OpenAPIExternalDocs
+
+ // Custom extensions (x-* properties) at root level
+ Extensions map[string]any
+}
+
+// OpenAPISpec represents an OpenAPI 3.x specification
+type OpenAPISpec struct {
+ config *OpenAPIConfig
+ endpoints []Endpoint
+ schemas map[string]SchemaProvider
+}
+
+// NewOpenAPISpec creates a new OpenAPI spec generator
+func NewOpenAPISpec(config *OpenAPIConfig) *OpenAPISpec {
+ if config.OpenAPIVersion == "" {
+ config.OpenAPIVersion = "3.0.3"
+ }
+ return &OpenAPISpec{
+ config: config,
+ schemas: make(map[string]SchemaProvider),
+ }
+}
+
+// AddEndpoints adds endpoints to the spec
+func (s *OpenAPISpec) AddEndpoints(endpoints []Endpoint) {
+ s.endpoints = append(s.endpoints, endpoints...)
+}
+
+// AddSchema adds a named schema (for $ref usage)
+func (s *OpenAPISpec) AddSchema(name string, schema SchemaProvider) {
+ s.schemas[name] = schema
+}
+
+// Generate generates the OpenAPI spec as a map
+func (s *OpenAPISpec) Generate() map[string]any {
+ spec := map[string]any{
+ "openapi": s.config.OpenAPIVersion,
+ "info": s.generateInfo(),
+ }
+
+ if len(s.config.Servers) > 0 {
+ spec["servers"] = s.generateServers()
+ }
+
+ spec["paths"] = s.generatePaths()
+ spec["components"] = s.generateComponents()
+
+ if len(s.config.Security) > 0 {
+ spec["security"] = s.generateSecurityRequirements(s.config.Security)
+ }
+
+ if len(s.config.Tags) > 0 {
+ spec["tags"] = s.generateTags()
+ }
+
+ if s.config.ExternalDocs != nil {
+ spec["externalDocs"] = map[string]any{
+ "description": s.config.ExternalDocs.Description,
+ "url": s.config.ExternalDocs.URL,
+ }
+ }
+
+ maps.Copy(spec, s.config.Extensions)
+
+ return spec
+}
+
+// JSON generates the OpenAPI spec as JSON
+func (s *OpenAPISpec) JSON() ([]byte, error) {
+ return json.Marshal(s.Generate())
+}
+
+// JSONIndent generates the OpenAPI spec as indented JSON
+func (s *OpenAPISpec) JSONIndent(prefix, indent string) ([]byte, error) {
+ return json.MarshalIndent(s.Generate(), prefix, indent)
+}
+
+func (s *OpenAPISpec) generateInfo() map[string]any {
+ info := map[string]any{
+ "title": s.config.Info.Title,
+ "version": s.config.Info.Version,
+ }
+
+ if s.config.Info.Description != "" {
+ info["description"] = s.config.Info.Description
+ }
+ if s.config.Info.TermsOfService != "" {
+ info["termsOfService"] = s.config.Info.TermsOfService
+ }
+ if s.config.Info.Contact != nil {
+ contact := make(map[string]any)
+ if s.config.Info.Contact.Name != "" {
+ contact["name"] = s.config.Info.Contact.Name
+ }
+ if s.config.Info.Contact.URL != "" {
+ contact["url"] = s.config.Info.Contact.URL
+ }
+ if s.config.Info.Contact.Email != "" {
+ contact["email"] = s.config.Info.Contact.Email
+ }
+ info["contact"] = contact
+ }
+ if s.config.Info.License != nil {
+ license := map[string]any{
+ "name": s.config.Info.License.Name,
+ }
+ if s.config.Info.License.URL != "" {
+ license["url"] = s.config.Info.License.URL
+ }
+ info["license"] = license
+ }
+
+ return info
+}
+
+func (s *OpenAPISpec) generateServers() []map[string]any {
+ servers := make([]map[string]any, 0, len(s.config.Servers))
+
+ for _, srv := range s.config.Servers {
+ server := map[string]any{
+ "url": srv.URL,
+ }
+ if srv.Description != "" {
+ server["description"] = srv.Description
+ }
+ if len(srv.Variables) > 0 {
+ vars := make(map[string]any)
+ for name, v := range srv.Variables {
+ varDef := map[string]any{
+ "default": v.Default,
+ }
+ if len(v.Enum) > 0 {
+ varDef["enum"] = v.Enum
+ }
+ if v.Description != "" {
+ varDef["description"] = v.Description
+ }
+ vars[name] = varDef
+ }
+ server["variables"] = vars
+ }
+ servers = append(servers, server)
+ }
+
+ return servers
+}
+
+func (s *OpenAPISpec) generatePaths() map[string]any {
+ paths := make(map[string]any)
+
+ for i := range s.endpoints {
+ ep := &s.endpoints[i]
+ path := ep.OpenAPIPath()
+ if paths[path] == nil {
+ paths[path] = make(map[string]any)
+ }
+
+ pathItem, _ := paths[path].(map[string]any)
+ method := strings.ToLower(ep.Method)
+ pathItem[method] = s.generateOperation(ep)
+ }
+
+ return paths
+}
+
+func (s *OpenAPISpec) generateOperation(ep *Endpoint) map[string]any {
+ op := make(map[string]any)
+
+ if ep.OperationID != "" {
+ op["operationId"] = ep.OperationID
+ }
+ if ep.Summary != "" {
+ op["summary"] = ep.Summary
+ }
+ if ep.Description != "" {
+ op["description"] = ep.Description
+ }
+ if len(ep.Tags) > 0 {
+ op["tags"] = ep.Tags
+ }
+ if ep.Deprecated {
+ op["deprecated"] = true
+ }
+
+ params := s.generateParameters(ep)
+ if len(params) > 0 {
+ op["parameters"] = params
+ }
+
+ if ep.Request != nil {
+ if reqBody := s.generateRequestBody(ep); reqBody != nil {
+ op["requestBody"] = reqBody
+ }
+ }
+
+ op["responses"] = s.generateResponses(ep)
+
+ if len(ep.Security) > 0 {
+ op["security"] = s.generateSecurityRequirements(ep.Security)
+ }
+
+ if ep.ExternalDocsURL != "" {
+ extDocs := map[string]any{"url": ep.ExternalDocsURL}
+ if ep.ExternalDocsDesc != "" {
+ extDocs["description"] = ep.ExternalDocsDesc
+ }
+ op["externalDocs"] = extDocs
+ }
+
+ if len(ep.Callbacks) > 0 {
+ op["callbacks"] = ep.Callbacks
+ }
+
+ if len(ep.Servers) > 0 {
+ servers := make([]map[string]any, 0, len(ep.Servers))
+ for _, srv := range ep.Servers {
+ server := map[string]any{"url": srv.URL}
+ if srv.Description != "" {
+ server["description"] = srv.Description
+ }
+ servers = append(servers, server)
+ }
+ op["servers"] = servers
+ }
+
+ maps.Copy(op, ep.Extensions)
+
+ return op
+}
+
+func (s *OpenAPISpec) generateParameters(ep *Endpoint) []map[string]any {
+ var params []map[string]any
+
+ // If request schema exists and has source-annotated fields, use BuildOpenAPIParameters
+ if ep.Request != nil {
+ schema := ep.Request.Schema()
+ hasSourcedFields := false
+ for _, fieldSchema := range schema.properties {
+ if fieldSchema.GetSource() != SourceBody {
+ hasSourcedFields = true
+ break
+ }
+ }
+ if hasSourcedFields {
+ return BuildOpenAPIParameters(schema)
+ }
+ }
+
+ // Legacy path: use explicit PathParams/QueryParams/HeaderParams/CookieParams maps
+ pathParamNames := ep.ExtractPathParams()
+ for _, name := range pathParamNames {
+ param := map[string]any{
+ "name": name,
+ "in": "path",
+ "required": true,
+ }
+ if schema, ok := ep.PathParams[name]; ok {
+ openAPI := schema.OpenAPI()
+ param["schema"] = openAPI
+ // Lift description/deprecated/example to parameter level
+ if desc, ok := openAPI["description"].(string); ok && desc != "" {
+ param["description"] = desc
+ }
+ if deprecated, ok := openAPI["deprecated"].(bool); ok && deprecated {
+ param["deprecated"] = true
+ }
+ if example, ok := openAPI["example"]; ok {
+ param["example"] = example
+ }
+ } else {
+ param["schema"] = map[string]any{"type": "string"}
+ }
+ params = append(params, param)
+ }
+
+ if len(ep.QueryParams) > 0 {
+ names := make([]string, 0, len(ep.QueryParams))
+ for name := range ep.QueryParams {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+
+ for _, name := range names {
+ schema := ep.QueryParams[name]
+ openAPI := schema.OpenAPI()
+ param := map[string]any{
+ "name": name,
+ "in": "query",
+ "schema": openAPI,
+ }
+ if schema.IsRequired() {
+ param["required"] = true
+ }
+ // Lift description/deprecated/example
+ if desc, ok := openAPI["description"].(string); ok && desc != "" {
+ param["description"] = desc
+ }
+ if deprecated, ok := openAPI["deprecated"].(bool); ok && deprecated {
+ param["deprecated"] = true
+ }
+ if example, ok := openAPI["example"]; ok {
+ param["example"] = example
+ }
+ // Add style/explode for array params
+ if _, isArray := schema.(*ArraySchema); isArray {
+ param["style"] = "form"
+ param["explode"] = true
+ }
+ params = append(params, param)
+ }
+ }
+
+ if len(ep.HeaderParams) > 0 {
+ names := make([]string, 0, len(ep.HeaderParams))
+ for name := range ep.HeaderParams {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+
+ for _, name := range names {
+ schema := ep.HeaderParams[name]
+ openAPI := schema.OpenAPI()
+ param := map[string]any{
+ "name": name,
+ "in": "header",
+ "schema": openAPI,
+ }
+ if schema.IsRequired() {
+ param["required"] = true
+ }
+ if desc, ok := openAPI["description"].(string); ok && desc != "" {
+ param["description"] = desc
+ }
+ if deprecated, ok := openAPI["deprecated"].(bool); ok && deprecated {
+ param["deprecated"] = true
+ }
+ if example, ok := openAPI["example"]; ok {
+ param["example"] = example
+ }
+ params = append(params, param)
+ }
+ }
+
+ if len(ep.CookieParams) > 0 {
+ names := make([]string, 0, len(ep.CookieParams))
+ for name := range ep.CookieParams {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+
+ for _, name := range names {
+ schema := ep.CookieParams[name]
+ openAPI := schema.OpenAPI()
+ param := map[string]any{
+ "name": name,
+ "in": "cookie",
+ "schema": openAPI,
+ }
+ if schema.IsRequired() {
+ param["required"] = true
+ }
+ if desc, ok := openAPI["description"].(string); ok && desc != "" {
+ param["description"] = desc
+ }
+ if deprecated, ok := openAPI["deprecated"].(bool); ok && deprecated {
+ param["deprecated"] = true
+ }
+ if example, ok := openAPI["example"]; ok {
+ param["example"] = example
+ }
+ params = append(params, param)
+ }
+ }
+
+ return params
+}
+
+func (s *OpenAPISpec) generateRequestBody(ep *Endpoint) map[string]any {
+ contentType := ep.RequestContentType
+ if contentType == "" {
+ contentType = "application/json"
+ }
+
+ schema := ep.Request.Schema()
+
+ // Check if schema has source-annotated fields - if so, only include body fields
+ hasSourcedFields := false
+ for _, fieldSchema := range schema.properties {
+ if fieldSchema.GetSource() != SourceBody {
+ hasSourcedFields = true
+ break
+ }
+ }
+
+ var bodySchema map[string]any
+ var hasRequired bool
+
+ if hasSourcedFields {
+ // Use SplitSchemaBySource to get only body fields
+ bodySchemaSplit, _ := SplitSchemaBySource(schema)
+ if bodySchemaSplit == nil {
+ return nil // No body fields
+ }
+ bodySchema = bodySchemaSplit.OpenAPI()
+ for _, fieldSchema := range bodySchemaSplit.properties {
+ if fieldSchema.IsRequired() {
+ hasRequired = true
+ break
+ }
+ }
+ } else {
+ // Legacy: use entire schema as body
+ bodySchema = schema.OpenAPI()
+ for _, fieldSchema := range schema.properties {
+ if fieldSchema.IsRequired() {
+ hasRequired = true
+ break
+ }
+ }
+ }
+
+ return map[string]any{
+ "required": hasRequired,
+ "content": map[string]any{
+ contentType: map[string]any{
+ "schema": bodySchema,
+ },
+ },
+ }
+}
+
+func (s *OpenAPISpec) generateResponses(ep *Endpoint) map[string]any {
+ responses := make(map[string]any)
+
+ switch {
+ case len(ep.Responses) > 0:
+ for code, schema := range ep.Responses {
+ desc := ep.ResponseDescriptions[code]
+ if desc == "" {
+ desc = defaultResponseDescription(code)
+ }
+ responses[statusCodeToString(code)] = s.generateResponseObject(schema, ep.ResponseContentType, desc)
+ }
+ case ep.Response != nil:
+ desc := ep.ResponseDescriptions[200]
+ if desc == "" {
+ desc = "Successful response"
+ }
+ responses["200"] = s.generateResponseObject(ep.Response, ep.ResponseContentType, desc)
+ default:
+ responses["200"] = map[string]any{
+ "description": "Successful response",
+ }
+ }
+
+ return responses
+}
+
+func (s *OpenAPISpec) generateResponseObject(schema SchemaProvider, contentType, description string) map[string]any {
+ if contentType == "" {
+ contentType = "application/json"
+ }
+
+ return map[string]any{
+ "description": description,
+ "content": map[string]any{
+ contentType: map[string]any{
+ "schema": schema.Schema().OpenAPI(),
+ },
+ },
+ }
+}
+
+func defaultResponseDescription(code int) string {
+ switch code {
+ case 200:
+ return "Successful response"
+ case 201:
+ return "Created"
+ case 204:
+ return "No content"
+ case 400:
+ return "Bad request"
+ case 401:
+ return "Unauthorized"
+ case 403:
+ return "Forbidden"
+ case 404:
+ return "Not found"
+ case 409:
+ return "Conflict"
+ case 422:
+ return "Validation error"
+ case 500:
+ return "Internal server error"
+ default:
+ if code >= 200 && code < 300 {
+ return "Successful response"
+ }
+ if code >= 400 && code < 500 {
+ return "Client error"
+ }
+ if code >= 500 {
+ return "Server error"
+ }
+ return "Response"
+ }
+}
+
+func (s *OpenAPISpec) generateComponents() map[string]any {
+ components := make(map[string]any)
+
+ if len(s.config.SecuritySchemes) > 0 {
+ secSchemes := make(map[string]any)
+ for name, scheme := range s.config.SecuritySchemes {
+ secSchemes[name] = scheme.OpenAPI()
+ }
+ components["securitySchemes"] = secSchemes
+ }
+
+ if len(s.schemas) > 0 {
+ schemas := make(map[string]any)
+ for name, provider := range s.schemas {
+ schemas[name] = provider.Schema().OpenAPI()
+ }
+ components["schemas"] = schemas
+ }
+
+ return components
+}
+
+func (s *OpenAPISpec) generateSecurityRequirements(security []Security) []map[string][]string {
+ result := make([]map[string][]string, 0, len(security))
+
+ for _, sec := range security {
+ result = append(result, sec.ToMap())
+ }
+
+ return result
+}
+
+func (s *OpenAPISpec) generateTags() []map[string]any {
+ tags := make([]map[string]any, 0, len(s.config.Tags))
+
+ for _, tag := range s.config.Tags {
+ t := map[string]any{
+ "name": tag.Name,
+ }
+ if tag.Description != "" {
+ t["description"] = tag.Description
+ }
+ if tag.ExternalDocs != nil {
+ t["externalDocs"] = map[string]any{
+ "description": tag.ExternalDocs.Description,
+ "url": tag.ExternalDocs.URL,
+ }
+ }
+ tags = append(tags, t)
+ }
+
+ return tags
+}
+
+func statusCodeToString(code int) string {
+ return strconv.Itoa(code)
+}
diff --git a/backend-go/pkg/api/openapi_test.go b/backend-go/pkg/api/openapi_test.go
new file mode 100644
index 0000000000..ae61b10d04
--- /dev/null
+++ b/backend-go/pkg/api/openapi_test.go
@@ -0,0 +1,1044 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// --- Test Types ---
+
+type CreateUserRequest struct {
+ Name string
+ Email string
+}
+
+func (r *CreateUserRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "name": String(&r.Name).Required().MinLength(1).MaxLength(100),
+ "email": String(&r.Email).Required().Email(),
+ }).Title("CreateUserRequest")
+}
+
+type UserResponse struct {
+ ID string
+ Name string
+ Email string
+}
+
+func (r *UserResponse) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "id": String(&r.ID).Required().UUID(),
+ "name": String(&r.Name).Required(),
+ "email": String(&r.Email).Required().Email(),
+ }).Title("UserResponse")
+}
+
+type ErrorResponse struct {
+ Code string
+ Message string
+}
+
+func (r *ErrorResponse) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "code": String(&r.Code).Required(),
+ "message": String(&r.Message).Required(),
+ }).Title("ErrorResponse")
+}
+
+// --- OpenAPISpec Tests ---
+
+func TestNewOpenAPISpec(t *testing.T) {
+ config := &OpenAPIConfig{
+ Info: OpenAPIInfo{
+ Title: "Test API",
+ Version: "1.0.0",
+ },
+ }
+
+ spec := NewOpenAPISpec(config)
+ require.NotNil(t, spec)
+
+ // Should default to 3.0.3
+ assert.Equal(t, "3.0.3", spec.config.OpenAPIVersion)
+}
+
+func TestOpenAPISpec_CustomVersion(t *testing.T) {
+ config := &OpenAPIConfig{
+ OpenAPIVersion: "3.1.0",
+ Info: OpenAPIInfo{
+ Title: "Test API",
+ Version: "1.0.0",
+ },
+ }
+
+ spec := NewOpenAPISpec(config)
+ assert.Equal(t, "3.1.0", spec.config.OpenAPIVersion)
+}
+
+func TestOpenAPISpec_Generate_Basic(t *testing.T) {
+ config := &OpenAPIConfig{
+ Info: OpenAPIInfo{
+ Title: "Test API",
+ Description: "A 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",
+ },
+ },
+ }
+
+ 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",
+ },
+ },
+ }
+
+ 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"])
+}
+
+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"])
+}
+
+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 {
+ for _, p := range params {
+ if p["name"] == name {
+ return p
+ }
+ }
+ return nil
+}
+
+func TestOpenAPISpec_Generate_QueryParameters(t *testing.T) {
+ config := &OpenAPIConfig{
+ Info: OpenAPIInfo{
+ Title: "Test API",
+ Version: "1.0.0",
+ },
+ }
+
+ 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),
+ },
+ },
+ })
+
+ 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
+}
+
+func TestOpenAPISpec_Generate_HeaderParameters(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,
+ HeaderParams: map[string]Schema{
+ "X-Request-ID": String(new(string)).Required().UUID(),
+ },
+ },
+ })
+
+ 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(),
+ },
+ },
+ })
+
+ 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",
+ },
+ }
+
+ 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",
+ },
+ }
+
+ spec := NewOpenAPISpec(config)
+ spec.AddEndpoints([]Endpoint{
+ {
+ Method: http.MethodPost,
+ Pattern: "/users",
+ Handler: nil,
+ Request: &CreateUserRequest{},
+ Responses: map[int]SchemaProvider{
+ 201: &UserResponse{},
+ 400: &ErrorResponse{},
+ },
+ },
+ })
+
+ 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",
+ },
+ Tags: []OpenAPITag{
+ {
+ Name: "Users",
+ Description: "User management endpoints",
+ },
+ {
+ Name: "Admin",
+ Description: "Admin endpoints",
+ ExternalDocs: &OpenAPIExternalDocs{
+ Description: "Admin guide",
+ URL: "https://example.com/admin",
+ },
+ },
+ },
+ }
+
+ 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",
+ },
+ ExternalDocs: &OpenAPIExternalDocs{
+ Description: "Full documentation",
+ URL: "https://docs.example.com",
+ },
+ }
+
+ 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",
+ },
+ }
+
+ 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",
+ },
+ }
+
+ spec := NewOpenAPISpec(config)
+ spec.AddEndpoints([]Endpoint{
+ {
+ 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",
+ },
+ }
+
+ 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",
+ },
+ }
+
+ spec := NewOpenAPISpec(config)
+ spec.AddEndpoints([]Endpoint{
+ {
+ Method: http.MethodGet,
+ Pattern: "/special",
+ Handler: nil,
+ Servers: []Server{
+ {
+ URL: "https://special.example.com",
+ Description: "Special server",
+ },
+ },
+ },
+ })
+
+ 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",
+ },
+ },
+ },
+ },
+ },
+ })
+
+ 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",
+ },
+ }
+
+ spec := NewOpenAPISpec(config)
+ spec.AddEndpoints([]Endpoint{
+ {
+ Method: http.MethodGet,
+ Pattern: "/custom",
+ Handler: nil,
+ Extensions: map[string]any{
+ "x-custom-field": "custom-value",
+ },
+ },
+ })
+
+ result := spec.Generate()
+
+ paths := result["paths"].(map[string]any)
+ path := paths["/custom"].(map[string]any)
+ getOp := path["get"].(map[string]any)
+
+ assert.Equal(t, "custom-value", getOp["x-custom-field"])
+}
+
+func TestOpenAPISpec_AddSchema(t *testing.T) {
+ config := &OpenAPIConfig{
+ Info: OpenAPIInfo{
+ Title: "Test API",
+ Version: "1.0.0",
+ },
+ }
+
+ spec := NewOpenAPISpec(config)
+ spec.AddSchema("User", &UserResponse{})
+ spec.AddSchema("Error", &ErrorResponse{})
+
+ result := spec.Generate()
+
+ components := result["components"].(map[string]any)
+ schemas := components["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"])
+}
+
+func TestOpenAPISpec_JSONIndent(t *testing.T) {
+ config := &OpenAPIConfig{
+ Info: OpenAPIInfo{
+ Title: "Test API",
+ Version: "1.0.0",
+ },
+ }
+
+ spec := NewOpenAPISpec(config)
+ jsonBytes, err := spec.JSONIndent("", " ")
+
+ require.NoError(t, err)
+ assert.Contains(t, string(jsonBytes), "\n")
+ assert.Contains(t, string(jsonBytes), " ")
+}
+
+// --- Endpoint Helper Tests ---
+
+func TestEndpoint_ExtractPathParams(t *testing.T) {
+ ep := Endpoint{
+ Pattern: "/users/{userId}/posts/{postId}",
+ }
+
+ params := ep.ExtractPathParams()
+
+ assert.Equal(t, []string{"userId", "postId"}, params)
+}
+
+func TestEndpoint_ExtractPathParams_NoParams(t *testing.T) {
+ ep := Endpoint{
+ Pattern: "/users",
+ }
+
+ params := ep.ExtractPathParams()
+
+ assert.Empty(t, params)
+}
+
+func TestEndpoint_OpenAPIPath(t *testing.T) {
+ ep := Endpoint{
+ Pattern: "/users/{id}",
+ }
+
+ path := ep.OpenAPIPath()
+
+ assert.Equal(t, "/users/{id}", path)
+}
+
+func TestEndpoint_RequiredSchemes(t *testing.T) {
+ ep := Endpoint{
+ Security: []Security{
+ NewSecurity("jwt"),
+ NewSecurity("api_key"),
+ },
+ }
+
+ 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
+ },
+ }
+
+ 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) }
+
+func TestOpenAPI_ResponseDescriptions(t *testing.T) {
+ spec := NewOpenAPISpec(&OpenAPIConfig{
+ Info: OpenAPIInfo{Title: "Test", Version: "1.0"},
+ })
+
+ spec.AddEndpoints([]Endpoint{{
+ Method: http.MethodGet,
+ Pattern: "/test",
+ Response: &emptyResponse{},
+ Responses: map[int]SchemaProvider{
+ 200: &emptyResponse{},
+ 400: &emptyResponse{},
+ 404: &emptyResponse{},
+ 500: &emptyResponse{},
+ },
+ ResponseDescriptions: map[int]string{
+ 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)
+
+ // 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"])
+
+ resp500 := responses["500"].(map[string]any)
+ assert.Equal(t, "Internal server error", resp500["description"])
+}
+
+func TestOpenAPI_DefaultResponseDescriptions(t *testing.T) {
+ tests := []struct {
+ code int
+ expected string
+ }{
+ {200, "Successful response"},
+ {201, "Created"},
+ {204, "No content"},
+ {400, "Bad request"},
+ {401, "Unauthorized"},
+ {403, "Forbidden"},
+ {404, "Not found"},
+ {409, "Conflict"},
+ {422, "Validation error"},
+ {500, "Internal server error"},
+ {299, "Successful response"}, // 2xx fallback
+ {499, "Client error"}, // 4xx fallback
+ {599, "Server error"}, // 5xx fallback
+ }
+
+ for _, tt := range tests {
+ t.Run(statusCodeToString(tt.code), func(t *testing.T) {
+ result := defaultResponseDescription(tt.code)
+ assert.Equal(t, tt.expected, result)
+ })
+ }
+}
+
+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"}},
+ }
+
+ 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)
+ })
+ }
+}
diff --git a/backend-go/pkg/api/request.go b/backend-go/pkg/api/request.go
new file mode 100644
index 0000000000..c92d6fa64d
--- /dev/null
+++ b/backend-go/pkg/api/request.go
@@ -0,0 +1,505 @@
+package api
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+)
+
+// ParseRequest populates a request struct from an HTTP request based on schema sources.
+// It handles body, path, query, header, and cookie parameters.
+// The request type must implement SchemaProvider.
+//
+// IMPORTANT: For fields with From(SourcePath/Query/Header/Cookie), the struct field
+// MUST use `json:"-"` tag to prevent body JSON from overwriting URL-supplied values.
+// The parser binds body first, then URL parameters override — but only if the struct
+// field isn't populated by JSON decoding.
+func ParseRequest[T SchemaProvider](r *http.Request, req T) error {
+ schema := req.Schema()
+
+ // Separate fields by source
+ hasBodyFields := false
+ pathFields := make(map[string]Schema)
+ queryFields := make(map[string]Schema)
+ headerFields := make(map[string]Schema)
+ cookieFields := make(map[string]Schema)
+
+ for name, fieldSchema := range schema.properties {
+ switch fieldSchema.GetSource() {
+ case SourcePath:
+ pathFields[name] = fieldSchema
+ case SourceQuery:
+ queryFields[name] = fieldSchema
+ case SourceHeader:
+ headerFields[name] = fieldSchema
+ case SourceCookie:
+ cookieFields[name] = fieldSchema
+ default:
+ hasBodyFields = true
+ }
+ }
+
+ // Parse body FIRST so URL parameters can override
+ // (prevents mass-assignment where body overwrites path/query/header values)
+ if hasBodyFields && r.Body != nil && r.ContentLength != 0 {
+ if err := json.NewDecoder(r.Body).Decode(req); err != nil {
+ return fmt.Errorf("body: %w", err)
+ }
+ }
+
+ // Parse path parameters (overrides body)
+ for name, fieldSchema := range pathFields {
+ value := chi.URLParam(r, name)
+ if err := setFieldValue(fieldSchema, value); err != nil {
+ return fmt.Errorf("path param %q: %w", name, err)
+ }
+ }
+
+ // Parse query parameters (overrides body) - cache Query() for efficiency
+ if len(queryFields) > 0 {
+ query := r.URL.Query()
+ for name, fieldSchema := range queryFields {
+ value := query.Get(name)
+ if err := setFieldValue(fieldSchema, value); err != nil {
+ return fmt.Errorf("query param %q: %w", name, err)
+ }
+ }
+ }
+
+ // Apply defaults for fields that weren't set
+ applyDefaults(schema)
+
+ // Parse header parameters (overrides body)
+ for name, fieldSchema := range headerFields {
+ value := r.Header.Get(name)
+ if err := setFieldValue(fieldSchema, value); err != nil {
+ return fmt.Errorf("header %q: %w", name, err)
+ }
+ }
+
+ // Parse cookie parameters (overrides body)
+ for name, fieldSchema := range cookieFields {
+ cookie, err := r.Cookie(name)
+ if errors.Is(err, http.ErrNoCookie) {
+ continue
+ }
+ if err != nil {
+ return fmt.Errorf("cookie %q: %w", name, err)
+ }
+ if err := setFieldValue(fieldSchema, cookie.Value); err != nil {
+ return fmt.Errorf("cookie %q: %w", name, err)
+ }
+ }
+
+ return nil
+}
+
+// setFieldValue sets the value of a schema field from a string.
+func setFieldValue(schema Schema, value string) error {
+ if value == "" {
+ return nil
+ }
+
+ switch s := schema.(type) {
+ case *StringSchema:
+ if s.ptr != nil {
+ *s.ptr = value
+ }
+
+ case *IntSchema:
+ i, err := strconv.ParseInt(value, 10, 64)
+ if err != nil {
+ return fmt.Errorf("invalid integer: %w", err)
+ }
+ if s.ptr != nil {
+ *s.ptr = int(i)
+ }
+ if s.ptr64 != nil {
+ *s.ptr64 = i
+ }
+
+ case *FloatSchema:
+ f, err := strconv.ParseFloat(value, 64)
+ if err != nil {
+ return fmt.Errorf("invalid float: %w", err)
+ }
+ if s.ptr != nil {
+ *s.ptr = f
+ }
+
+ case *BoolSchema:
+ b, err := strconv.ParseBool(value)
+ if err != nil {
+ return fmt.Errorf("invalid boolean: %w", err)
+ }
+ if s.ptr != nil {
+ *s.ptr = b
+ }
+
+ case *UUIDSchema:
+ u, err := uuid.Parse(value)
+ if err != nil {
+ return fmt.Errorf("invalid UUID: %w", err)
+ }
+ if s.ptr != nil {
+ *s.ptr = u
+ }
+
+ case *TimeSchema:
+ var t time.Time
+ var err error
+ switch s.format {
+ case "date":
+ t, err = time.Parse("2006-01-02", value)
+ case "time":
+ t, err = time.Parse("15:04:05", value)
+ default:
+ t, err = time.Parse(time.RFC3339, value)
+ }
+ if err != nil {
+ return fmt.Errorf("invalid time: %w", err)
+ }
+ if s.ptr != nil {
+ *s.ptr = t
+ }
+
+ default:
+ return fmt.Errorf("unsupported schema type for parameter: %T", schema)
+ }
+
+ return nil
+}
+
+// chiRegexPattern matches chi path parameter patterns like {id:[0-9]+}
+var chiRegexPattern = regexp.MustCompile(`\{([^:}]+)(?::[^}]+)?\}`)
+
+// ExtractPathParams extracts path parameter names from a chi-style pattern.
+// Strips any chi regex constraints (e.g., {id:[0-9]+} → id).
+func ExtractPathParams(pattern string) []string {
+ matches := chiRegexPattern.FindAllStringSubmatch(pattern, -1)
+ params := make([]string, 0, len(matches))
+ for _, match := range matches {
+ if len(match) > 1 {
+ params = append(params, match[1])
+ }
+ }
+ return params
+}
+
+// ParamSourceString returns the OpenAPI "in" value for a ParamSource.
+func (s ParamSource) String() string {
+ switch s {
+ case SourcePath:
+ return "path"
+ case SourceQuery:
+ return "query"
+ case SourceHeader:
+ return "header"
+ case SourceCookie:
+ return "cookie"
+ default:
+ return "body"
+ }
+}
+
+// SplitSchemaBySource separates an ObjectSchema's properties by their parameter source.
+// Returns body schema and parameter schemas grouped by source location.
+// Preserves property order from the original schema.
+func SplitSchemaBySource(schema *ObjectSchema) (bodySchema *ObjectSchema, params map[ParamSource]map[string]Schema) {
+ params = make(map[ParamSource]map[string]Schema)
+ bodyProps := make(map[string]Schema)
+ var bodyOrder []string
+
+ // Use propertyOrder to maintain deterministic ordering
+ for _, name := range schema.propertyOrder {
+ fieldSchema := schema.properties[name]
+ source := fieldSchema.GetSource()
+ if source == SourceBody {
+ bodyProps[name] = fieldSchema
+ bodyOrder = append(bodyOrder, name)
+ } else {
+ if params[source] == nil {
+ params[source] = make(map[string]Schema)
+ }
+ params[source][name] = fieldSchema
+ }
+ }
+
+ if len(bodyProps) > 0 {
+ bodySchema = &ObjectSchema{
+ properties: bodyProps,
+ propertyOrder: bodyOrder,
+ required: schema.required,
+ additionalProps: schema.additionalProps,
+ title: schema.title,
+ description: schema.description,
+ }
+ }
+
+ return
+}
+
+// BuildOpenAPIParameters generates OpenAPI parameter objects from non-body schema fields.
+func BuildOpenAPIParameters(schema *ObjectSchema) []map[string]any {
+ var params []map[string]any
+
+ for name, fieldSchema := range schema.properties {
+ source := fieldSchema.GetSource()
+ if source == SourceBody {
+ continue
+ }
+
+ openAPI := fieldSchema.OpenAPI()
+
+ param := map[string]any{
+ "name": name,
+ "in": source.String(),
+ "required": fieldSchema.IsRequired() || source == SourcePath,
+ "schema": openAPI,
+ }
+
+ if desc, ok := openAPI["description"].(string); ok && desc != "" {
+ param["description"] = desc
+ }
+ if deprecated, ok := openAPI["deprecated"].(bool); ok && deprecated {
+ param["deprecated"] = true
+ }
+ if example, ok := openAPI["example"]; ok {
+ param["example"] = example
+ }
+
+ // Add style/explode for query array parameters
+ if source == SourceQuery {
+ if _, isArray := fieldSchema.(*ArraySchema); isArray {
+ param["style"] = "form"
+ param["explode"] = true
+ }
+ }
+
+ params = append(params, param)
+ }
+
+ return params
+}
+
+// BuildOpenAPIRequestBody generates an OpenAPI request body object from body schema fields.
+// Returns nil if there are no body fields.
+func BuildOpenAPIRequestBody(schema *ObjectSchema, contentType string) map[string]any {
+ bodySchema, _ := SplitSchemaBySource(schema)
+ if bodySchema == nil {
+ return nil
+ }
+
+ if contentType == "" {
+ contentType = "application/json"
+ }
+
+ hasRequired := false
+ for _, fieldSchema := range bodySchema.properties {
+ if fieldSchema.IsRequired() {
+ hasRequired = true
+ break
+ }
+ }
+
+ return map[string]any{
+ "required": hasRequired,
+ "content": map[string]any{
+ contentType: map[string]any{
+ "schema": bodySchema.OpenAPI(),
+ },
+ },
+ }
+}
+
+// ParseRequestOption configures ParseRequest behavior.
+type ParseRequestOption func(*parseRequestConfig)
+
+type parseRequestConfig struct {
+ disallowUnknownFields bool
+}
+
+// DisallowUnknownFields causes body parsing to fail if unknown fields are present.
+func DisallowUnknownFields() ParseRequestOption {
+ return func(c *parseRequestConfig) {
+ c.disallowUnknownFields = true
+ }
+}
+
+// ParseRequestWithOptions is like ParseRequest but accepts configuration options.
+func ParseRequestWithOptions[T SchemaProvider](r *http.Request, req T, opts ...ParseRequestOption) error {
+ cfg := &parseRequestConfig{}
+ for _, opt := range opts {
+ opt(cfg)
+ }
+
+ schema := req.Schema()
+
+ // Separate fields by source
+ hasBodyFields := false
+ pathFields := make(map[string]Schema)
+ queryFields := make(map[string]Schema)
+ headerFields := make(map[string]Schema)
+ cookieFields := make(map[string]Schema)
+
+ for name, fieldSchema := range schema.properties {
+ switch fieldSchema.GetSource() {
+ case SourcePath:
+ pathFields[name] = fieldSchema
+ case SourceQuery:
+ queryFields[name] = fieldSchema
+ case SourceHeader:
+ headerFields[name] = fieldSchema
+ case SourceCookie:
+ cookieFields[name] = fieldSchema
+ default:
+ hasBodyFields = true
+ }
+ }
+
+ // Handle body parsing
+ if r.Body != nil && r.ContentLength != 0 {
+ if schema.HasBodyUnion() {
+ // For body unions, capture raw body for union parsing during validation
+ var rawBody json.RawMessage
+ if err := json.NewDecoder(r.Body).Decode(&rawBody); err != nil {
+ return fmt.Errorf("body: %w", err)
+ }
+ // Store in the schema's raw pointer - UnionFromSchema will parse during validation
+ if rawPtr := schema.getBodyUnionRawPtr(); rawPtr != nil {
+ *rawPtr = rawBody
+ }
+ } else if hasBodyFields {
+ // Normal body parsing
+ decoder := json.NewDecoder(r.Body)
+ if cfg.disallowUnknownFields {
+ decoder.DisallowUnknownFields()
+ }
+ if err := decoder.Decode(req); err != nil {
+ return fmt.Errorf("body: %w", err)
+ }
+ }
+ }
+
+ // Parse path parameters (overrides body)
+ for name, fieldSchema := range pathFields {
+ value := chi.URLParam(r, name)
+ if err := setFieldValue(fieldSchema, value); err != nil {
+ return fmt.Errorf("path param %q: %w", name, err)
+ }
+ }
+
+ // Parse query parameters (overrides body)
+ if len(queryFields) > 0 {
+ query := r.URL.Query()
+ for name, fieldSchema := range queryFields {
+ values := query[name]
+ if len(values) == 0 {
+ continue
+ }
+ // For array fields, we would need special handling
+ // For now, take the first value
+ if err := setFieldValue(fieldSchema, values[0]); err != nil {
+ return fmt.Errorf("query param %q: %w", name, err)
+ }
+ }
+ }
+
+ // Parse header parameters (overrides body)
+ for name, fieldSchema := range headerFields {
+ value := r.Header.Get(name)
+ if err := setFieldValue(fieldSchema, value); err != nil {
+ return fmt.Errorf("header %q: %w", name, err)
+ }
+ }
+
+ // Parse cookie parameters (overrides body)
+ for name, fieldSchema := range cookieFields {
+ cookie, err := r.Cookie(name)
+ if errors.Is(err, http.ErrNoCookie) {
+ continue
+ }
+ if err != nil {
+ return fmt.Errorf("cookie %q: %w", name, err)
+ }
+ if err := setFieldValue(fieldSchema, cookie.Value); err != nil {
+ return fmt.Errorf("cookie %q: %w", name, err)
+ }
+ }
+
+ // Apply defaults for fields that weren't set
+ applyDefaults(schema)
+
+ return nil
+}
+
+// ParseAndValidate parses the request and validates it against the schema.
+// This is the recommended way to handle requests as it ensures validation is always run.
+func ParseAndValidate[T SchemaProvider](r *http.Request, req T, opts ...ParseRequestOption) error {
+ if err := ParseRequestWithOptions(r, req, opts...); err != nil {
+ return err
+ }
+
+ if errs := req.Schema().Validate(); len(errs) > 0 {
+ return ValidationErrors(errs)
+ }
+
+ return nil
+}
+
+// ParseQueryArray extracts multiple values for a query parameter.
+// Useful for ?tags=a&tags=b style parameters.
+func ParseQueryArray(r *http.Request, name string) []string {
+ return r.URL.Query()[name]
+}
+
+// ParseQueryArrayCSV extracts comma-separated values for a query parameter.
+// Useful for ?tags=a,b,c style parameters.
+func ParseQueryArrayCSV(r *http.Request, name string) []string {
+ value := r.URL.Query().Get(name)
+ if value == "" {
+ return nil
+ }
+ return strings.Split(value, ",")
+}
+
+// applyDefaults applies default values to schema fields that weren't set.
+// For non-body fields (query, path, etc.), if the value is zero and a default exists, apply it.
+func applyDefaults(schema *ObjectSchema) {
+ for _, fieldSchema := range schema.properties {
+ switch s := fieldSchema.(type) {
+ case *IntSchema:
+ if s.defaultVal != nil && s.source != SourceBody {
+ val, _ := s.value()
+ if val == 0 {
+ if s.ptr != nil {
+ *s.ptr = int(*s.defaultVal)
+ }
+ if s.ptr64 != nil {
+ *s.ptr64 = *s.defaultVal
+ }
+ }
+ }
+ case *StringSchema:
+ if s.defaultVal != nil && s.source != SourceBody && s.ptr != nil && *s.ptr == "" {
+ *s.ptr = *s.defaultVal
+ }
+ case *BoolSchema:
+ if s.defaultVal != nil && s.source != SourceBody && s.ptr != nil && !*s.ptr {
+ *s.ptr = *s.defaultVal
+ }
+ case *FloatSchema:
+ if s.defaultVal != nil && s.source != SourceBody && s.ptr != nil && *s.ptr == 0 {
+ *s.ptr = *s.defaultVal
+ }
+ }
+ }
+}
diff --git a/backend-go/pkg/api/request_test.go b/backend-go/pkg/api/request_test.go
new file mode 100644
index 0000000000..790587387b
--- /dev/null
+++ b/backend-go/pkg/api/request_test.go
@@ -0,0 +1,956 @@
+package api
+
+import (
+ "bytes"
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type ParseTestRequest struct {
+ OrgID string `json:"-"`
+ Include string `json:"-"`
+ Name string `json:"name"`
+ Age int `json:"age"`
+}
+
+func (r *ParseTestRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "orgId": String(&r.OrgID).Required().From(SourcePath),
+ "include": String(&r.Include).Optional().From(SourceQuery),
+ "name": String(&r.Name).Required(),
+ "age": Int(&r.Age).Optional(),
+ })
+}
+
+func TestParseRequest_PathAndQuery(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req ParseTestRequest
+ if err := ParseRequest(r, &req); err != nil {
+ t.Errorf("ParseRequest failed: %v", err)
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ if req.OrgID != "org-123" {
+ t.Errorf("expected OrgID 'org-123', got %q", req.OrgID)
+ }
+ if req.Include != "metadata" {
+ t.Errorf("expected Include 'metadata', got %q", req.Include)
+ }
+ if req.Name != "John" {
+ t.Errorf("expected Name 'John', got %q", req.Name)
+ }
+ if req.Age != 30 {
+ t.Errorf("expected Age 30, got %d", req.Age)
+ }
+ }
+
+ r := chi.NewRouter()
+ r.Post("/orgs/{orgId}/users", handler)
+
+ body := `{"name": "John", "age": 30}`
+ req := httptest.NewRequestWithContext(context.Background(), "POST", "/orgs/org-123/users?include=metadata", bytes.NewBufferString(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ r.ServeHTTP(w, req)
+
+ if w.Code != 200 {
+ t.Errorf("expected status 200, got %d", w.Code)
+ }
+}
+
+func TestParseRequest_UUIDPath(t *testing.T) {
+ type UUIDRequest struct {
+ ID uuid.UUID `json:"-"`
+ }
+
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req UUIDRequest
+ schema := Object(map[string]Schema{
+ "id": UUID(&req.ID).Required().From(SourcePath),
+ })
+ _ = schema // For schema definition
+
+ // Manual parse since UUIDRequest doesn't implement SchemaProvider
+ idStr := chi.URLParam(r, "id")
+ var err error
+ req.ID, err = uuid.Parse(idStr)
+ if err != nil {
+ t.Errorf("failed to parse UUID: %v", err)
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ expected := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
+ if req.ID != expected {
+ t.Errorf("expected ID %v, got %v", expected, req.ID)
+ }
+ }
+
+ r := chi.NewRouter()
+ r.Get("/items/{id}", handler)
+
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/items/550e8400-e29b-41d4-a716-446655440000", nil)
+ w := httptest.NewRecorder()
+
+ r.ServeHTTP(w, req)
+
+ if w.Code != 200 {
+ t.Errorf("expected status 200, got %d", w.Code)
+ }
+}
+
+func TestExtractPathParams(t *testing.T) {
+ tests := []struct {
+ pattern string
+ expected []string
+ }{
+ {"/users/{id}", []string{"id"}},
+ {"/orgs/{orgId}/projects/{projectId}", []string{"orgId", "projectId"}},
+ {"/items/{id:[0-9]+}", []string{"id"}},
+ {"/users/{userID:[a-f0-9-]+}/posts/{postID:[0-9]+}", []string{"userID", "postID"}},
+ {"/static/path", nil},
+ {"/{version}/api/{resource}", []string{"version", "resource"}},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.pattern, func(t *testing.T) {
+ result := ExtractPathParams(tt.pattern)
+ if len(result) != len(tt.expected) {
+ t.Errorf("expected %v, got %v", tt.expected, result)
+ return
+ }
+ for i, param := range result {
+ if param != tt.expected[i] {
+ t.Errorf("expected param %d to be %q, got %q", i, tt.expected[i], param)
+ }
+ }
+ })
+ }
+}
+
+func TestSplitSchemaBySource(t *testing.T) {
+ var name, orgID, include, token string
+
+ schema := Object(map[string]Schema{
+ "name": String(&name).Required(),
+ "orgId": String(&orgID).Required().From(SourcePath),
+ "include": String(&include).Optional().From(SourceQuery),
+ "token": String(&token).Required().From(SourceHeader),
+ })
+
+ bodySchema, params := SplitSchemaBySource(schema)
+
+ if bodySchema == nil {
+ t.Fatal("expected body schema, got nil")
+ }
+ if len(bodySchema.properties) != 1 {
+ t.Errorf("expected 1 body property, got %d", len(bodySchema.properties))
+ }
+ if _, ok := bodySchema.properties["name"]; !ok {
+ t.Error("expected 'name' in body properties")
+ }
+
+ if len(params[SourcePath]) != 1 {
+ t.Errorf("expected 1 path param, got %d", len(params[SourcePath]))
+ }
+ if len(params[SourceQuery]) != 1 {
+ t.Errorf("expected 1 query param, got %d", len(params[SourceQuery]))
+ }
+ if len(params[SourceHeader]) != 1 {
+ t.Errorf("expected 1 header param, got %d", len(params[SourceHeader]))
+ }
+}
+
+func TestBuildOpenAPIParameters(t *testing.T) {
+ var name, orgID, include string
+ var limit int
+
+ schema := Object(map[string]Schema{
+ "name": String(&name).Required(),
+ "orgId": String(&orgID).Required().From(SourcePath).Description("Organization ID"),
+ "include": String(&include).Optional().From(SourceQuery).Description("Fields to include"),
+ "limit": Int(&limit).Optional().From(SourceQuery),
+ })
+
+ params := BuildOpenAPIParameters(schema)
+
+ if len(params) != 3 {
+ t.Fatalf("expected 3 parameters, got %d", len(params))
+ }
+
+ paramMap := make(map[string]map[string]any)
+ for _, p := range params {
+ paramMap[p["name"].(string)] = p
+ }
+
+ orgParam := paramMap["orgId"]
+ if orgParam["in"] != "path" {
+ t.Errorf("expected orgId in 'path', got %v", orgParam["in"])
+ }
+ if orgParam["required"] != true {
+ t.Error("expected orgId to be required")
+ }
+ if orgParam["description"] != "Organization ID" {
+ t.Errorf("expected description 'Organization ID', got %v", orgParam["description"])
+ }
+
+ includeParam := paramMap["include"]
+ if includeParam["in"] != "query" {
+ t.Errorf("expected include in 'query', got %v", includeParam["in"])
+ }
+ if includeParam["required"] != false {
+ t.Error("expected include to not be required")
+ }
+}
+
+func TestBuildOpenAPIRequestBody(t *testing.T) {
+ var name, orgID string
+
+ schema := Object(map[string]Schema{
+ "name": String(&name).Required(),
+ "orgId": String(&orgID).Required().From(SourcePath),
+ })
+
+ body := BuildOpenAPIRequestBody(schema, "")
+
+ if body == nil {
+ t.Fatal("expected request body, got nil")
+ }
+
+ if body["required"] != true {
+ t.Error("expected required to be true")
+ }
+
+ content := body["content"].(map[string]any)
+ jsonContent := content["application/json"].(map[string]any)
+ bodySchema := jsonContent["schema"].(map[string]any)
+
+ props := bodySchema["properties"].(map[string]any)
+ if _, ok := props["name"]; !ok {
+ t.Error("expected 'name' in body schema properties")
+ }
+ if _, ok := props["orgId"]; ok {
+ t.Error("did not expect 'orgId' in body schema properties")
+ }
+}
+
+func TestParamSourceString(t *testing.T) {
+ tests := []struct {
+ source ParamSource
+ expected string
+ }{
+ {SourceBody, "body"},
+ {SourcePath, "path"},
+ {SourceQuery, "query"},
+ {SourceHeader, "header"},
+ {SourceCookie, "cookie"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.expected, func(t *testing.T) {
+ if tt.source.String() != tt.expected {
+ t.Errorf("expected %q, got %q", tt.expected, tt.source.String())
+ }
+ })
+ }
+}
+
+type HeaderCookieRequest struct {
+ AuthToken string `json:"-"`
+ SessionID string `json:"-"`
+ RequestBody string `json:"body"`
+}
+
+func (r *HeaderCookieRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "Authorization": String(&r.AuthToken).Required().From(SourceHeader),
+ "session_id": String(&r.SessionID).Optional().From(SourceCookie),
+ "body": String(&r.RequestBody).Required(),
+ })
+}
+
+func TestParseRequest_HeaderAndCookie(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req HeaderCookieRequest
+ if err := ParseRequest(r, &req); err != nil {
+ t.Errorf("ParseRequest failed: %v", err)
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ if req.AuthToken != "Bearer token123" {
+ t.Errorf("expected AuthToken 'Bearer token123', got %q", req.AuthToken)
+ }
+ if req.SessionID != "sess-abc" {
+ t.Errorf("expected SessionID 'sess-abc', got %q", req.SessionID)
+ }
+ if req.RequestBody != "hello" {
+ t.Errorf("expected RequestBody 'hello', got %q", req.RequestBody)
+ }
+ }
+
+ r := chi.NewRouter()
+ r.Post("/api/endpoint", handler)
+
+ body := `{"body": "hello"}`
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/api/endpoint", bytes.NewBufferString(body))
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("Authorization", "Bearer token123")
+ httpReq.AddCookie(&http.Cookie{Name: "session_id", Value: "sess-abc"})
+ w := httptest.NewRecorder()
+
+ r.ServeHTTP(w, httpReq)
+
+ if w.Code != 200 {
+ t.Errorf("expected status 200, got %d", w.Code)
+ }
+}
+
+func TestSetFieldValue_Int(t *testing.T) {
+ var val int
+ schema := Int(&val)
+
+ if err := setFieldValue(schema, "42"); err != nil {
+ t.Fatalf("setFieldValue failed: %v", err)
+ }
+ if val != 42 {
+ t.Errorf("expected 42, got %d", val)
+ }
+}
+
+func TestSetFieldValue_Bool(t *testing.T) {
+ var val bool
+ schema := Bool(&val)
+
+ if err := setFieldValue(schema, "true"); err != nil {
+ t.Fatalf("setFieldValue failed: %v", err)
+ }
+ if !val {
+ t.Error("expected true, got false")
+ }
+}
+
+func TestSetFieldValue_Float(t *testing.T) {
+ var val float64
+ schema := Float(&val)
+
+ if err := setFieldValue(schema, "3.14"); err != nil {
+ t.Fatalf("setFieldValue failed: %v", err)
+ }
+ if val != 3.14 {
+ t.Errorf("expected 3.14, got %f", val)
+ }
+}
+
+func TestSetFieldValue_UUID(t *testing.T) {
+ var val uuid.UUID
+ schema := UUID(&val)
+
+ if err := setFieldValue(schema, "550e8400-e29b-41d4-a716-446655440000"); err != nil {
+ t.Fatalf("setFieldValue failed: %v", err)
+ }
+ expected := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
+ if val != expected {
+ t.Errorf("expected %v, got %v", expected, val)
+ }
+}
+
+func TestSetFieldValue_InvalidInt(t *testing.T) {
+ var val int
+ schema := Int(&val)
+
+ if err := setFieldValue(schema, "not-a-number"); err == nil {
+ t.Error("expected error for invalid int")
+ }
+}
+
+func TestSetFieldValue_InvalidUUID(t *testing.T) {
+ var val uuid.UUID
+ schema := UUID(&val)
+
+ if err := setFieldValue(schema, "not-a-uuid"); err == nil {
+ t.Error("expected error for invalid UUID")
+ }
+}
+
+func TestParseQueryArray(t *testing.T) {
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/items?tags=a&tags=b&tags=c", nil)
+ tags := ParseQueryArray(req, "tags")
+
+ if len(tags) != 3 {
+ t.Fatalf("expected 3 tags, got %d", len(tags))
+ }
+ if tags[0] != "a" || tags[1] != "b" || tags[2] != "c" {
+ t.Errorf("expected [a, b, c], got %v", tags)
+ }
+}
+
+func TestParseQueryArrayCSV(t *testing.T) {
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/items?tags=a,b,c", nil)
+ tags := ParseQueryArrayCSV(req, "tags")
+
+ if len(tags) != 3 {
+ t.Fatalf("expected 3 tags, got %d", len(tags))
+ }
+ if tags[0] != "a" || tags[1] != "b" || tags[2] != "c" {
+ t.Errorf("expected [a, b, c], got %v", tags)
+ }
+}
+
+func TestParseRequest_NoBody(t *testing.T) {
+ type GetRequest struct {
+ ID string `json:"-"`
+ }
+
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req GetRequest
+ schema := Object(map[string]Schema{
+ "id": String(&req.ID).Required().From(SourcePath),
+ })
+
+ // Extract path param manually (since GetRequest doesn't implement SchemaProvider)
+ for name, fieldSchema := range schema.properties {
+ if fieldSchema.GetSource() == SourcePath {
+ value := chi.URLParam(r, name)
+ if err := setFieldValue(fieldSchema, value); err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+ }
+ }
+
+ if req.ID != "item-123" {
+ t.Errorf("expected ID 'item-123', got %q", req.ID)
+ }
+ }
+
+ router := chi.NewRouter()
+ router.Get("/items/{id}", handler)
+
+ httpReq := httptest.NewRequestWithContext(context.Background(), "GET", "/items/item-123", nil)
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ if w.Code != 200 {
+ t.Errorf("expected status 200, got %d", w.Code)
+ }
+}
+
+func TestParseRequest_EmptyBody_RequiredFieldValidation(t *testing.T) {
+ type RequestWithRequiredBody struct {
+ ID string `json:"-"`
+ Name string `json:"name"`
+ }
+
+ var failed bool
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req RequestWithRequiredBody
+ schema := Object(map[string]Schema{
+ "id": String(&req.ID).Required().From(SourcePath),
+ "name": String(&req.Name).Required(),
+ })
+
+ // Parse path params
+ req.ID = chi.URLParam(r, "id")
+
+ // Body is empty (ContentLength == 0), validation should fail for required "name"
+ errs := schema.Validate()
+ if len(errs) == 0 {
+ failed = true
+ t.Error("expected validation error for required 'name' field")
+ }
+ }
+
+ router := chi.NewRouter()
+ router.Post("/items/{id}", handler)
+
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/items/item-123", nil) // Empty body
+ httpReq.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ if failed {
+ t.Error("test failed inside handler")
+ }
+}
+
+func TestParseRequest_ChunkedTransferEncoding(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req ParseTestRequest
+ if err := ParseRequest(r, &req); err != nil {
+ t.Errorf("ParseRequest failed: %v", err)
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ if req.Name != "ChunkedTest" {
+ t.Errorf("expected Name 'ChunkedTest', got %q", req.Name)
+ }
+ }
+
+ router := chi.NewRouter()
+ router.Post("/orgs/{orgId}/test", handler)
+
+ body := `{"name": "ChunkedTest", "age": 25}`
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/orgs/org-123/test", bytes.NewBufferString(body))
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.ContentLength = -1 // Simulate chunked transfer encoding
+ httpReq.TransferEncoding = []string{"chunked"}
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ if w.Code != 200 {
+ t.Errorf("expected status 200, got %d", w.Code)
+ }
+}
+
+type RequiredHeaderRequest struct {
+ APIKey string `json:"-"`
+}
+
+func (r *RequiredHeaderRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "X-API-Key": String(&r.APIKey).Required().From(SourceHeader),
+ })
+}
+
+func TestParseAndValidate_RequiredHeaderMissing(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req RequiredHeaderRequest
+ err := ParseAndValidate(r, &req)
+ if err == nil {
+ t.Error("expected validation error for missing required header")
+ return
+ }
+
+ // Error message should mention 'required'
+ if !bytes.Contains([]byte(err.Error()), []byte("required")) {
+ t.Errorf("expected 'required' in error message, got: %v", err)
+ }
+ }
+
+ router := chi.NewRouter()
+ router.Get("/api/test", handler)
+
+ httpReq := httptest.NewRequestWithContext(context.Background(), "GET", "/api/test", nil) // No X-API-Key header
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+}
+
+type RequiredCookieRequest struct {
+ SessionID string `json:"-"`
+}
+
+func (r *RequiredCookieRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "session_id": String(&r.SessionID).Required().From(SourceCookie),
+ })
+}
+
+func TestParseAndValidate_RequiredCookieMissing(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req RequiredCookieRequest
+ err := ParseAndValidate(r, &req)
+ if err == nil {
+ t.Error("expected validation error for missing required cookie")
+ return
+ }
+
+ // Error message should mention 'required'
+ if !bytes.Contains([]byte(err.Error()), []byte("required")) {
+ t.Errorf("expected 'required' in error message, got: %v", err)
+ }
+ }
+
+ router := chi.NewRouter()
+ router.Get("/api/test", handler)
+
+ httpReq := httptest.NewRequestWithContext(context.Background(), "GET", "/api/test", nil) // No session_id cookie
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+}
+
+func TestParseRequest_UUIDPath_WithSchemaProvider(t *testing.T) {
+ type UUIDPathRequest struct {
+ ID uuid.UUID `json:"-"`
+ }
+
+ // Helper to create schema - using closure to bind to request
+ schemaFor := func(req *UUIDPathRequest) *ObjectSchema {
+ return Object(map[string]Schema{
+ "id": UUID(&req.ID).Required().From(SourcePath),
+ })
+ }
+
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req UUIDPathRequest
+ schema := schemaFor(&req)
+
+ // Extract path param and validate
+ idStr := chi.URLParam(r, "id")
+ if err := setFieldValue(schema.properties["id"], idStr); err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ errs := schema.Validate()
+ if len(errs) > 0 {
+ http.Error(w, errs[0].Message, 400)
+ return
+ }
+
+ expected := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
+ if req.ID != expected {
+ t.Errorf("expected ID %v, got %v", expected, req.ID)
+ }
+ }
+
+ router := chi.NewRouter()
+ router.Get("/items/{id}", handler)
+
+ httpReq := httptest.NewRequestWithContext(context.Background(), "GET", "/items/550e8400-e29b-41d4-a716-446655440000", nil)
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ if w.Code != 200 {
+ t.Errorf("expected status 200, got %d", w.Code)
+ }
+}
+
+func TestParseQueryArray_Empty(t *testing.T) {
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/items", nil)
+ tags := ParseQueryArray(req, "tags")
+
+ if len(tags) != 0 {
+ t.Errorf("expected empty array, got %v", tags)
+ }
+}
+
+func TestParseQueryArrayCSV_Empty(t *testing.T) {
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/items", nil)
+ tags := ParseQueryArrayCSV(req, "tags")
+
+ if len(tags) != 0 {
+ t.Errorf("expected empty array, got %v", tags)
+ }
+}
+
+func TestParseQueryArrayCSV_SingleValue(t *testing.T) {
+ req := httptest.NewRequestWithContext(context.Background(), "GET", "/items?tags=single", nil)
+ tags := ParseQueryArrayCSV(req, "tags")
+
+ if len(tags) != 1 || tags[0] != "single" {
+ t.Errorf("expected [single], got %v", tags)
+ }
+}
+
+// --- Mass Assignment Tests ---
+
+type MassAssignmentRequest struct {
+ OrgID string `json:"orgId"` // Intentionally NOT json:"-" to test the vulnerability
+ Name string `json:"name"`
+}
+
+func (r *MassAssignmentRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "orgId": String(&r.OrgID).Required().From(SourcePath),
+ "name": String(&r.Name).Required(),
+ })
+}
+
+func TestParseRequest_MassAssignment_PathWinsOverBody(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req MassAssignmentRequest
+ if err := ParseRequest(r, &req); err != nil {
+ t.Errorf("ParseRequest failed: %v", err)
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ // Path parameter should win over body, even with matching JSON tag
+ // This tests the fix for the mass-assignment vulnerability
+ assert.Equal(t, "legitimate-org", req.OrgID, "path param should override body")
+ assert.Equal(t, "secret-name", req.Name)
+ }
+
+ router := chi.NewRouter()
+ router.Post("/orgs/{orgId}/secrets", handler)
+
+ // Attacker tries to override orgId via body
+ body := `{"orgId": "attacker-org", "name": "secret-name"}`
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/orgs/legitimate-org/secrets", bytes.NewBufferString(body))
+ httpReq.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ assert.Equal(t, 200, w.Code)
+}
+
+// --- Header/Cookie Parameter Tests ---
+
+type HeaderCookieTestRequest struct {
+ AuthHeader string `json:"-"`
+ SessionID string `json:"-"`
+ BodyField string `json:"body"`
+}
+
+func (r *HeaderCookieTestRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "X-Auth-Token": String(&r.AuthHeader).Required().From(SourceHeader),
+ "session": String(&r.SessionID).Optional().From(SourceCookie),
+ "body": String(&r.BodyField).Required(),
+ })
+}
+
+func TestParseRequest_HeaderParam(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req HeaderCookieTestRequest
+ if err := ParseRequest(r, &req); err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ assert.Equal(t, "token-value", req.AuthHeader)
+ assert.Equal(t, "data", req.BodyField)
+ }
+
+ router := chi.NewRouter()
+ router.Post("/test", handler)
+
+ body := `{"body": "data"}`
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/test", bytes.NewBufferString(body))
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("X-Auth-Token", "token-value")
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ assert.Equal(t, 200, w.Code)
+}
+
+func TestParseRequest_CookieParam(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req HeaderCookieTestRequest
+ if err := ParseRequest(r, &req); err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ assert.Equal(t, "sess-123", req.SessionID)
+ }
+
+ router := chi.NewRouter()
+ router.Post("/test", handler)
+
+ body := `{"body": "data"}`
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/test", bytes.NewBufferString(body))
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("X-Auth-Token", "token")
+ httpReq.AddCookie(&http.Cookie{Name: "session", Value: "sess-123"})
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ assert.Equal(t, 200, w.Code)
+}
+
+func TestParseRequest_MissingCookie_Tolerated(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req HeaderCookieTestRequest
+ if err := ParseRequest(r, &req); err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ // Missing optional cookie should be tolerated
+ assert.Empty(t, req.SessionID)
+ }
+
+ router := chi.NewRouter()
+ router.Post("/test", handler)
+
+ body := `{"body": "data"}`
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/test", bytes.NewBufferString(body))
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("X-Auth-Token", "token")
+ // No cookie set
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ assert.Equal(t, 200, w.Code)
+}
+
+func TestParseRequest_EmptyBody_SkipsBodyParsing(t *testing.T) {
+ type GetRequest struct {
+ ID string `json:"-"`
+ }
+
+ var req GetRequest
+ schema := Object(map[string]Schema{
+ "id": String(&req.ID).Required().From(SourcePath),
+ })
+
+ // Create request with Content-Length: 0
+ httpReq := httptest.NewRequestWithContext(context.Background(), "GET", "/items/123", http.NoBody)
+ httpReq.ContentLength = 0
+
+ // Manually test the schema source separation
+ hasBodyFields := false
+ for _, fieldSchema := range schema.properties {
+ if fieldSchema.GetSource() == SourceBody {
+ hasBodyFields = true
+ }
+ }
+
+ assert.False(t, hasBodyFields, "GET request with only path params should have no body fields")
+}
+
+// --- ParseAndValidate Tests ---
+
+func TestParseAndValidate_ValidRequest(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req ParseTestRequest
+ if err := ParseAndValidate(r, &req); err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ assert.Equal(t, "org-123", req.OrgID)
+ assert.Equal(t, "John", req.Name)
+ }
+
+ router := chi.NewRouter()
+ router.Post("/orgs/{orgId}/users", handler)
+
+ body := `{"name": "John", "age": 30}`
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/orgs/org-123/users", bytes.NewBufferString(body))
+ httpReq.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ assert.Equal(t, 200, w.Code)
+}
+
+func TestParseAndValidate_InvalidRequest(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req ParseTestRequest
+ if err := ParseAndValidate(r, &req); err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+ w.WriteHeader(200)
+ }
+
+ router := chi.NewRouter()
+ router.Post("/orgs/{orgId}/users", handler)
+
+ // Missing required "name" field
+ body := `{"age": 30}`
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/orgs/org-123/users", bytes.NewBufferString(body))
+ httpReq.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ assert.Equal(t, 400, w.Code)
+}
+
+// --- DisallowUnknownFields Tests ---
+
+type strictBodyRequest struct {
+ Name string `json:"name"`
+}
+
+func (r *strictBodyRequest) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "name": String(&r.Name).Required(),
+ })
+}
+
+func TestParseRequestWithOptions_DisallowUnknownFields(t *testing.T) {
+ handler := func(w http.ResponseWriter, r *http.Request) {
+ var req strictBodyRequest
+ err := ParseRequestWithOptions(r, &req, DisallowUnknownFields())
+ if err == nil {
+ t.Error("expected error for unknown field 'extra'")
+ http.Error(w, "expected error", 500)
+ return
+ }
+ w.WriteHeader(http.StatusBadRequest)
+ }
+
+ router := chi.NewRouter()
+ router.Post("/test", handler)
+
+ body := `{"name": "John", "extra": "field"}`
+ httpReq := httptest.NewRequestWithContext(context.Background(), "POST", "/test", bytes.NewBufferString(body))
+ httpReq.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+
+ router.ServeHTTP(w, httpReq)
+
+ assert.Equal(t, http.StatusBadRequest, w.Code)
+}
+
+// --- setFieldValue Error Tests ---
+
+func TestSetFieldValue_ErrorPaths(t *testing.T) {
+ t.Run("invalid int", func(t *testing.T) {
+ var val int
+ schema := Int(&val)
+ err := setFieldValue(schema, "not-a-number")
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "invalid integer")
+ })
+
+ t.Run("invalid float", func(t *testing.T) {
+ var val float64
+ schema := Float(&val)
+ err := setFieldValue(schema, "not-a-float")
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "invalid float")
+ })
+
+ t.Run("invalid bool", func(t *testing.T) {
+ var val bool
+ schema := Bool(&val)
+ err := setFieldValue(schema, "not-a-bool")
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "invalid boolean")
+ })
+
+ t.Run("invalid uuid", func(t *testing.T) {
+ var val uuid.UUID
+ schema := UUID(&val)
+ err := setFieldValue(schema, "not-a-uuid")
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "invalid UUID")
+ })
+
+ t.Run("invalid time", func(t *testing.T) {
+ var val time.Time
+ schema := Time(&val)
+ err := setFieldValue(schema, "not-a-time")
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "invalid time")
+ })
+}
diff --git a/backend-go/pkg/api/router.go b/backend-go/pkg/api/router.go
new file mode 100644
index 0000000000..b776daada7
--- /dev/null
+++ b/backend-go/pkg/api/router.go
@@ -0,0 +1,329 @@
+package api
+
+import (
+ "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
+}
+
+// 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
+}
+
+// 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,
+ }
+
+ fn(sub)
+
+ r.endpoints = append(r.endpoints, sub.endpoints...)
+
+ r.Router.Mount(pattern, sub.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,
+ }
+
+ fn(sub)
+
+ r.endpoints = append(r.endpoints, sub.endpoints...)
+}
+
+// Mount attaches a sub-router at a given pattern
+func (r *Router) Mount(pattern string, handler http.Handler) {
+ r.Router.Mount(pattern, handler)
+
+ 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)
+ }
+ }
+}
+
+// Use appends middleware to the router
+func (r *Router) Use(middlewares ...func(http.Handler) http.Handler) {
+ r.Router.Use(middlewares...)
+}
+
+// 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,
+ }
+}
+
+// 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)
+ }
+
+ // Store original pattern for chi registration (relative to this router)
+ chiPattern := ep.Pattern
+ if chiPattern == "" {
+ chiPattern = "/"
+ }
+
+ // 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)
+ }
+}
+
+// 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)
+}
+
+// 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)
+}
+
+// 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)
+}
+
+// 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)
+ }
+ 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)
+}
+
+// Endpoints returns all registered endpoints (for OpenAPI generation)
+func (r *Router) Endpoints() []Endpoint {
+ return r.endpoints
+}
+
+// ServeHTTP implements http.Handler
+func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
+ r.Router.ServeHTTP(w, req)
+}
+
+// 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
+ }
+}
+
+// WithResponse sets the response schema
+func WithResponse(resp SchemaProvider) EndpointOption {
+ return func(e *Endpoint) {
+ e.Response = resp
+ }
+}
+
+// WithResponses sets multiple response schemas by status code
+func WithResponses(responses map[int]SchemaProvider) EndpointOption {
+ return func(e *Endpoint) {
+ e.Responses = responses
+ }
+}
+
+// WithSecurityRequirements sets the security requirements (OR relationship)
+func WithSecurityRequirements(security ...Security) EndpointOption {
+ return func(e *Endpoint) {
+ e.Security = security
+ }
+}
+
+// WithNoAuth explicitly marks endpoint as requiring no authentication
+func WithNoAuth() EndpointOption {
+ return func(e *Endpoint) {
+ e.Security = []Security{{}}
+ }
+}
+
+// WithTags sets the tags
+func WithTags(tags ...string) EndpointOption {
+ return func(e *Endpoint) {
+ e.Tags = tags
+ }
+}
+
+// WithSummary sets the summary
+func WithSummary(summary string) EndpointOption {
+ return func(e *Endpoint) {
+ e.Summary = summary
+ }
+}
+
+// WithDescription sets the description
+func WithDescription(desc string) EndpointOption {
+ return func(e *Endpoint) {
+ e.Description = desc
+ }
+}
+
+// WithOperationID sets the operation ID
+func WithOperationID(id string) EndpointOption {
+ return func(e *Endpoint) {
+ e.OperationID = id
+ }
+}
+
+// WithDeprecated marks the endpoint as deprecated
+func WithDeprecated() EndpointOption {
+ return func(e *Endpoint) {
+ e.Deprecated = true
+ }
+}
+
+// WithPathParams sets the path parameter schemas
+func WithPathParams(params map[string]Schema) EndpointOption {
+ return func(e *Endpoint) {
+ e.PathParams = params
+ }
+}
+
+// WithQueryParams sets the query parameter schemas
+func WithQueryParams(params map[string]Schema) EndpointOption {
+ return func(e *Endpoint) {
+ e.QueryParams = params
+ }
+}
+
+// WithHeaderParams sets the header parameter schemas
+func WithHeaderParams(params map[string]Schema) EndpointOption {
+ return func(e *Endpoint) {
+ e.HeaderParams = params
+ }
+}
+
+// WithCookieParams sets the cookie parameter schemas
+func WithCookieParams(params map[string]Schema) EndpointOption {
+ return func(e *Endpoint) {
+ e.CookieParams = params
+ }
+}
+
+// WithResponseDescriptions sets custom descriptions for response status codes
+func WithResponseDescriptions(descriptions map[int]string) EndpointOption {
+ return func(e *Endpoint) {
+ e.ResponseDescriptions = descriptions
+ }
+}
diff --git a/backend-go/pkg/api/router_test.go b/backend-go/pkg/api/router_test.go
new file mode 100644
index 0000000000..da05399798
--- /dev/null
+++ b/backend-go/pkg/api/router_test.go
@@ -0,0 +1,702 @@
+package api
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// --- Basic Route Registration ---
+
+func TestRouter_Get(t *testing.T) {
+ r := NewRouter()
+
+ called := false
+ r.Get("/test", func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ w.WriteHeader(http.StatusOK)
+ })
+
+ 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()
+ require.Len(t, endpoints, 1)
+ assert.Equal(t, http.MethodGet, endpoints[0].Method)
+ assert.Equal(t, "/test", endpoints[0].Pattern)
+}
+
+func TestRouter_Post(t *testing.T) {
+ r := NewRouter()
+
+ r.Post("/create", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusCreated)
+ })
+
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/create", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ r.ServeHTTP(rec, req)
+
+ assert.Equal(t, http.StatusCreated, rec.Code)
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+ assert.Equal(t, http.MethodPost, endpoints[0].Method)
+}
+
+func TestRouter_Put(t *testing.T) {
+ r := NewRouter()
+
+ r.Put("/update", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+ assert.Equal(t, http.MethodPut, endpoints[0].Method)
+}
+
+func TestRouter_Patch(t *testing.T) {
+ r := NewRouter()
+
+ r.Patch("/partial", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+ assert.Equal(t, http.MethodPatch, endpoints[0].Method)
+}
+
+func TestRouter_Delete(t *testing.T) {
+ r := NewRouter()
+
+ r.Delete("/remove", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusNoContent)
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+ assert.Equal(t, http.MethodDelete, endpoints[0].Method)
+}
+
+// --- Route with Options ---
+
+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(),
+ )
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+
+ ep := endpoints[0]
+ assert.Equal(t, "Get user by ID", ep.Summary)
+ assert.Equal(t, "Retrieves a user by their unique ID", ep.Description)
+ assert.Equal(t, "getUser", ep.OperationID)
+ assert.Equal(t, []string{"Users"}, ep.Tags)
+ assert.True(t, ep.Deprecated)
+ require.Len(t, ep.Security, 1)
+ reqs := ep.Security[0].Requirements()
+ require.Len(t, reqs, 1)
+ 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()
+
+ 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)
+ })
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 2)
+ assert.Equal(t, "/api/v1/users", endpoints[0].Pattern)
+ assert.Equal(t, "/api/v1/users", endpoints[1].Pattern)
+
+ // Test actual routing
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/v1/users", http.NoBody)
+ rec := httptest.NewRecorder()
+ r.ServeHTTP(rec, req)
+ assert.Equal(t, http.StatusOK, rec.Code)
+}
+
+func TestRouter_NestedRoutes(t *testing.T) {
+ r := NewRouter()
+
+ 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"))
+ })
+ })
+ })
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 2)
+ assert.Equal(t, "/api/v1/users/", endpoints[0].Pattern)
+ assert.Equal(t, "/api/v1/users/{id}", endpoints[1].Pattern)
+
+ // Test actual routing
+ 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, "list users", string(body))
+}
+
+// --- Default Security and Tags ---
+
+func TestRouter_WithSecurity(t *testing.T) {
+ r := NewRouter()
+
+ 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) {})
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 2)
+
+ for _, ep := range endpoints {
+ require.Len(t, ep.Security, 1)
+ reqs := ep.Security[0].Requirements()
+ require.Len(t, reqs, 1)
+ assert.Equal(t, "jwt", reqs[0].Scheme)
+ }
+}
+
+func TestRouter_WithTags(t *testing.T) {
+ r := NewRouter()
+
+ 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) {})
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 2)
+
+ for _, ep := range endpoints {
+ assert.Equal(t, []string{"Users", "Admin"}, ep.Tags)
+ }
+}
+
+func TestRouter_InheritedDefaults(t *testing.T) {
+ r := NewRouter()
+
+ r.Route("/api", func(api *Router) {
+ api.WithSecurity(NewSecurity("jwt"))
+ api.WithTags("API")
+
+ api.Route("/v1", func(v1 *Router) {
+ // Should inherit security and tags from parent
+ v1.Get("/test", func(w http.ResponseWriter, r *http.Request) {})
+ })
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+
+ ep := endpoints[0]
+ require.Len(t, ep.Security, 1)
+ reqs := ep.Security[0].Requirements()
+ require.Len(t, reqs, 1)
+ assert.Equal(t, "jwt", reqs[0].Scheme)
+ 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()
+
+ 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"),
+ )
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+
+ ep := endpoints[0]
+ require.Len(t, ep.Security, 1)
+ reqs := ep.Security[0].Requirements()
+ require.Len(t, reqs, 1)
+ assert.Equal(t, "api_key", reqs[0].Scheme)
+ assert.Equal(t, []string{"Special"}, ep.Tags)
+}
+
+// --- Group without path prefix ---
+
+func TestRouter_Group(t *testing.T) {
+ r := NewRouter()
+
+ 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) {})
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 2)
+
+ for _, ep := range endpoints {
+ require.Len(t, ep.Security, 1)
+ }
+ assert.Equal(t, "/a", endpoints[0].Pattern)
+ 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()
+
+ middlewareCalled := false
+ r.Use(func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ middlewareCalled = true
+ next.ServeHTTP(w, r)
+ })
+ })
+
+ r.Get("/test", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/test", http.NoBody)
+ rec := httptest.NewRecorder()
+
+ r.ServeHTTP(rec, req)
+
+ assert.True(t, middlewareCalled)
+ assert.Equal(t, http.StatusOK, rec.Code)
+}
+
+func TestRouter_With(t *testing.T) {
+ r := NewRouter()
+
+ middlewareCalled := false
+ withRouter := r.With(func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ middlewareCalled = true
+ next.ServeHTTP(w, r)
+ })
+ })
+
+ // Original router
+ r.Get("/original", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ // Router with middleware
+ withRouter.Get("/with-middleware", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+
+ // Test original - middleware should NOT be called
+ req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/original", http.NoBody)
+ rec := httptest.NewRecorder()
+ r.ServeHTTP(rec, req)
+ assert.False(t, middlewareCalled)
+
+ // Test with middleware
+ req = httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/with-middleware", http.NoBody)
+ rec = httptest.NewRecorder()
+ r.ServeHTTP(rec, req)
+ assert.True(t, middlewareCalled)
+}
+
+// --- Mount ---
+
+func TestRouter_Mount(t *testing.T) {
+ r := NewRouter()
+
+ sub := NewRouter()
+ sub.Get("/users", func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte("users"))
+ })
+
+ r.Mount("/api/v1", sub)
+
+ // Test routing
+ 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))
+
+ // Check endpoints are collected with prefix
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+ 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_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
+}
+
+func (r *TestResponse) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "id": String(&r.ID).Required(),
+ "name": String(&r.Name).Required(),
+ })
+}
+
+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)
+}
+
+// --- Multiple Methods Same Path ---
+
+func TestRouter_MultipleMethods(t *testing.T) {
+ r := NewRouter()
+
+ 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"))
+ })
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 4)
+
+ methods := make(map[string]bool)
+ for _, ep := range endpoints {
+ methods[ep.Method] = true
+ }
+
+ assert.True(t, methods[http.MethodGet])
+ assert.True(t, methods[http.MethodPost])
+ assert.True(t, methods[http.MethodPut])
+ assert.True(t, methods[http.MethodDelete])
+}
+
+// --- Security with Scopes ---
+
+func TestRouter_SecurityWithScopes(t *testing.T) {
+ r := NewRouter()
+
+ r.Get("/admin", func(w http.ResponseWriter, r *http.Request) {},
+ WithSecurityRequirements(
+ NewSecurity("oauth2", "read:admin", "write:admin"),
+ ),
+ )
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+
+ ep := endpoints[0]
+ require.Len(t, ep.Security, 1)
+ reqs := ep.Security[0].Requirements()
+ require.Len(t, reqs, 1)
+ assert.Equal(t, "oauth2", reqs[0].Scheme)
+ assert.Equal(t, []string{"read:admin", "write:admin"}, reqs[0].Scopes)
+}
+
+func TestRouter_MultipleSecurityOptions(t *testing.T) {
+ r := NewRouter()
+
+ r.Get("/flexible", func(w http.ResponseWriter, r *http.Request) {},
+ WithSecurityRequirements(
+ NewSecurity("jwt"),
+ NewSecurity("api_key"),
+ ),
+ )
+
+ endpoints := r.Endpoints()
+ require.Len(t, endpoints, 1)
+
+ 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.go
new file mode 100644
index 0000000000..183c568617
--- /dev/null
+++ b/backend-go/pkg/api/schema.go
@@ -0,0 +1,1697 @@
+package api
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/mail"
+ "net/url"
+ "regexp"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// SchemaProvider is implemented by request/response types to provide their schema
+type SchemaProvider interface {
+ Schema() *ObjectSchema
+}
+
+// ParamSource indicates where a parameter value comes from
+type ParamSource int
+
+const (
+ // SourceBody is the default - value comes from JSON request body
+ SourceBody ParamSource = iota
+ // SourcePath - value comes from URL path parameter (e.g., /users/{id})
+ SourcePath
+ // SourceQuery - value comes from URL query string (e.g., ?limit=10)
+ SourceQuery
+ // SourceHeader - value comes from HTTP header
+ SourceHeader
+ // SourceCookie - value comes from HTTP cookie
+ SourceCookie
+)
+
+// Schema is the interface all schema types implement
+type Schema interface {
+ // Validate validates the bound value and returns validation errors
+ Validate() []ValidationError
+
+ // OpenAPI returns the OpenAPI schema representation
+ OpenAPI() map[string]any
+
+ // IsRequired returns whether this field is required
+ IsRequired() bool
+
+ // IsPresent returns whether the bound value is present (non-nil, non-zero)
+ // Used by OneOf/AnyOf to determine which variant is active
+ IsPresent() bool
+
+ // GetSource returns where this parameter value comes from (Body by default)
+ GetSource() ParamSource
+}
+
+// ValidationError represents a single validation error
+type ValidationError struct {
+ Field string `json:"field"`
+ Message string `json:"message"`
+ Code string `json:"code"`
+}
+
+func (e ValidationError) Error() string {
+ if e.Field != "" {
+ return fmt.Sprintf("%s: %s", e.Field, e.Message)
+ }
+ return e.Message
+}
+
+// ValidationErrors is a collection of validation errors
+type ValidationErrors []ValidationError
+
+func (e ValidationErrors) Error() string {
+ if len(e) == 0 {
+ return ""
+ }
+ if len(e) == 1 {
+ return e[0].Error()
+ }
+ var sb strings.Builder
+ sb.WriteString("validation failed: ")
+ for i, err := range e {
+ if i > 0 {
+ sb.WriteString("; ")
+ }
+ sb.WriteString(err.Error())
+ }
+ return sb.String()
+}
+
+// HasErrors returns true if there are any validation errors
+func (e ValidationErrors) HasErrors() bool {
+ return len(e) > 0
+}
+
+// --- String Schema ---
+
+type StringSchema struct {
+ ptr *string
+ required bool
+ minLength *int
+ maxLength *int
+ pattern *regexp.Regexp
+ patternStr string
+ enum []string
+ format string
+ defaultVal *string
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ source ParamSource
+}
+
+func String(ptr *string) *StringSchema {
+ return &StringSchema{ptr: ptr}
+}
+
+// From sets the parameter source (Path, Query, Header, Cookie). Default is Body.
+func (s *StringSchema) From(source ParamSource) *StringSchema {
+ s.source = source
+ return s
+}
+
+func (s *StringSchema) GetSource() ParamSource {
+ return s.source
+}
+
+func (s *StringSchema) Required() *StringSchema {
+ s.required = true
+ return s
+}
+
+func (s *StringSchema) Optional() *StringSchema {
+ s.required = false
+ return s
+}
+
+func (s *StringSchema) MinLength(n int) *StringSchema {
+ s.minLength = &n
+ return s
+}
+
+func (s *StringSchema) MaxLength(n int) *StringSchema {
+ s.maxLength = &n
+ return s
+}
+
+func (s *StringSchema) Length(minLen, maxLen int) *StringSchema {
+ s.minLength = &minLen
+ s.maxLength = &maxLen
+ return s
+}
+
+// Pattern sets a regex pattern for validation. Panics on invalid regex.
+// For runtime-built patterns from config, use TryPattern instead.
+func (s *StringSchema) Pattern(pattern string) *StringSchema {
+ s.patternStr = pattern
+ s.pattern = regexp.MustCompile(pattern)
+ return s
+}
+
+// TryPattern sets a regex pattern for validation, returning an error if invalid.
+// Use this when patterns come from config or user input.
+func (s *StringSchema) TryPattern(pattern string) (*StringSchema, error) {
+ compiled, err := regexp.Compile(pattern)
+ if err != nil {
+ return s, err
+ }
+ s.patternStr = pattern
+ s.pattern = compiled
+ return s, nil
+}
+
+// PatternCompiled sets a pre-compiled regex pattern for validation.
+func (s *StringSchema) PatternCompiled(pattern *regexp.Regexp) *StringSchema {
+ s.pattern = pattern
+ if pattern != nil {
+ s.patternStr = pattern.String()
+ }
+ return s
+}
+
+func (s *StringSchema) Enum(values ...string) *StringSchema {
+ s.enum = values
+ return s
+}
+
+func (s *StringSchema) Format(format string) *StringSchema {
+ s.format = format
+ return s
+}
+
+// Email sets email format validation using RFC 5322 parsing.
+// Note: This accepts RFC-compliant addresses including comments, quoted local-parts,
+// and dotless domains (e.g., "user@localhost"). For stricter internet email validation,
+// use EmailStrict().
+func (s *StringSchema) Email() *StringSchema {
+ s.format = "email"
+ return s
+}
+
+// EmailStrict sets strict email format validation requiring:
+// - An @ symbol with local and domain parts
+// - Domain must contain at least one dot (e.g., "[email protected]")
+// Use this for public-facing forms expecting internet email addresses.
+func (s *StringSchema) EmailStrict() *StringSchema {
+ s.format = "email-strict"
+ return s
+}
+
+// URI sets URI format validation. Accepts any valid URI including relative paths.
+// For absolute URLs with scheme (http/https), use URL() instead.
+func (s *StringSchema) URI() *StringSchema {
+ s.format = "uri"
+ return s
+}
+
+// URL sets absolute URL format validation requiring a scheme (http, https, etc.)
+// and host. Use this for webhook URLs, redirect URIs, etc.
+func (s *StringSchema) URL() *StringSchema {
+ s.format = "url"
+ return s
+}
+
+func (s *StringSchema) UUID() *StringSchema {
+ s.format = "uuid"
+ return s
+}
+
+func (s *StringSchema) DateTime() *StringSchema {
+ s.format = "date-time"
+ return s
+}
+
+func (s *StringSchema) Date() *StringSchema {
+ s.format = "date"
+ return s
+}
+
+func (s *StringSchema) Password() *StringSchema {
+ s.format = "password"
+ return s
+}
+
+func (s *StringSchema) Default(val string) *StringSchema {
+ s.defaultVal = &val
+ return s
+}
+
+func (s *StringSchema) Example(val any) *StringSchema {
+ s.example = val
+ return s
+}
+
+func (s *StringSchema) Title(val string) *StringSchema {
+ s.title = val
+ return s
+}
+
+func (s *StringSchema) Description(val string) *StringSchema {
+ s.description = val
+ return s
+}
+
+func (s *StringSchema) Deprecated() *StringSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *StringSchema) Nullable() *StringSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *StringSchema) ReadOnly() *StringSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *StringSchema) WriteOnly() *StringSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *StringSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *StringSchema) IsPresent() bool {
+ return s.ptr != nil && *s.ptr != ""
+}
+
+func (s *StringSchema) Validate() []ValidationError {
+ var errs []ValidationError
+ val := ""
+ if s.ptr != nil {
+ val = *s.ptr
+ }
+
+ if val == "" {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ return errs
+ }
+
+ if s.minLength != nil && len(val) < *s.minLength {
+ errs = append(errs, ValidationError{
+ Code: "min_length",
+ Message: fmt.Sprintf("must be at least %d characters", *s.minLength),
+ })
+ }
+
+ if s.maxLength != nil && len(val) > *s.maxLength {
+ errs = append(errs, ValidationError{
+ Code: "max_length",
+ Message: fmt.Sprintf("must be at most %d characters", *s.maxLength),
+ })
+ }
+
+ if s.pattern != nil && !s.pattern.MatchString(val) {
+ errs = append(errs, ValidationError{
+ Code: "pattern",
+ Message: fmt.Sprintf("must match pattern %s", s.patternStr),
+ })
+ }
+
+ if len(s.enum) > 0 {
+ found := slices.Contains(s.enum, val)
+ if !found {
+ errs = append(errs, ValidationError{
+ Code: "enum",
+ Message: fmt.Sprintf("must be one of: %s", strings.Join(s.enum, ", ")),
+ })
+ }
+ }
+
+ if s.format != "" {
+ if err := validateStringFormat(val, s.format); err != nil {
+ errs = append(errs, ValidationError{Code: "format", Message: err.Error()})
+ }
+ }
+
+ return errs
+}
+
+func validateStringFormat(val, format string) error {
+ switch format {
+ case "email":
+ if _, err := mail.ParseAddress(val); err != nil {
+ return fmt.Errorf("must be a valid email address")
+ }
+ case "email-strict":
+ addr, err := mail.ParseAddress(val)
+ if err != nil {
+ return fmt.Errorf("must be a valid email address")
+ }
+ // Require @ and domain with at least one dot
+ parts := strings.SplitN(addr.Address, "@", 2)
+ if len(parts) != 2 || !strings.Contains(parts[1], ".") {
+ return fmt.Errorf("must be a valid internet email address (e.g., [email protected])")
+ }
+ case "uri":
+ if _, err := url.ParseRequestURI(val); err != nil {
+ return fmt.Errorf("must be a valid URI")
+ }
+ case "url":
+ parsed, err := url.Parse(val)
+ if err != nil {
+ return fmt.Errorf("must be a valid URL")
+ }
+ if parsed.Scheme == "" {
+ return fmt.Errorf("must be an absolute URL with scheme (e.g., https://example.com)")
+ }
+ if parsed.Host == "" {
+ return fmt.Errorf("must be an absolute URL with host")
+ }
+ case "uuid":
+ if _, err := uuid.Parse(val); err != nil {
+ return fmt.Errorf("must be a valid UUID")
+ }
+ case "date-time":
+ if _, err := time.Parse(time.RFC3339, val); err != nil {
+ return fmt.Errorf("must be a valid RFC3339 date-time")
+ }
+ case "date":
+ if _, err := time.Parse("2006-01-02", val); err != nil {
+ return fmt.Errorf("must be a valid date (YYYY-MM-DD)")
+ }
+ }
+ return nil
+}
+
+func (s *StringSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "string"}
+
+ if s.minLength != nil {
+ schema["minLength"] = *s.minLength
+ }
+ if s.maxLength != nil {
+ schema["maxLength"] = *s.maxLength
+ }
+ if s.patternStr != "" {
+ schema["pattern"] = s.patternStr
+ }
+ if len(s.enum) > 0 {
+ schema["enum"] = s.enum
+ }
+ if s.format != "" {
+ schema["format"] = s.format
+ }
+ if s.defaultVal != nil {
+ schema["default"] = *s.defaultVal
+ }
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- Int Schema ---
+
+type IntSchema struct {
+ ptr *int
+ ptr64 *int64
+ required bool
+ minimum *int64
+ maximum *int64
+ exclusiveMinimum *int64
+ exclusiveMaximum *int64
+ multipleOf *int64
+ enum []int64
+ defaultVal *int64
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ source ParamSource
+}
+
+func Int(ptr *int) *IntSchema {
+ return &IntSchema{ptr: ptr}
+}
+
+func Int64(ptr *int64) *IntSchema {
+ return &IntSchema{ptr64: ptr}
+}
+
+func (s *IntSchema) From(source ParamSource) *IntSchema {
+ s.source = source
+ return s
+}
+
+func (s *IntSchema) GetSource() ParamSource {
+ return s.source
+}
+
+func (s *IntSchema) Required() *IntSchema {
+ s.required = true
+ return s
+}
+
+func (s *IntSchema) Optional() *IntSchema {
+ s.required = false
+ return s
+}
+
+func (s *IntSchema) Min(n int64) *IntSchema {
+ s.minimum = &n
+ return s
+}
+
+func (s *IntSchema) Max(n int64) *IntSchema {
+ s.maximum = &n
+ return s
+}
+
+func (s *IntSchema) Range(minVal, maxVal int64) *IntSchema {
+ s.minimum = &minVal
+ s.maximum = &maxVal
+ return s
+}
+
+func (s *IntSchema) ExclusiveMin(n int64) *IntSchema {
+ s.exclusiveMinimum = &n
+ return s
+}
+
+func (s *IntSchema) ExclusiveMax(n int64) *IntSchema {
+ s.exclusiveMaximum = &n
+ return s
+}
+
+func (s *IntSchema) MultipleOf(n int64) *IntSchema {
+ s.multipleOf = &n
+ return s
+}
+
+func (s *IntSchema) Enum(values ...int64) *IntSchema {
+ s.enum = values
+ return s
+}
+
+func (s *IntSchema) Default(val int64) *IntSchema {
+ s.defaultVal = &val
+ return s
+}
+
+func (s *IntSchema) Example(val any) *IntSchema {
+ s.example = val
+ return s
+}
+
+func (s *IntSchema) Title(val string) *IntSchema {
+ s.title = val
+ return s
+}
+
+func (s *IntSchema) Description(val string) *IntSchema {
+ s.description = val
+ return s
+}
+
+func (s *IntSchema) Deprecated() *IntSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *IntSchema) Nullable() *IntSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *IntSchema) ReadOnly() *IntSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *IntSchema) WriteOnly() *IntSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *IntSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *IntSchema) IsPresent() bool {
+ return s.ptr != nil || s.ptr64 != nil
+}
+
+func (s *IntSchema) value() (int64, bool) {
+ if s.ptr != nil {
+ return int64(*s.ptr), true
+ }
+ if s.ptr64 != nil {
+ return *s.ptr64, true
+ }
+ return 0, false
+}
+
+func (s *IntSchema) Validate() []ValidationError {
+ var errs []ValidationError
+
+ // ptr == nil means the value was not provided (distinct from value being 0)
+ if s.ptr == nil && s.ptr64 == nil {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ return errs
+ }
+
+ val, _ := s.value()
+
+ if s.minimum != nil && val < *s.minimum {
+ errs = append(errs, ValidationError{
+ Code: "minimum",
+ Message: fmt.Sprintf("must be at least %d", *s.minimum),
+ })
+ }
+
+ if s.maximum != nil && val > *s.maximum {
+ errs = append(errs, ValidationError{
+ Code: "maximum",
+ Message: fmt.Sprintf("must be at most %d", *s.maximum),
+ })
+ }
+
+ if s.exclusiveMinimum != nil && val <= *s.exclusiveMinimum {
+ errs = append(errs, ValidationError{
+ Code: "exclusive_minimum",
+ Message: fmt.Sprintf("must be greater than %d", *s.exclusiveMinimum),
+ })
+ }
+
+ if s.exclusiveMaximum != nil && val >= *s.exclusiveMaximum {
+ errs = append(errs, ValidationError{
+ Code: "exclusive_maximum",
+ Message: fmt.Sprintf("must be less than %d", *s.exclusiveMaximum),
+ })
+ }
+
+ if s.multipleOf != nil && val%*s.multipleOf != 0 {
+ errs = append(errs, ValidationError{
+ Code: "multiple_of",
+ Message: fmt.Sprintf("must be a multiple of %d", *s.multipleOf),
+ })
+ }
+
+ if len(s.enum) > 0 {
+ found := slices.Contains(s.enum, val)
+ if !found {
+ errs = append(errs, ValidationError{
+ Code: "enum",
+ Message: "must be one of the allowed values",
+ })
+ }
+ }
+
+ return errs
+}
+
+func (s *IntSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "integer", "format": "int64"}
+
+ if s.minimum != nil {
+ schema["minimum"] = *s.minimum
+ }
+ if s.maximum != nil {
+ schema["maximum"] = *s.maximum
+ }
+ if s.exclusiveMinimum != nil {
+ schema["exclusiveMinimum"] = *s.exclusiveMinimum
+ }
+ if s.exclusiveMaximum != nil {
+ schema["exclusiveMaximum"] = *s.exclusiveMaximum
+ }
+ if s.multipleOf != nil {
+ schema["multipleOf"] = *s.multipleOf
+ }
+ if len(s.enum) > 0 {
+ schema["enum"] = s.enum
+ }
+ if s.defaultVal != nil {
+ schema["default"] = *s.defaultVal
+ }
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- Float Schema ---
+
+type FloatSchema struct {
+ ptr *float64
+ required bool
+ minimum *float64
+ maximum *float64
+ exclusiveMinimum *float64
+ exclusiveMaximum *float64
+ multipleOf *float64
+ defaultVal *float64
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ source ParamSource
+}
+
+func Float(ptr *float64) *FloatSchema {
+ return &FloatSchema{ptr: ptr}
+}
+
+func (s *FloatSchema) From(source ParamSource) *FloatSchema {
+ s.source = source
+ return s
+}
+
+func (s *FloatSchema) GetSource() ParamSource {
+ return s.source
+}
+
+func (s *FloatSchema) Required() *FloatSchema {
+ s.required = true
+ return s
+}
+
+func (s *FloatSchema) Optional() *FloatSchema {
+ s.required = false
+ return s
+}
+
+func (s *FloatSchema) Min(n float64) *FloatSchema {
+ s.minimum = &n
+ return s
+}
+
+func (s *FloatSchema) Max(n float64) *FloatSchema {
+ s.maximum = &n
+ return s
+}
+
+func (s *FloatSchema) Range(minVal, maxVal float64) *FloatSchema {
+ s.minimum = &minVal
+ s.maximum = &maxVal
+ return s
+}
+
+func (s *FloatSchema) ExclusiveMin(n float64) *FloatSchema {
+ s.exclusiveMinimum = &n
+ return s
+}
+
+func (s *FloatSchema) ExclusiveMax(n float64) *FloatSchema {
+ s.exclusiveMaximum = &n
+ return s
+}
+
+func (s *FloatSchema) MultipleOf(n float64) *FloatSchema {
+ s.multipleOf = &n
+ return s
+}
+
+func (s *FloatSchema) Default(val float64) *FloatSchema {
+ s.defaultVal = &val
+ return s
+}
+
+func (s *FloatSchema) Example(val any) *FloatSchema {
+ s.example = val
+ return s
+}
+
+func (s *FloatSchema) Title(val string) *FloatSchema {
+ s.title = val
+ return s
+}
+
+func (s *FloatSchema) Description(val string) *FloatSchema {
+ s.description = val
+ return s
+}
+
+func (s *FloatSchema) Deprecated() *FloatSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *FloatSchema) Nullable() *FloatSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *FloatSchema) ReadOnly() *FloatSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *FloatSchema) WriteOnly() *FloatSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *FloatSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *FloatSchema) IsPresent() bool {
+ return s.ptr != nil
+}
+
+func (s *FloatSchema) Validate() []ValidationError {
+ var errs []ValidationError
+
+ // ptr == nil means the value was not provided (distinct from value being 0)
+ if s.ptr == nil {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ return errs
+ }
+
+ val := *s.ptr
+
+ if s.minimum != nil && val < *s.minimum {
+ errs = append(errs, ValidationError{
+ Code: "minimum",
+ Message: fmt.Sprintf("must be at least %v", *s.minimum),
+ })
+ }
+
+ if s.maximum != nil && val > *s.maximum {
+ errs = append(errs, ValidationError{
+ Code: "maximum",
+ Message: fmt.Sprintf("must be at most %v", *s.maximum),
+ })
+ }
+
+ if s.exclusiveMinimum != nil && val <= *s.exclusiveMinimum {
+ errs = append(errs, ValidationError{
+ Code: "exclusive_minimum",
+ Message: fmt.Sprintf("must be greater than %v", *s.exclusiveMinimum),
+ })
+ }
+
+ if s.exclusiveMaximum != nil && val >= *s.exclusiveMaximum {
+ errs = append(errs, ValidationError{
+ Code: "exclusive_maximum",
+ Message: fmt.Sprintf("must be less than %v", *s.exclusiveMaximum),
+ })
+ }
+
+ return errs
+}
+
+func (s *FloatSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "number", "format": "double"}
+
+ if s.minimum != nil {
+ schema["minimum"] = *s.minimum
+ }
+ if s.maximum != nil {
+ schema["maximum"] = *s.maximum
+ }
+ if s.exclusiveMinimum != nil {
+ schema["exclusiveMinimum"] = *s.exclusiveMinimum
+ }
+ if s.exclusiveMaximum != nil {
+ schema["exclusiveMaximum"] = *s.exclusiveMaximum
+ }
+ if s.multipleOf != nil {
+ schema["multipleOf"] = *s.multipleOf
+ }
+ if s.defaultVal != nil {
+ schema["default"] = *s.defaultVal
+ }
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- Bool Schema ---
+
+type BoolSchema struct {
+ ptr *bool
+ required bool
+ defaultVal *bool
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ source ParamSource
+}
+
+func Bool(ptr *bool) *BoolSchema {
+ return &BoolSchema{ptr: ptr}
+}
+
+func (s *BoolSchema) From(source ParamSource) *BoolSchema {
+ s.source = source
+ return s
+}
+
+func (s *BoolSchema) GetSource() ParamSource {
+ return s.source
+}
+
+func (s *BoolSchema) Required() *BoolSchema {
+ s.required = true
+ return s
+}
+
+func (s *BoolSchema) Optional() *BoolSchema {
+ s.required = false
+ return s
+}
+
+func (s *BoolSchema) Default(val bool) *BoolSchema {
+ s.defaultVal = &val
+ return s
+}
+
+func (s *BoolSchema) Example(val any) *BoolSchema {
+ s.example = val
+ return s
+}
+
+func (s *BoolSchema) Title(val string) *BoolSchema {
+ s.title = val
+ return s
+}
+
+func (s *BoolSchema) Description(val string) *BoolSchema {
+ s.description = val
+ return s
+}
+
+func (s *BoolSchema) Deprecated() *BoolSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *BoolSchema) Nullable() *BoolSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *BoolSchema) ReadOnly() *BoolSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *BoolSchema) WriteOnly() *BoolSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *BoolSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *BoolSchema) IsPresent() bool {
+ return s.ptr != nil
+}
+
+func (s *BoolSchema) Validate() []ValidationError {
+ var errs []ValidationError
+
+ // ptr == nil means the value was not provided (distinct from value being false)
+ if s.ptr == nil {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ }
+
+ return errs
+}
+
+func (s *BoolSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "boolean"}
+
+ if s.defaultVal != nil {
+ schema["default"] = *s.defaultVal
+ }
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- UUID Schema ---
+
+type UUIDSchema struct {
+ ptr *uuid.UUID
+ required bool
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ source ParamSource
+}
+
+func UUID(ptr *uuid.UUID) *UUIDSchema {
+ return &UUIDSchema{ptr: ptr}
+}
+
+func (s *UUIDSchema) From(source ParamSource) *UUIDSchema {
+ s.source = source
+ return s
+}
+
+func (s *UUIDSchema) GetSource() ParamSource {
+ return s.source
+}
+
+func (s *UUIDSchema) Required() *UUIDSchema {
+ s.required = true
+ return s
+}
+
+func (s *UUIDSchema) Optional() *UUIDSchema {
+ s.required = false
+ return s
+}
+
+func (s *UUIDSchema) Example(val any) *UUIDSchema {
+ s.example = val
+ return s
+}
+
+func (s *UUIDSchema) Title(val string) *UUIDSchema {
+ s.title = val
+ return s
+}
+
+func (s *UUIDSchema) Description(val string) *UUIDSchema {
+ s.description = val
+ return s
+}
+
+func (s *UUIDSchema) Deprecated() *UUIDSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *UUIDSchema) Nullable() *UUIDSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *UUIDSchema) ReadOnly() *UUIDSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *UUIDSchema) WriteOnly() *UUIDSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *UUIDSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *UUIDSchema) IsPresent() bool {
+ return s.ptr != nil && *s.ptr != uuid.Nil
+}
+
+func (s *UUIDSchema) Validate() []ValidationError {
+ var errs []ValidationError
+
+ if s.ptr == nil || *s.ptr == uuid.Nil {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ }
+
+ return errs
+}
+
+func (s *UUIDSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "string", "format": "uuid"}
+
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- Time Schema ---
+
+type TimeSchema struct {
+ ptr *time.Time
+ required bool
+ format string // "date-time", "date", "time"
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ source ParamSource
+}
+
+func Time(ptr *time.Time) *TimeSchema {
+ return &TimeSchema{ptr: ptr, format: "date-time"}
+}
+
+func (s *TimeSchema) From(source ParamSource) *TimeSchema {
+ s.source = source
+ return s
+}
+
+func (s *TimeSchema) GetSource() ParamSource {
+ return s.source
+}
+
+func (s *TimeSchema) Required() *TimeSchema {
+ s.required = true
+ return s
+}
+
+func (s *TimeSchema) Optional() *TimeSchema {
+ s.required = false
+ return s
+}
+
+func (s *TimeSchema) DateOnly() *TimeSchema {
+ s.format = "date"
+ return s
+}
+
+func (s *TimeSchema) TimeOnly() *TimeSchema {
+ s.format = "time"
+ return s
+}
+
+func (s *TimeSchema) Example(val any) *TimeSchema {
+ s.example = val
+ return s
+}
+
+func (s *TimeSchema) Title(val string) *TimeSchema {
+ s.title = val
+ return s
+}
+
+func (s *TimeSchema) Description(val string) *TimeSchema {
+ s.description = val
+ return s
+}
+
+func (s *TimeSchema) Deprecated() *TimeSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *TimeSchema) Nullable() *TimeSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *TimeSchema) ReadOnly() *TimeSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *TimeSchema) WriteOnly() *TimeSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *TimeSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *TimeSchema) IsPresent() bool {
+ return s.ptr != nil && !s.ptr.IsZero()
+}
+
+func (s *TimeSchema) Validate() []ValidationError {
+ var errs []ValidationError
+
+ if s.ptr == nil || s.ptr.IsZero() {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ }
+
+ return errs
+}
+
+func (s *TimeSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "string", "format": s.format}
+
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- Bytes Schema ---
+
+type BytesSchema struct {
+ ptr *[]byte
+ required bool
+ minLength *int
+ maxLength *int
+ format string // "byte" (base64), "binary"
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ source ParamSource
+}
+
+func Bytes(ptr *[]byte) *BytesSchema {
+ return &BytesSchema{ptr: ptr, format: "byte"}
+}
+
+func (s *BytesSchema) From(source ParamSource) *BytesSchema {
+ s.source = source
+ return s
+}
+
+func (s *BytesSchema) GetSource() ParamSource {
+ return s.source
+}
+
+func (s *BytesSchema) Required() *BytesSchema {
+ s.required = true
+ return s
+}
+
+func (s *BytesSchema) Optional() *BytesSchema {
+ s.required = false
+ return s
+}
+
+func (s *BytesSchema) MinLength(n int) *BytesSchema {
+ s.minLength = &n
+ return s
+}
+
+func (s *BytesSchema) MaxLength(n int) *BytesSchema {
+ s.maxLength = &n
+ return s
+}
+
+func (s *BytesSchema) Binary() *BytesSchema {
+ s.format = "binary"
+ return s
+}
+
+func (s *BytesSchema) Example(val any) *BytesSchema {
+ s.example = val
+ return s
+}
+
+func (s *BytesSchema) Title(val string) *BytesSchema {
+ s.title = val
+ return s
+}
+
+func (s *BytesSchema) Description(val string) *BytesSchema {
+ s.description = val
+ return s
+}
+
+func (s *BytesSchema) Deprecated() *BytesSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *BytesSchema) Nullable() *BytesSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *BytesSchema) ReadOnly() *BytesSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *BytesSchema) WriteOnly() *BytesSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *BytesSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *BytesSchema) IsPresent() bool {
+ return s.ptr != nil && len(*s.ptr) > 0
+}
+
+func (s *BytesSchema) Validate() []ValidationError {
+ var errs []ValidationError
+
+ if s.ptr == nil || len(*s.ptr) == 0 {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ return errs
+ }
+
+ val := *s.ptr
+
+ if s.minLength != nil && len(val) < *s.minLength {
+ errs = append(errs, ValidationError{
+ Code: "min_length",
+ Message: fmt.Sprintf("must be at least %d bytes", *s.minLength),
+ })
+ }
+
+ if s.maxLength != nil && len(val) > *s.maxLength {
+ errs = append(errs, ValidationError{
+ Code: "max_length",
+ Message: fmt.Sprintf("must be at most %d bytes", *s.maxLength),
+ })
+ }
+
+ return errs
+}
+
+func (s *BytesSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "string", "format": s.format}
+
+ if s.minLength != nil {
+ schema["minLength"] = *s.minLength
+ }
+ if s.maxLength != nil {
+ schema["maxLength"] = *s.maxLength
+ }
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- Any Schema (for free-form objects) ---
+
+type AnySchema struct {
+ ptr *any
+ required bool
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ source ParamSource
+}
+
+func Any(ptr *any) *AnySchema {
+ return &AnySchema{ptr: ptr}
+}
+
+func (s *AnySchema) From(source ParamSource) *AnySchema {
+ s.source = source
+ return s
+}
+
+func (s *AnySchema) GetSource() ParamSource {
+ return s.source
+}
+
+func (s *AnySchema) Required() *AnySchema {
+ s.required = true
+ return s
+}
+
+func (s *AnySchema) Optional() *AnySchema {
+ s.required = false
+ return s
+}
+
+func (s *AnySchema) Example(val any) *AnySchema {
+ s.example = val
+ return s
+}
+
+func (s *AnySchema) Title(val string) *AnySchema {
+ s.title = val
+ return s
+}
+
+func (s *AnySchema) Description(val string) *AnySchema {
+ s.description = val
+ return s
+}
+
+func (s *AnySchema) Deprecated() *AnySchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *AnySchema) Nullable() *AnySchema {
+ s.nullable = true
+ return s
+}
+
+func (s *AnySchema) ReadOnly() *AnySchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *AnySchema) WriteOnly() *AnySchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *AnySchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *AnySchema) IsPresent() bool {
+ return s.ptr != nil && *s.ptr != nil
+}
+
+func (s *AnySchema) Validate() []ValidationError {
+ var errs []ValidationError
+
+ if s.ptr == nil || *s.ptr == nil {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ }
+
+ return errs
+}
+
+func (s *AnySchema) OpenAPI() map[string]any {
+ schema := map[string]any{}
+
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- Raw JSON Schema (for json.RawMessage fields) ---
+
+type RawSchema struct {
+ ptr *json.RawMessage
+ required bool
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ source ParamSource
+}
+
+func Raw(ptr *json.RawMessage) *RawSchema {
+ return &RawSchema{ptr: ptr}
+}
+
+func (s *RawSchema) From(source ParamSource) *RawSchema {
+ s.source = source
+ return s
+}
+
+func (s *RawSchema) GetSource() ParamSource {
+ return s.source
+}
+
+func (s *RawSchema) Required() *RawSchema {
+ s.required = true
+ return s
+}
+
+func (s *RawSchema) Optional() *RawSchema {
+ s.required = false
+ return s
+}
+
+func (s *RawSchema) Example(val any) *RawSchema {
+ s.example = val
+ return s
+}
+
+func (s *RawSchema) Title(val string) *RawSchema {
+ s.title = val
+ return s
+}
+
+func (s *RawSchema) Description(val string) *RawSchema {
+ s.description = val
+ return s
+}
+
+func (s *RawSchema) Deprecated() *RawSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *RawSchema) Nullable() *RawSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *RawSchema) ReadOnly() *RawSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *RawSchema) WriteOnly() *RawSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *RawSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *RawSchema) IsPresent() bool {
+ return s.ptr != nil && len(*s.ptr) > 0
+}
+
+func (s *RawSchema) Validate() []ValidationError {
+ var errs []ValidationError
+
+ if s.ptr == nil || len(*s.ptr) == 0 {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ }
+
+ return errs
+}
+
+func (s *RawSchema) OpenAPI() map[string]any {
+ schema := map[string]any{}
+
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
diff --git a/backend-go/pkg/api/schema_composite.go b/backend-go/pkg/api/schema_composite.go
new file mode 100644
index 0000000000..6ff53f1930
--- /dev/null
+++ b/backend-go/pkg/api/schema_composite.go
@@ -0,0 +1,1118 @@
+package api
+
+import (
+ "encoding/json"
+ "fmt"
+)
+
+// --- Object Schema ---
+
+type ObjectSchema struct {
+ properties map[string]Schema
+ propertyOrder []string
+ required bool
+ additionalProps *bool
+ minProperties *int
+ maxProperties *int
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+ discriminator string
+ discriminatorMap map[string]string
+
+ // For root-level unions (body IS the union)
+ bodyUnion *bodyUnionConfig
+}
+
+// bodyUnionConfig holds configuration for root-level union bodies
+type bodyUnionConfig struct {
+ rawPtr any // *json.RawMessage
+ targetPtr any // *T where T is the union interface
+ parser any // UnionDef[T]
+ schema Schema // The union schema for OpenAPI/validation
+}
+
+func Object(fields map[string]Schema) *ObjectSchema {
+ order := make([]string, 0, len(fields))
+ for k := range fields {
+ order = append(order, k)
+ }
+ return &ObjectSchema{
+ properties: fields,
+ propertyOrder: order,
+ }
+}
+
+func (s *ObjectSchema) Required() *ObjectSchema {
+ s.required = true
+ return s
+}
+
+func (s *ObjectSchema) Optional() *ObjectSchema {
+ s.required = false
+ return s
+}
+
+// AdditionalProperties sets the OpenAPI additionalProperties field.
+// NOTE: This is OpenAPI metadata only — it does NOT enforce validation.
+// To reject unknown fields at parse time, use json.Decoder.DisallowUnknownFields():
+//
+// decoder := json.NewDecoder(r.Body)
+// decoder.DisallowUnknownFields()
+// if err := decoder.Decode(&req); err != nil { ... }
+func (s *ObjectSchema) AdditionalProperties(allow bool) *ObjectSchema {
+ s.additionalProps = &allow
+ return s
+}
+
+func (s *ObjectSchema) MinProperties(n int) *ObjectSchema {
+ s.minProperties = &n
+ return s
+}
+
+func (s *ObjectSchema) MaxProperties(n int) *ObjectSchema {
+ s.maxProperties = &n
+ return s
+}
+
+func (s *ObjectSchema) Example(val any) *ObjectSchema {
+ s.example = val
+ return s
+}
+
+func (s *ObjectSchema) Title(val string) *ObjectSchema {
+ s.title = val
+ return s
+}
+
+func (s *ObjectSchema) Description(val string) *ObjectSchema {
+ s.description = val
+ return s
+}
+
+func (s *ObjectSchema) Deprecated() *ObjectSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *ObjectSchema) Nullable() *ObjectSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *ObjectSchema) ReadOnly() *ObjectSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *ObjectSchema) WriteOnly() *ObjectSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *ObjectSchema) Discriminator(propertyName string, mapping map[string]string) *ObjectSchema {
+ s.discriminator = propertyName
+ s.discriminatorMap = mapping
+ return s
+}
+
+// HasBodyUnion returns true if this schema has a root-level body union configured
+func (s *ObjectSchema) HasBodyUnion() bool {
+ return s.bodyUnion != nil
+}
+
+// GetBodyUnionSchema returns the union schema for the body, or nil if not set
+func (s *ObjectSchema) GetBodyUnionSchema() Schema {
+ if s.bodyUnion != nil {
+ return s.bodyUnion.schema
+ }
+ return nil
+}
+
+// getBodyUnionRawPtr returns the raw JSON pointer for the body union
+func (s *ObjectSchema) getBodyUnionRawPtr() *json.RawMessage {
+ if s.bodyUnion != nil {
+ if rawPtr, ok := s.bodyUnion.rawPtr.(*json.RawMessage); ok {
+ return rawPtr
+ }
+ }
+ return nil
+}
+
+func (s *ObjectSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *ObjectSchema) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *ObjectSchema) IsPresent() bool {
+ // Object is present if any of its properties are present
+ for _, schema := range s.properties {
+ if schema.IsPresent() {
+ return true
+ }
+ }
+ return false
+}
+
+func (s *ObjectSchema) Validate() []ValidationError {
+ var errs []ValidationError
+
+ // Validate regular properties
+ for field, schema := range s.properties {
+ fieldErrs := schema.Validate()
+ for _, e := range fieldErrs {
+ inner := e.Field
+ if inner != "" {
+ e.Field = field + "." + inner
+ } else {
+ e.Field = field
+ }
+ errs = append(errs, e)
+ }
+ }
+
+ // Validate body union if present
+ if s.bodyUnion != nil && s.bodyUnion.schema != nil {
+ errs = append(errs, s.bodyUnion.schema.Validate()...)
+ }
+
+ return errs
+}
+
+func (s *ObjectSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "object"}
+
+ if len(s.properties) > 0 {
+ props := make(map[string]any)
+ var requiredFields []string
+
+ // Use propertyOrder for deterministic iteration
+ for _, field := range s.propertyOrder {
+ fieldSchema := s.properties[field]
+ props[field] = fieldSchema.OpenAPI()
+ if fieldSchema.IsRequired() {
+ requiredFields = append(requiredFields, field)
+ }
+ }
+
+ schema["properties"] = props
+ if len(requiredFields) > 0 {
+ schema["required"] = requiredFields
+ }
+ }
+
+ if s.additionalProps != nil {
+ schema["additionalProperties"] = *s.additionalProps
+ }
+ if s.minProperties != nil {
+ schema["minProperties"] = *s.minProperties
+ }
+ if s.maxProperties != nil {
+ schema["maxProperties"] = *s.maxProperties
+ }
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+ if s.discriminator != "" {
+ disc := map[string]any{"propertyName": s.discriminator}
+ if len(s.discriminatorMap) > 0 {
+ disc["mapping"] = s.discriminatorMap
+ }
+ schema["discriminator"] = disc
+ }
+
+ return schema
+}
+
+// --- Array Schema ---
+
+type ArraySchema struct {
+ items Schema
+ required bool
+ minItems *int
+ maxItems *int
+ uniqueItems bool
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+
+ validateFn func() []ValidationError
+ isPresentFn func() bool
+}
+
+func Array(items Schema) *ArraySchema {
+ return &ArraySchema{items: items}
+}
+
+func (s *ArraySchema) Required() *ArraySchema {
+ s.required = true
+ return s
+}
+
+func (s *ArraySchema) Optional() *ArraySchema {
+ s.required = false
+ return s
+}
+
+func (s *ArraySchema) MinItems(n int) *ArraySchema {
+ s.minItems = &n
+ return s
+}
+
+func (s *ArraySchema) MaxItems(n int) *ArraySchema {
+ s.maxItems = &n
+ return s
+}
+
+func (s *ArraySchema) UniqueItems() *ArraySchema {
+ s.uniqueItems = true
+ return s
+}
+
+func (s *ArraySchema) Example(val any) *ArraySchema {
+ s.example = val
+ return s
+}
+
+func (s *ArraySchema) Title(val string) *ArraySchema {
+ s.title = val
+ return s
+}
+
+func (s *ArraySchema) Description(val string) *ArraySchema {
+ s.description = val
+ return s
+}
+
+func (s *ArraySchema) Deprecated() *ArraySchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *ArraySchema) Nullable() *ArraySchema {
+ s.nullable = true
+ return s
+}
+
+func (s *ArraySchema) ReadOnly() *ArraySchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *ArraySchema) WriteOnly() *ArraySchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *ArraySchema) ValidateFn(fn func() []ValidationError) *ArraySchema {
+ s.validateFn = fn
+ return s
+}
+
+func (s *ArraySchema) IsPresentFn(fn func() bool) *ArraySchema {
+ s.isPresentFn = fn
+ return s
+}
+
+func (s *ArraySchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *ArraySchema) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *ArraySchema) IsPresent() bool {
+ if s.isPresentFn != nil {
+ return s.isPresentFn()
+ }
+ return false
+}
+
+func (s *ArraySchema) Validate() []ValidationError {
+ if s.validateFn != nil {
+ return s.validateFn()
+ }
+ return nil
+}
+
+func (s *ArraySchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "array"}
+
+ if s.items != nil {
+ schema["items"] = s.items.OpenAPI()
+ }
+ if s.minItems != nil {
+ schema["minItems"] = *s.minItems
+ }
+ if s.maxItems != nil {
+ schema["maxItems"] = *s.maxItems
+ }
+ if s.uniqueItems {
+ schema["uniqueItems"] = true
+ }
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- Map Schema (string keys, typed values) ---
+
+type MapSchema struct {
+ valueSchema Schema
+ required bool
+ minProps *int
+ maxProps *int
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+ readOnly bool
+ writeOnly bool
+
+ validateFn func() []ValidationError
+ isPresentFn func() bool
+}
+
+func Map(valueSchema Schema) *MapSchema {
+ return &MapSchema{valueSchema: valueSchema}
+}
+
+func (s *MapSchema) Required() *MapSchema {
+ s.required = true
+ return s
+}
+
+func (s *MapSchema) Optional() *MapSchema {
+ s.required = false
+ return s
+}
+
+func (s *MapSchema) MinProperties(n int) *MapSchema {
+ s.minProps = &n
+ return s
+}
+
+func (s *MapSchema) MaxProperties(n int) *MapSchema {
+ s.maxProps = &n
+ return s
+}
+
+func (s *MapSchema) Example(val any) *MapSchema {
+ s.example = val
+ return s
+}
+
+func (s *MapSchema) Title(val string) *MapSchema {
+ s.title = val
+ return s
+}
+
+func (s *MapSchema) Description(val string) *MapSchema {
+ s.description = val
+ return s
+}
+
+func (s *MapSchema) Deprecated() *MapSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *MapSchema) Nullable() *MapSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *MapSchema) ReadOnly() *MapSchema {
+ s.readOnly = true
+ return s
+}
+
+func (s *MapSchema) WriteOnly() *MapSchema {
+ s.writeOnly = true
+ return s
+}
+
+func (s *MapSchema) ValidateFn(fn func() []ValidationError) *MapSchema {
+ s.validateFn = fn
+ return s
+}
+
+func (s *MapSchema) IsPresentFn(fn func() bool) *MapSchema {
+ s.isPresentFn = fn
+ return s
+}
+
+func (s *MapSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *MapSchema) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *MapSchema) IsPresent() bool {
+ if s.isPresentFn != nil {
+ return s.isPresentFn()
+ }
+ return false
+}
+
+func (s *MapSchema) Validate() []ValidationError {
+ if s.validateFn != nil {
+ return s.validateFn()
+ }
+ return nil
+}
+
+func (s *MapSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"type": "object"}
+
+ if s.valueSchema != nil {
+ schema["additionalProperties"] = s.valueSchema.OpenAPI()
+ }
+ if s.minProps != nil {
+ schema["minProperties"] = *s.minProps
+ }
+ if s.maxProps != nil {
+ schema["maxProperties"] = *s.maxProps
+ }
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.readOnly {
+ schema["readOnly"] = true
+ }
+ if s.writeOnly {
+ schema["writeOnly"] = true
+ }
+
+ return schema
+}
+
+// --- OneOf Schema (discriminated union) ---
+
+type OneOfSchema struct {
+ // For discriminated union (with type field)
+ discriminator string
+ variants map[string]SchemaProvider
+ activeVariant *string // which variant is active (for validation)
+
+ // For simple oneOf (exactly one of these schemas must match)
+ schemas []Schema
+
+ required bool
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+
+ validateFn func() []ValidationError
+}
+
+// OneOf creates a discriminated union schema with a type discriminator.
+// For validation to work, call SetActiveVariant() with the discriminator value
+// after determining which variant is active (usually after JSON parsing).
+func OneOf(discriminator string, variants map[string]SchemaProvider) *OneOfSchema {
+ return &OneOfSchema{
+ discriminator: discriminator,
+ variants: variants,
+ }
+}
+
+// OneOfSchemas creates a oneOf schema where exactly one of the schemas must be present
+// Use this for "either A or B" patterns without a discriminator field
+func OneOfSchemas(schemas ...Schema) *OneOfSchema {
+ return &OneOfSchema{
+ schemas: schemas,
+ }
+}
+
+// SetActiveVariant sets which variant is active for discriminated oneOf validation.
+// Call this after JSON parsing with the value of the discriminator field.
+func (s *OneOfSchema) SetActiveVariant(variantKey string) *OneOfSchema {
+ s.activeVariant = &variantKey
+ return s
+}
+
+func (s *OneOfSchema) Required() *OneOfSchema {
+ s.required = true
+ return s
+}
+
+func (s *OneOfSchema) Optional() *OneOfSchema {
+ s.required = false
+ return s
+}
+
+func (s *OneOfSchema) Example(val any) *OneOfSchema {
+ s.example = val
+ return s
+}
+
+func (s *OneOfSchema) Title(val string) *OneOfSchema {
+ s.title = val
+ return s
+}
+
+func (s *OneOfSchema) Description(val string) *OneOfSchema {
+ s.description = val
+ return s
+}
+
+func (s *OneOfSchema) Deprecated() *OneOfSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *OneOfSchema) Nullable() *OneOfSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *OneOfSchema) ValidateFn(fn func() []ValidationError) *OneOfSchema {
+ s.validateFn = fn
+ return s
+}
+
+func (s *OneOfSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *OneOfSchema) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *OneOfSchema) IsPresent() bool {
+ // For simple oneOf, check if any schema is present
+ if len(s.schemas) > 0 {
+ for _, schema := range s.schemas {
+ if schema.IsPresent() {
+ return true
+ }
+ }
+ return false
+ }
+ // For discriminated oneOf, check if active variant is set
+ if s.discriminator != "" && s.activeVariant != nil {
+ if variant, ok := s.variants[*s.activeVariant]; ok {
+ return variant.Schema().IsPresent()
+ }
+ }
+ return false
+}
+
+func (s *OneOfSchema) Validate() []ValidationError {
+ if s.validateFn != nil {
+ return s.validateFn()
+ }
+
+ // For simple oneOf (schemas list), validate exactly one is present
+ if len(s.schemas) > 0 {
+ var presentSchemas []Schema
+ for _, schema := range s.schemas {
+ if schema.IsPresent() {
+ presentSchemas = append(presentSchemas, schema)
+ }
+ }
+
+ if len(presentSchemas) == 0 {
+ if s.required {
+ return []ValidationError{{Code: "oneOf", Message: "exactly one option must be provided"}}
+ }
+ return nil
+ }
+
+ if len(presentSchemas) > 1 {
+ return []ValidationError{{Code: "oneOf", Message: "only one option allowed, multiple provided"}}
+ }
+
+ // Validate the one that's present
+ return presentSchemas[0].Validate()
+ }
+
+ // For discriminated oneOf, validate the active variant if set
+ if s.discriminator != "" && len(s.variants) > 0 {
+ if s.activeVariant == nil {
+ if s.required {
+ return []ValidationError{{Code: "oneOf", Message: "discriminator value not set"}}
+ }
+ return nil
+ }
+
+ variant, ok := s.variants[*s.activeVariant]
+ if !ok {
+ return []ValidationError{{
+ Code: "oneOf",
+ Message: fmt.Sprintf("unknown %s value: %q", s.discriminator, *s.activeVariant),
+ }}
+ }
+
+ // Validate the active variant's schema
+ return variant.Schema().Validate()
+ }
+
+ return nil
+}
+
+func (s *OneOfSchema) OpenAPI() map[string]any {
+ var schema map[string]any
+
+ // Simple oneOf (without discriminator)
+ if len(s.schemas) > 0 {
+ oneOf := make([]map[string]any, 0, len(s.schemas))
+ for _, sch := range s.schemas {
+ oneOf = append(oneOf, sch.OpenAPI())
+ }
+ schema = map[string]any{"oneOf": oneOf}
+ } else {
+ // Discriminated oneOf with inline schemas
+ oneOf := make([]map[string]any, 0, len(s.variants))
+
+ for _, variant := range s.variants {
+ variantSchema := variant.Schema().OpenAPI()
+ oneOf = append(oneOf, variantSchema)
+ }
+
+ // Note: mapping is omitted when schemas are inline (not $ref).
+ // OpenAPI tooling can match variants by the discriminator property's
+ // enum/const value in each inline schema.
+ schema = map[string]any{
+ "oneOf": oneOf,
+ "discriminator": map[string]any{
+ "propertyName": s.discriminator,
+ },
+ }
+ }
+
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+
+ return schema
+}
+
+// --- AnyOf Schema ---
+
+type AnyOfSchema struct {
+ schemas []Schema
+ required bool
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+}
+
+func AnyOf(schemas ...Schema) *AnyOfSchema {
+ return &AnyOfSchema{schemas: schemas}
+}
+
+func (s *AnyOfSchema) Required() *AnyOfSchema {
+ s.required = true
+ return s
+}
+
+func (s *AnyOfSchema) Optional() *AnyOfSchema {
+ s.required = false
+ return s
+}
+
+func (s *AnyOfSchema) Example(val any) *AnyOfSchema {
+ s.example = val
+ return s
+}
+
+func (s *AnyOfSchema) Title(val string) *AnyOfSchema {
+ s.title = val
+ return s
+}
+
+func (s *AnyOfSchema) Description(val string) *AnyOfSchema {
+ s.description = val
+ return s
+}
+
+func (s *AnyOfSchema) Deprecated() *AnyOfSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *AnyOfSchema) Nullable() *AnyOfSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *AnyOfSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *AnyOfSchema) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *AnyOfSchema) IsPresent() bool {
+ for _, schema := range s.schemas {
+ if schema.IsPresent() {
+ return true
+ }
+ }
+ return false
+}
+
+func (s *AnyOfSchema) Validate() []ValidationError {
+ // Check if at least one schema is present
+ var presentSchemas []Schema
+ for _, schema := range s.schemas {
+ if schema.IsPresent() {
+ presentSchemas = append(presentSchemas, schema)
+ }
+ }
+
+ if len(presentSchemas) == 0 {
+ if s.required {
+ return []ValidationError{{Code: "anyOf", Message: "at least one option must be provided"}}
+ }
+ return nil
+ }
+
+ // Validate all that are present
+ var errs []ValidationError
+ for _, schema := range presentSchemas {
+ errs = append(errs, schema.Validate()...)
+ }
+ return errs
+}
+
+func (s *AnyOfSchema) OpenAPI() map[string]any {
+ anyOf := make([]map[string]any, 0, len(s.schemas))
+ for _, schema := range s.schemas {
+ anyOf = append(anyOf, schema.OpenAPI())
+ }
+
+ result := map[string]any{"anyOf": anyOf}
+
+ if s.example != nil {
+ result["example"] = s.example
+ }
+ if s.title != "" {
+ result["title"] = s.title
+ }
+ if s.description != "" {
+ result["description"] = s.description
+ }
+ if s.deprecated {
+ result["deprecated"] = true
+ }
+ if s.nullable {
+ result["nullable"] = true
+ }
+
+ return result
+}
+
+// --- AllOf Schema ---
+
+type AllOfSchema struct {
+ schemas []Schema
+ required bool
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+}
+
+func AllOf(schemas ...Schema) *AllOfSchema {
+ return &AllOfSchema{schemas: schemas}
+}
+
+func (s *AllOfSchema) Required() *AllOfSchema {
+ s.required = true
+ return s
+}
+
+func (s *AllOfSchema) Optional() *AllOfSchema {
+ s.required = false
+ return s
+}
+
+func (s *AllOfSchema) Example(val any) *AllOfSchema {
+ s.example = val
+ return s
+}
+
+func (s *AllOfSchema) Title(val string) *AllOfSchema {
+ s.title = val
+ return s
+}
+
+func (s *AllOfSchema) Description(val string) *AllOfSchema {
+ s.description = val
+ return s
+}
+
+func (s *AllOfSchema) Deprecated() *AllOfSchema {
+ s.deprecated = true
+ return s
+}
+
+func (s *AllOfSchema) Nullable() *AllOfSchema {
+ s.nullable = true
+ return s
+}
+
+func (s *AllOfSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *AllOfSchema) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *AllOfSchema) IsPresent() bool {
+ // AllOf is present if any of its schemas is present
+ for _, schema := range s.schemas {
+ if schema.IsPresent() {
+ return true
+ }
+ }
+ return false
+}
+
+func (s *AllOfSchema) Validate() []ValidationError {
+ var errs []ValidationError
+ for _, schema := range s.schemas {
+ errs = append(errs, schema.Validate()...)
+ }
+ return errs
+}
+
+func (s *AllOfSchema) OpenAPI() map[string]any {
+ allOf := make([]map[string]any, 0, len(s.schemas))
+ for _, schema := range s.schemas {
+ allOf = append(allOf, schema.OpenAPI())
+ }
+
+ result := map[string]any{"allOf": allOf}
+
+ if s.example != nil {
+ result["example"] = s.example
+ }
+ if s.title != "" {
+ result["title"] = s.title
+ }
+ if s.description != "" {
+ result["description"] = s.description
+ }
+ if s.deprecated {
+ result["deprecated"] = true
+ }
+ if s.nullable {
+ result["nullable"] = true
+ }
+
+ return result
+}
+
+// --- Ref Schema (for referencing other schemas) ---
+
+type RefSchema struct {
+ ref string
+ required bool
+ description string
+}
+
+func Ref(ref string) *RefSchema {
+ return &RefSchema{ref: ref}
+}
+
+func (s *RefSchema) Required() *RefSchema {
+ s.required = true
+ return s
+}
+
+func (s *RefSchema) Optional() *RefSchema {
+ s.required = false
+ return s
+}
+
+func (s *RefSchema) Description(val string) *RefSchema {
+ s.description = val
+ return s
+}
+
+func (s *RefSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *RefSchema) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *RefSchema) IsPresent() bool {
+ // Ref schemas don't have bound values, always return false
+ return false
+}
+
+func (s *RefSchema) Validate() []ValidationError {
+ return nil
+}
+
+func (s *RefSchema) OpenAPI() map[string]any {
+ schema := map[string]any{"$ref": s.ref}
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ return schema
+}
+
+// --- Const Schema (for fixed values) ---
+
+type ConstSchema struct {
+ value any
+ required bool
+ title string
+ description string
+}
+
+func Const(value any) *ConstSchema {
+ return &ConstSchema{value: value}
+}
+
+func (s *ConstSchema) Required() *ConstSchema {
+ s.required = true
+ return s
+}
+
+func (s *ConstSchema) Optional() *ConstSchema {
+ s.required = false
+ return s
+}
+
+func (s *ConstSchema) Title(val string) *ConstSchema {
+ s.title = val
+ return s
+}
+
+func (s *ConstSchema) Description(val string) *ConstSchema {
+ s.description = val
+ return s
+}
+
+func (s *ConstSchema) IsRequired() bool {
+ return s.required
+}
+
+func (s *ConstSchema) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *ConstSchema) IsPresent() bool {
+ // Const schemas have a fixed value, present if value is non-nil
+ return s.value != nil
+}
+
+func (s *ConstSchema) Validate() []ValidationError {
+ return nil
+}
+
+func (s *ConstSchema) OpenAPI() map[string]any {
+ // Use enum with single value for OpenAPI 3.0.x compatibility
+ // (const is only available in OpenAPI 3.1+)
+ schema := map[string]any{
+ "enum": []any{s.value},
+ }
+ switch s.value.(type) {
+ case string:
+ schema["type"] = "string"
+ case int, int32, int64:
+ schema["type"] = "integer"
+ case float32, float64:
+ schema["type"] = "number"
+ case bool:
+ schema["type"] = "boolean"
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ return schema
+}
diff --git a/backend-go/pkg/api/schema_composite_test.go b/backend-go/pkg/api/schema_composite_test.go
new file mode 100644
index 0000000000..8ef123b558
--- /dev/null
+++ b/backend-go/pkg/api/schema_composite_test.go
@@ -0,0 +1,580 @@
+package api
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// --- Object Schema Tests ---
+
+func TestObjectSchema_Validate(t *testing.T) {
+ var name string
+ var age *int
+
+ schema := Object(map[string]Schema{
+ "name": String(&name).Required().MinLength(1),
+ "age": Int(age).Required().Min(0), // nil pointer = missing
+ })
+
+ // Both fields missing - should have 2 errors
+ errs := schema.Validate()
+ require.Len(t, errs, 2)
+
+ // Set valid values
+ name = "John"
+ ageVal := 25
+ age = &ageVal
+ // Rebuild schema with new pointer
+ schema = Object(map[string]Schema{
+ "name": String(&name).Required().MinLength(1),
+ "age": Int(age).Required().Min(0),
+ })
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestObjectSchema_NestedValidation(t *testing.T) {
+ var street string
+ var city string
+
+ schema := Object(map[string]Schema{
+ "address": Object(map[string]Schema{
+ "street": String(&street).Required(),
+ "city": String(&city).Required(),
+ }),
+ })
+
+ errs := schema.Validate()
+ require.Len(t, errs, 2)
+
+ street = "123 Main St"
+ city = "NYC"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestObjectSchema_NestedFieldPaths(t *testing.T) {
+ // Issue #6: Nested validation error paths should be properly constructed
+ var email string
+
+ schema := Object(map[string]Schema{
+ "user": Object(map[string]Schema{
+ "profile": Object(map[string]Schema{
+ "email": String(&email).Required().Email(),
+ }),
+ }),
+ })
+
+ // Empty email should produce error with full path
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "user.profile.email", errs[0].Field)
+ assert.Equal(t, "required", errs[0].Code)
+
+ // Invalid email should produce error with full path
+ email = "not-an-email"
+ errs = schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "user.profile.email", errs[0].Field)
+ assert.Equal(t, "format", errs[0].Code)
+}
+
+func TestObjectSchema_NestedFieldPaths_MultipleErrors(t *testing.T) {
+ var name string
+
+ schema := Object(map[string]Schema{
+ "data": Object(map[string]Schema{
+ "name": String(&name).Required(),
+ "age": Int(nil).Required(), // nil pointer = missing
+ }),
+ })
+
+ errs := schema.Validate()
+ require.Len(t, errs, 2)
+
+ // Check both errors have correct paths
+ paths := make(map[string]bool)
+ for _, e := range errs {
+ paths[e.Field] = true
+ }
+ assert.True(t, paths["data.name"], "expected error for data.name")
+ assert.True(t, paths["data.age"], "expected error for data.age")
+}
+
+func TestObjectSchema_OpenAPI(t *testing.T) {
+ var name string
+ var email string
+
+ schema := Object(map[string]Schema{
+ "name": String(&name).Required().MinLength(1),
+ "email": String(&email).Required().Email(),
+ }).Title("User").Description("A user object").AdditionalProperties(false)
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "object", openapi["type"])
+ assert.Equal(t, "User", openapi["title"])
+ assert.Equal(t, "A user object", openapi["description"])
+ assert.Equal(t, false, openapi["additionalProperties"])
+
+ props := openapi["properties"].(map[string]any)
+ assert.Contains(t, props, "name")
+ assert.Contains(t, props, "email")
+
+ required := openapi["required"].([]string)
+ assert.Contains(t, required, "name")
+ assert.Contains(t, required, "email")
+}
+
+func TestObjectSchema_MinMaxProperties(t *testing.T) {
+ schema := Object(nil).MinProperties(1).MaxProperties(10)
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, 1, openapi["minProperties"])
+ assert.Equal(t, 10, openapi["maxProperties"])
+}
+
+func TestObjectSchema_Discriminator(t *testing.T) {
+ schema := Object(nil).Discriminator("type", map[string]string{
+ "dog": "#/components/schemas/Dog",
+ "cat": "#/components/schemas/Cat",
+ })
+
+ openapi := schema.OpenAPI()
+
+ disc := openapi["discriminator"].(map[string]any)
+ assert.Equal(t, "type", disc["propertyName"])
+ mapping := disc["mapping"].(map[string]string)
+ assert.Equal(t, "#/components/schemas/Dog", mapping["dog"])
+ assert.Equal(t, "#/components/schemas/Cat", mapping["cat"])
+}
+
+// --- Array Schema Tests ---
+
+func TestArraySchema_OpenAPI(t *testing.T) {
+ var itemVal string
+ itemSchema := String(&itemVal)
+
+ schema := Array(itemSchema).
+ MinItems(1).
+ MaxItems(100).
+ UniqueItems().
+ Title("Tags").
+ Description("List of tags")
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "array", openapi["type"])
+ assert.Equal(t, 1, openapi["minItems"])
+ assert.Equal(t, 100, openapi["maxItems"])
+ assert.Equal(t, true, openapi["uniqueItems"])
+ assert.Equal(t, "Tags", openapi["title"])
+ assert.Equal(t, "List of tags", openapi["description"])
+
+ items := openapi["items"].(map[string]any)
+ assert.Equal(t, "string", items["type"])
+}
+
+func TestArraySchema_ValidateFn(t *testing.T) {
+ called := false
+ schema := Array(nil).ValidateFn(func() []ValidationError {
+ called = true
+ return []ValidationError{{Code: "custom", Message: "custom error"}}
+ })
+
+ errs := schema.Validate()
+ assert.True(t, called)
+ require.Len(t, errs, 1)
+ assert.Equal(t, "custom", errs[0].Code)
+}
+
+func TestArraySchema_Required(t *testing.T) {
+ schema := Array(nil).Required()
+ assert.True(t, schema.IsRequired())
+
+ schema = Array(nil).Optional()
+ assert.False(t, schema.IsRequired())
+}
+
+// --- Map Schema Tests ---
+
+func TestMapSchema_OpenAPI(t *testing.T) {
+ var val string
+ valueSchema := String(&val)
+
+ schema := Map(valueSchema).
+ MinProperties(1).
+ MaxProperties(50).
+ Title("Metadata").
+ Description("Key-value metadata")
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "object", openapi["type"])
+ assert.Equal(t, 1, openapi["minProperties"])
+ assert.Equal(t, 50, openapi["maxProperties"])
+ assert.Equal(t, "Metadata", openapi["title"])
+
+ additionalProps := openapi["additionalProperties"].(map[string]any)
+ assert.Equal(t, "string", additionalProps["type"])
+}
+
+func TestMapSchema_ValidateFn(t *testing.T) {
+ schema := Map(nil).ValidateFn(func() []ValidationError {
+ return []ValidationError{{Code: "custom", Message: "custom error"}}
+ })
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "custom", errs[0].Code)
+}
+
+// --- OneOf Schema Tests ---
+
+type testDogSchema struct {
+ Breed string
+}
+
+func (d *testDogSchema) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "type": Const("dog"), // discriminator - OpenAPI only, not validated
+ "breed": String(&d.Breed).Required(),
+ })
+}
+
+type testCatSchema struct {
+ Color string
+}
+
+func (c *testCatSchema) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "type": Const("cat"), // discriminator - OpenAPI only, not validated
+ "color": String(&c.Color).Required(),
+ })
+}
+
+func TestOneOfSchema_OpenAPI(t *testing.T) {
+ schema := OneOf("type", map[string]SchemaProvider{
+ "dog": &testDogSchema{},
+ "cat": &testCatSchema{},
+ }).Title("Animal").Description("Either a dog or cat")
+
+ openapi := schema.OpenAPI()
+
+ assert.NotNil(t, openapi["oneOf"])
+ assert.Equal(t, "Animal", openapi["title"])
+ assert.Equal(t, "Either a dog or cat", openapi["description"])
+
+ disc := openapi["discriminator"].(map[string]any)
+ assert.Equal(t, "type", disc["propertyName"])
+}
+
+func TestOneOfSchema_ValidateFn(t *testing.T) {
+ schema := OneOf("type", nil).ValidateFn(func() []ValidationError {
+ return []ValidationError{{Code: "union", Message: "invalid variant"}}
+ })
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "union", errs[0].Code)
+}
+
+func TestOneOfSchema_DiscriminatedValidation(t *testing.T) {
+ dog := &testDogSchema{Breed: "Labrador"}
+ cat := &testCatSchema{} // Color not set - will fail validation
+
+ t.Run("validates active variant - valid", func(t *testing.T) {
+ schema := OneOf("type", map[string]SchemaProvider{
+ "dog": dog,
+ "cat": cat,
+ }).SetActiveVariant("dog")
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+ })
+
+ t.Run("validates active variant - invalid", func(t *testing.T) {
+ schema := OneOf("type", map[string]SchemaProvider{
+ "dog": dog,
+ "cat": cat,
+ }).SetActiveVariant("cat")
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "color", errs[0].Field)
+ })
+
+ t.Run("unknown variant", func(t *testing.T) {
+ schema := OneOf("type", map[string]SchemaProvider{
+ "dog": dog,
+ "cat": cat,
+ }).SetActiveVariant("bird")
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "oneOf", errs[0].Code)
+ assert.Contains(t, errs[0].Message, "bird")
+ })
+
+ t.Run("no active variant - required", func(t *testing.T) {
+ schema := OneOf("type", map[string]SchemaProvider{
+ "dog": dog,
+ "cat": cat,
+ }).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "oneOf", errs[0].Code)
+ })
+
+ t.Run("no active variant - optional", func(t *testing.T) {
+ schema := OneOf("type", map[string]SchemaProvider{
+ "dog": dog,
+ "cat": cat,
+ }).Optional()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+ })
+}
+
+func TestOneOfSchema_DiscriminatedIsPresent(t *testing.T) {
+ dog := &testDogSchema{Breed: "Labrador"}
+ cat := &testCatSchema{}
+
+ t.Run("present when active variant set and has values", func(t *testing.T) {
+ schema := OneOf("type", map[string]SchemaProvider{
+ "dog": dog,
+ "cat": cat,
+ }).SetActiveVariant("dog")
+
+ assert.True(t, schema.IsPresent())
+ })
+
+ t.Run("not present when no active variant", func(t *testing.T) {
+ schema := OneOf("type", map[string]SchemaProvider{
+ "dog": dog,
+ "cat": cat,
+ })
+
+ assert.False(t, schema.IsPresent())
+ })
+}
+
+// --- AnyOf Schema Tests ---
+
+func TestAnyOfSchema_OpenAPI(t *testing.T) {
+ var strVal string
+ var intVal int
+
+ schema := AnyOf(
+ String(&strVal),
+ Int(&intVal),
+ ).Title("StringOrInt").Description("Can be string or integer")
+
+ openapi := schema.OpenAPI()
+
+ anyOf := openapi["anyOf"].([]map[string]any)
+ require.Len(t, anyOf, 2)
+ assert.Equal(t, "string", anyOf[0]["type"])
+ assert.Equal(t, "integer", anyOf[1]["type"])
+ assert.Equal(t, "StringOrInt", openapi["title"])
+}
+
+func TestAnyOfSchema_Required(t *testing.T) {
+ schema := AnyOf().Required()
+ assert.True(t, schema.IsRequired())
+
+ schema = AnyOf().Optional()
+ assert.False(t, schema.IsRequired())
+}
+
+// --- AllOf Schema Tests ---
+
+func TestAllOfSchema_OpenAPI(t *testing.T) {
+ var name string
+ var age int
+
+ schema := AllOf(
+ Object(map[string]Schema{"name": String(&name)}),
+ Object(map[string]Schema{"age": Int(&age)}),
+ ).Title("Combined").Description("Combined schema")
+
+ openapi := schema.OpenAPI()
+
+ allOf := openapi["allOf"].([]map[string]any)
+ require.Len(t, allOf, 2)
+ assert.Equal(t, "Combined", openapi["title"])
+}
+
+func TestAllOfSchema_Validate(t *testing.T) {
+ var name string
+ var age *int
+
+ schema := AllOf(
+ Object(map[string]Schema{"name": String(&name).Required()}),
+ Object(map[string]Schema{"age": Int(age).Required()}), // nil pointer = missing
+ )
+
+ errs := schema.Validate()
+ require.Len(t, errs, 2)
+
+ name = "John"
+ ageVal := 25
+ age = &ageVal
+ // Rebuild schema with new pointer
+ schema = AllOf(
+ Object(map[string]Schema{"name": String(&name).Required()}),
+ Object(map[string]Schema{"age": Int(age).Required()}),
+ )
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+// --- Ref Schema Tests ---
+
+func TestRefSchema_OpenAPI(t *testing.T) {
+ schema := Ref("#/components/schemas/User").
+ Required().
+ Description("Reference to User schema")
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "#/components/schemas/User", openapi["$ref"])
+ assert.Equal(t, "Reference to User schema", openapi["description"])
+}
+
+func TestRefSchema_Required(t *testing.T) {
+ schema := Ref("#/components/schemas/User").Required()
+ assert.True(t, schema.IsRequired())
+
+ schema = Ref("#/components/schemas/User").Optional()
+ assert.False(t, schema.IsRequired())
+}
+
+func TestRefSchema_Validate(t *testing.T) {
+ schema := Ref("#/components/schemas/User")
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+// --- Const Schema Tests ---
+
+func TestConstSchema_OpenAPI(t *testing.T) {
+ schema := Const("fixed_value").
+ Title("Constant").
+ Description("A constant value")
+
+ openapi := schema.OpenAPI()
+
+ // Uses enum with single value for OpenAPI 3.0.x compatibility
+ assert.Equal(t, []any{"fixed_value"}, openapi["enum"])
+ assert.Equal(t, "string", openapi["type"])
+ assert.Equal(t, "Constant", openapi["title"])
+ assert.Equal(t, "A constant value", openapi["description"])
+}
+
+func TestConstSchema_Required(t *testing.T) {
+ schema := Const("value").Required()
+ assert.True(t, schema.IsRequired())
+
+ schema = Const("value").Optional()
+ assert.False(t, schema.IsRequired())
+}
+
+func TestConstSchema_Validate(t *testing.T) {
+ schema := Const("value")
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+// --- Nullable and other modifiers ---
+
+func TestObjectSchema_Modifiers(t *testing.T) {
+ schema := Object(nil).
+ Nullable().
+ ReadOnly().
+ WriteOnly().
+ Deprecated().
+ Example(map[string]any{"key": "value"})
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, true, openapi["nullable"])
+ assert.Equal(t, true, openapi["readOnly"])
+ assert.Equal(t, true, openapi["writeOnly"])
+ assert.Equal(t, true, openapi["deprecated"])
+ assert.NotNil(t, openapi["example"])
+}
+
+func TestArraySchema_Modifiers(t *testing.T) {
+ schema := Array(nil).
+ Nullable().
+ ReadOnly().
+ WriteOnly().
+ Deprecated().
+ Example([]string{"a", "b"})
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, true, openapi["nullable"])
+ assert.Equal(t, true, openapi["readOnly"])
+ assert.Equal(t, true, openapi["writeOnly"])
+ assert.Equal(t, true, openapi["deprecated"])
+ assert.NotNil(t, openapi["example"])
+}
+
+func TestMapSchema_Modifiers(t *testing.T) {
+ schema := Map(nil).
+ Nullable().
+ ReadOnly().
+ WriteOnly().
+ Deprecated().
+ Example(map[string]string{"a": "b"})
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, true, openapi["nullable"])
+ assert.Equal(t, true, openapi["readOnly"])
+ assert.Equal(t, true, openapi["writeOnly"])
+ assert.Equal(t, true, openapi["deprecated"])
+ assert.NotNil(t, openapi["example"])
+}
+
+func TestOneOfSchema_Modifiers(t *testing.T) {
+ schema := OneOf("type", nil).
+ Nullable().
+ Deprecated().
+ Example(map[string]any{"type": "dog"})
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, true, openapi["nullable"])
+ assert.Equal(t, true, openapi["deprecated"])
+ assert.NotNil(t, openapi["example"])
+}
+
+func TestAnyOfSchema_Modifiers(t *testing.T) {
+ schema := AnyOf().
+ Nullable().
+ Deprecated()
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, true, openapi["nullable"])
+ assert.Equal(t, true, openapi["deprecated"])
+}
+
+func TestAllOfSchema_Modifiers(t *testing.T) {
+ schema := AllOf().
+ Nullable().
+ Deprecated()
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, true, openapi["nullable"])
+ assert.Equal(t, true, openapi["deprecated"])
+}
diff --git a/backend-go/pkg/api/schema_test.go b/backend-go/pkg/api/schema_test.go
new file mode 100644
index 0000000000..42f5495ab9
--- /dev/null
+++ b/backend-go/pkg/api/schema_test.go
@@ -0,0 +1,752 @@
+package api
+
+import (
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// --- String Schema Tests ---
+
+func TestStringSchema_Required(t *testing.T) {
+ var val string
+ schema := String(&val).Required()
+
+ assert.True(t, schema.IsRequired())
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+}
+
+func TestStringSchema_Optional(t *testing.T) {
+ var val string
+ schema := String(&val).Optional()
+
+ assert.False(t, schema.IsRequired())
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_MinLength(t *testing.T) {
+ val := "ab"
+ schema := String(&val).MinLength(3)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "min_length", errs[0].Code)
+
+ val = "abc"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_MaxLength(t *testing.T) {
+ val := "abcdef"
+ schema := String(&val).MaxLength(5)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "max_length", errs[0].Code)
+
+ val = "abcde"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_Length(t *testing.T) {
+ val := "ab"
+ schema := String(&val).Length(3, 5)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "min_length", errs[0].Code)
+
+ val = "abcdef"
+ errs = schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "max_length", errs[0].Code)
+
+ val = "abcd"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_Pattern(t *testing.T) {
+ val := "abc123"
+ schema := String(&val).Pattern(`^[a-z]+$`)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "pattern", errs[0].Code)
+
+ val = "abc"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_Enum(t *testing.T) {
+ val := "invalid"
+ schema := String(&val).Enum("foo", "bar", "baz")
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "enum", errs[0].Code)
+
+ val = "bar"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_FormatEmail(t *testing.T) {
+ val := "not-an-email"
+ schema := String(&val).Email()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "format", errs[0].Code)
+
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_FormatUUID(t *testing.T) {
+ val := "not-a-uuid"
+ schema := String(&val).UUID()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "format", errs[0].Code)
+
+ val = "550e8400-e29b-41d4-a716-446655440000"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_FormatURI(t *testing.T) {
+ val := "not a uri"
+ schema := String(&val).URI()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "format", errs[0].Code)
+
+ val = "https://example.com/path"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_FormatDateTime(t *testing.T) {
+ val := "not-a-date"
+ schema := String(&val).DateTime()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "format", errs[0].Code)
+
+ val = "2024-01-15T10:30:00Z"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_FormatDate(t *testing.T) {
+ val := "not-a-date"
+ schema := String(&val).Date()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "format", errs[0].Code)
+
+ val = "2024-01-15"
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestStringSchema_OpenAPI(t *testing.T) {
+ var val string
+ schema := String(&val).
+ Required().
+ MinLength(1).
+ MaxLength(100).
+ Pattern(`^[a-z]+$`).
+ Format("custom").
+ Default("default").
+ Example("example").
+ Title("Title").
+ Description("Description").
+ Deprecated().
+ Nullable().
+ ReadOnly()
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "string", openapi["type"])
+ assert.Equal(t, 1, openapi["minLength"])
+ assert.Equal(t, 100, openapi["maxLength"])
+ assert.Equal(t, `^[a-z]+$`, openapi["pattern"])
+ assert.Equal(t, "custom", openapi["format"])
+ assert.Equal(t, "default", openapi["default"])
+ assert.Equal(t, "example", openapi["example"])
+ assert.Equal(t, "Title", openapi["title"])
+ assert.Equal(t, "Description", openapi["description"])
+ assert.Equal(t, true, openapi["deprecated"])
+ assert.Equal(t, true, openapi["nullable"])
+ assert.Equal(t, true, openapi["readOnly"])
+}
+
+func TestStringSchema_OpenAPI_Enum(t *testing.T) {
+ var val string
+ schema := String(&val).Enum("a", "b", "c")
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, []string{"a", "b", "c"}, openapi["enum"])
+}
+
+// --- Int Schema Tests ---
+
+func TestIntSchema_Required_NilPointer(t *testing.T) {
+ // nil pointer means value was not provided
+ schema := Int(nil).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+}
+
+func TestIntSchema_Required_ZeroValue(t *testing.T) {
+ // Zero is a valid provided value, not "missing"
+ val := 0
+ schema := Int(&val).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs) // 0 is valid when ptr is non-nil
+}
+
+func TestIntSchema_Required_NonZeroValue(t *testing.T) {
+ val := 42
+ schema := Int(&val).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestIntSchema_Min(t *testing.T) {
+ val := 5
+ schema := Int(&val).Min(10)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "minimum", errs[0].Code)
+
+ val = 10
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestIntSchema_Max(t *testing.T) {
+ val := 15
+ schema := Int(&val).Max(10)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "maximum", errs[0].Code)
+
+ val = 10
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestIntSchema_Range(t *testing.T) {
+ val := 5
+ schema := Int(&val).Range(10, 20)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "minimum", errs[0].Code)
+
+ val = 25
+ errs = schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "maximum", errs[0].Code)
+
+ val = 15
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestIntSchema_ExclusiveMin(t *testing.T) {
+ val := 10
+ schema := Int(&val).ExclusiveMin(10)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "exclusive_minimum", errs[0].Code)
+
+ val = 11
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestIntSchema_ExclusiveMax(t *testing.T) {
+ val := 10
+ schema := Int(&val).ExclusiveMax(10)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "exclusive_maximum", errs[0].Code)
+
+ val = 9
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestIntSchema_MultipleOf(t *testing.T) {
+ val := 7
+ schema := Int(&val).MultipleOf(3)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "multiple_of", errs[0].Code)
+
+ val = 9
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestIntSchema_Enum(t *testing.T) {
+ val := 5
+ schema := Int(&val).Enum(1, 2, 3)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "enum", errs[0].Code)
+
+ val = 2
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestInt64Schema(t *testing.T) {
+ var val int64 = 100
+ schema := Int64(&val).Min(50).Max(200)
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+
+ openapi := schema.OpenAPI()
+ assert.Equal(t, "integer", openapi["type"])
+ assert.Equal(t, "int64", openapi["format"])
+}
+
+func TestIntSchema_OpenAPI(t *testing.T) {
+ var val int
+ schema := Int(&val).
+ Min(0).
+ Max(100).
+ MultipleOf(5).
+ Default(50).
+ Example(25).
+ Title("Count").
+ Description("A count value").
+ Deprecated().
+ Nullable()
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "integer", openapi["type"])
+ assert.Equal(t, "int64", openapi["format"])
+ assert.Equal(t, int64(0), openapi["minimum"])
+ assert.Equal(t, int64(100), openapi["maximum"])
+ assert.Equal(t, int64(5), openapi["multipleOf"])
+ assert.Equal(t, int64(50), openapi["default"])
+ assert.Equal(t, 25, openapi["example"])
+ assert.Equal(t, "Count", openapi["title"])
+ assert.Equal(t, "A count value", openapi["description"])
+ assert.Equal(t, true, openapi["deprecated"])
+ assert.Equal(t, true, openapi["nullable"])
+}
+
+// --- Float Schema Tests ---
+
+func TestFloatSchema_Required_NilPointer(t *testing.T) {
+ // nil pointer means value was not provided
+ schema := Float(nil).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+}
+
+func TestFloatSchema_Required_ZeroValue(t *testing.T) {
+ // Zero is a valid provided value, not "missing"
+ val := 0.0
+ schema := Float(&val).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs) // 0.0 is valid when ptr is non-nil
+}
+
+func TestFloatSchema_Required_NonZeroValue(t *testing.T) {
+ val := 3.14
+ schema := Float(&val).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestFloatSchema_Min(t *testing.T) {
+ val := 1.5
+ schema := Float(&val).Min(2.0)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "minimum", errs[0].Code)
+
+ val = 2.5
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestFloatSchema_Max(t *testing.T) {
+ val := 5.5
+ schema := Float(&val).Max(5.0)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "maximum", errs[0].Code)
+
+ val = 4.5
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestFloatSchema_Range(t *testing.T) {
+ val := 0.5
+ schema := Float(&val).Range(1.0, 10.0)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+
+ val = 5.0
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestFloatSchema_ExclusiveMinMax(t *testing.T) {
+ val := 5.0
+ schema := Float(&val).ExclusiveMin(5.0)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "exclusive_minimum", errs[0].Code)
+
+ schema = Float(&val).ExclusiveMax(5.0)
+ errs = schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "exclusive_maximum", errs[0].Code)
+}
+
+func TestFloatSchema_OpenAPI(t *testing.T) {
+ var val float64
+ schema := Float(&val).Min(0.0).Max(1.0).Title("Ratio")
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "number", openapi["type"])
+ assert.Equal(t, "double", openapi["format"])
+ assert.Equal(t, 0.0, openapi["minimum"])
+ assert.Equal(t, 1.0, openapi["maximum"])
+ assert.Equal(t, "Ratio", openapi["title"])
+}
+
+// --- Bool Schema Tests ---
+
+func TestBoolSchema_Required_NilPointer(t *testing.T) {
+ // nil pointer means value was not provided
+ schema := Bool(nil).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+}
+
+func TestBoolSchema_Required_FalseValue(t *testing.T) {
+ // false is a valid provided value, not "missing"
+ val := false
+ schema := Bool(&val).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs) // false is valid when ptr is non-nil
+}
+
+func TestBoolSchema_Required_TrueValue(t *testing.T) {
+ val := true
+ schema := Bool(&val).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestBoolSchema_OpenAPI(t *testing.T) {
+ var val bool
+ schema := Bool(&val).
+ Default(true).
+ Example(false).
+ Title("Enabled").
+ Description("Whether feature is enabled").
+ Deprecated().
+ Nullable()
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "boolean", openapi["type"])
+ assert.Equal(t, true, openapi["default"])
+ assert.Equal(t, false, openapi["example"])
+ assert.Equal(t, "Enabled", openapi["title"])
+ assert.Equal(t, "Whether feature is enabled", openapi["description"])
+ assert.Equal(t, true, openapi["deprecated"])
+ assert.Equal(t, true, openapi["nullable"])
+}
+
+// --- UUID Schema Tests ---
+
+func TestUUIDSchema_Required(t *testing.T) {
+ var val uuid.UUID
+ schema := UUID(&val).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+
+ val = uuid.New()
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestUUIDSchema_Optional(t *testing.T) {
+ var val uuid.UUID
+ schema := UUID(&val).Optional()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestUUIDSchema_OpenAPI(t *testing.T) {
+ var val uuid.UUID
+ schema := UUID(&val).Title("ID").Description("Unique identifier")
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "string", openapi["type"])
+ assert.Equal(t, "uuid", openapi["format"])
+ assert.Equal(t, "ID", openapi["title"])
+ assert.Equal(t, "Unique identifier", openapi["description"])
+}
+
+// --- Time Schema Tests ---
+
+func TestTimeSchema_Required(t *testing.T) {
+ var val time.Time
+ schema := Time(&val).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+
+ val = time.Now()
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestTimeSchema_Optional(t *testing.T) {
+ var val time.Time
+ schema := Time(&val).Optional()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestTimeSchema_OpenAPI(t *testing.T) {
+ var val time.Time
+ schema := Time(&val).Title("Created At")
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "string", openapi["type"])
+ assert.Equal(t, "date-time", openapi["format"])
+ assert.Equal(t, "Created At", openapi["title"])
+}
+
+func TestTimeSchema_DateOnly(t *testing.T) {
+ var val time.Time
+ schema := Time(&val).DateOnly()
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "date", openapi["format"])
+}
+
+func TestTimeSchema_TimeOnly(t *testing.T) {
+ var val time.Time
+ schema := Time(&val).TimeOnly()
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "time", openapi["format"])
+}
+
+// --- Bytes Schema Tests ---
+
+func TestBytesSchema_Required(t *testing.T) {
+ var val []byte
+ schema := Bytes(&val).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+
+ val = []byte("data")
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestBytesSchema_MinMaxLength(t *testing.T) {
+ val := []byte("ab")
+ schema := Bytes(&val).MinLength(3).MaxLength(10)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "min_length", errs[0].Code)
+
+ val = []byte("abcdefghijk")
+ errs = schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "max_length", errs[0].Code)
+
+ val = []byte("abcde")
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestBytesSchema_OpenAPI(t *testing.T) {
+ var val []byte
+ schema := Bytes(&val).MinLength(1).MaxLength(1024)
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "string", openapi["type"])
+ assert.Equal(t, "byte", openapi["format"])
+ assert.Equal(t, 1, openapi["minLength"])
+ assert.Equal(t, 1024, openapi["maxLength"])
+}
+
+func TestBytesSchema_Binary(t *testing.T) {
+ var val []byte
+ schema := Bytes(&val).Binary()
+
+ openapi := schema.OpenAPI()
+
+ assert.Equal(t, "binary", openapi["format"])
+}
+
+// --- Any Schema Tests ---
+
+func TestAnySchema_Required(t *testing.T) {
+ var val any
+ schema := Any(&val).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+
+ val = map[string]any{"key": "value"}
+ errs = schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestAnySchema_OpenAPI(t *testing.T) {
+ var val any
+ schema := Any(&val).Title("Data").Description("Arbitrary data")
+
+ openapi := schema.OpenAPI()
+
+ _, hasType := openapi["type"]
+ assert.False(t, hasType)
+ assert.Equal(t, "Data", openapi["title"])
+ assert.Equal(t, "Arbitrary data", openapi["description"])
+}
+
+// --- Raw Schema Tests ---
+
+func TestRawSchema_Required(t *testing.T) {
+ var rawMessage json.RawMessage
+ schema := Raw(&rawMessage).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+}
+
+func TestRawSchema_OpenAPI(t *testing.T) {
+ var rawMessage json.RawMessage
+ schema := Raw(&rawMessage).Title("Raw JSON")
+
+ openapi := schema.OpenAPI()
+
+ _, hasType := openapi["type"]
+ assert.False(t, hasType)
+ assert.Equal(t, "Raw JSON", openapi["title"])
+}
+
+// --- Multiple Validation Errors ---
+
+func TestStringSchema_MultipleErrors(t *testing.T) {
+ val := "ab"
+ schema := String(&val).MinLength(5).Pattern(`^[0-9]+$`)
+
+ errs := schema.Validate()
+ require.Len(t, errs, 2)
+
+ codes := make([]string, len(errs))
+ for i, e := range errs {
+ codes[i] = e.Code
+ }
+ assert.Contains(t, codes, "min_length")
+ assert.Contains(t, codes, "pattern")
+}
+
+// --- ValidationErrors type ---
+
+func TestValidationErrors_Error(t *testing.T) {
+ errs := ValidationErrors{
+ {Field: "name", Message: "is required", Code: "required"},
+ {Field: "email", Message: "must be valid", Code: "format"},
+ }
+
+ errStr := errs.Error()
+ assert.Contains(t, errStr, "name: is required")
+ assert.Contains(t, errStr, "email: must be valid")
+}
+
+func TestValidationErrors_HasErrors(t *testing.T) {
+ var errs ValidationErrors
+ assert.False(t, errs.HasErrors())
+
+ errs = append(errs, ValidationError{Message: "error"})
+ assert.True(t, errs.HasErrors())
+}
+
+func TestValidationError_Error(t *testing.T) {
+ err := ValidationError{Field: "name", Message: "is required"}
+ assert.Equal(t, "name: is required", err.Error())
+
+ err = ValidationError{Message: "something went wrong"}
+ assert.Equal(t, "something went wrong", err.Error())
+}
diff --git a/backend-go/pkg/api/union.go b/backend-go/pkg/api/union.go
new file mode 100644
index 0000000000..e5fe486392
--- /dev/null
+++ b/backend-go/pkg/api/union.go
@@ -0,0 +1,644 @@
+package api
+
+import (
+ "encoding/json"
+ "fmt"
+)
+
+// Union is a marker interface for discriminated union types.
+// Embed UnionBase in your types to implement this interface.
+type Union interface {
+ SchemaProvider
+ unionMarker()
+}
+
+// UnionBase is an embeddable type that satisfies the Union marker interface.
+// Embed this in your union variant types:
+//
+// type MyVariant struct {
+// api.UnionBase
+// Field string `json:"field"`
+// }
+type UnionBase struct{}
+
+//nolint:unused // Implements Union interface for external packages
+func (UnionBase) unionMarker() {}
+
+// UnionDef defines a discriminated union parser
+type UnionDef[T Union] struct {
+ Discriminator string
+ Variants map[string]func() T
+}
+
+// Parse parses raw JSON into the appropriate union variant
+func (u UnionDef[T]) Parse(data json.RawMessage) (T, error) {
+ var zero T
+
+ if len(data) == 0 || string(data) == "null" {
+ return zero, nil
+ }
+
+ // Use consistent parsing path for all discriminators
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return zero, fmt.Errorf("failed to parse union: %w", err)
+ }
+
+ discRaw, ok := raw[u.Discriminator]
+ if !ok {
+ return zero, fmt.Errorf("missing discriminator field %q", u.Discriminator)
+ }
+
+ var discValue string
+ if err := json.Unmarshal(discRaw, &discValue); err != nil {
+ return zero, fmt.Errorf("invalid %s value (must be string): %w", u.Discriminator, err)
+ }
+
+ factory, ok := u.Variants[discValue]
+ if !ok {
+ return zero, fmt.Errorf("unknown %s value: %q", u.Discriminator, discValue)
+ }
+
+ result := factory()
+ if err := json.Unmarshal(data, result); err != nil {
+ return zero, fmt.Errorf("failed to unmarshal variant %q: %w", discValue, err)
+ }
+
+ return result, nil
+}
+
+// OpenAPI generates the OpenAPI schema for this union
+func (u UnionDef[T]) OpenAPI() map[string]any {
+ oneOf := make([]map[string]any, 0, len(u.Variants))
+
+ for _, factory := range u.Variants {
+ variant := factory()
+ variantSchema := variant.Schema().OpenAPI()
+ oneOf = append(oneOf, variantSchema)
+ }
+
+ // Note: mapping is omitted for inline schemas - tooling matches by
+ // the discriminator property's enum value in each variant
+ return map[string]any{
+ "oneOf": oneOf,
+ "discriminator": map[string]any{
+ "propertyName": u.Discriminator,
+ },
+ }
+}
+
+// UnionBinding holds the binding info for a union field during JSON parsing
+type UnionBinding struct {
+ jsonKey string
+ parse func(raw json.RawMessage) error
+}
+
+// U creates a UnionBinding for use with ParseUnions
+func U[T Union](jsonKey string, target *T, parser UnionDef[T]) UnionBinding {
+ return UnionBinding{
+ jsonKey: jsonKey,
+ parse: func(raw json.RawMessage) error {
+ parsed, err := parser.Parse(raw)
+ if err != nil {
+ return err
+ }
+ *target = parsed
+ return nil
+ },
+ }
+}
+
+// ParseUnions parses union fields from raw JSON data.
+//
+// Deprecated: Use ParseUnionField with json.RawMessage for better performance.
+func ParseUnions(data []byte, bindings ...UnionBinding) error {
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return fmt.Errorf("failed to parse JSON: %w", err)
+ }
+
+ for _, b := range bindings {
+ rawField, ok := raw[b.jsonKey]
+ if !ok || string(rawField) == "null" {
+ continue
+ }
+ if err := b.parse(rawField); err != nil {
+ return fmt.Errorf("%s: %w", b.jsonKey, err)
+ }
+ }
+
+ return nil
+}
+
+// ParseUnionField parses a union from a json.RawMessage field.
+// Use this with json.RawMessage struct fields to avoid double JSON parsing.
+//
+// Example:
+//
+// type Request struct {
+// AuthRaw json.RawMessage `json:"auth"`
+// Auth AuthMethod `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.AuthRaw, &r.Auth, AuthParser)
+// }
+func ParseUnionField[T Union](raw json.RawMessage, target *T, parser UnionDef[T]) error {
+ if len(raw) == 0 || string(raw) == "null" {
+ return nil
+ }
+ parsed, err := parser.Parse(raw)
+ if err != nil {
+ return err
+ }
+ *target = parsed
+ return nil
+}
+
+// NestedUnionDef defines a discriminated union where the discriminator
+// and payload are in separate fields.
+//
+// Example JSON: {"method": "password", "payload": {"username": "...", "password": "..."}}
+type NestedUnionDef[T Union] struct {
+ Discriminator string // Field name containing the type (e.g., "method")
+ PayloadField string // Field name containing the payload (e.g., "payload")
+ Variants map[string]func() T // Factory functions for each variant
+}
+
+// Parse parses a nested union from JSON containing discriminator and payload fields
+func (u NestedUnionDef[T]) Parse(data json.RawMessage) (T, error) {
+ var zero T
+
+ if len(data) == 0 || string(data) == "null" {
+ return zero, nil
+ }
+
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return zero, fmt.Errorf("failed to parse nested union: %w", err)
+ }
+
+ // Extract discriminator
+ discRaw, ok := raw[u.Discriminator]
+ if !ok {
+ return zero, fmt.Errorf("missing discriminator field %q", u.Discriminator)
+ }
+ var discValue string
+ if err := json.Unmarshal(discRaw, &discValue); err != nil {
+ return zero, fmt.Errorf("invalid discriminator value: %w", err)
+ }
+
+ factory, ok := u.Variants[discValue]
+ if !ok {
+ return zero, fmt.Errorf("unknown %s value: %q", u.Discriminator, discValue)
+ }
+
+ // Extract and unmarshal payload
+ payloadRaw, ok := raw[u.PayloadField]
+ if !ok || string(payloadRaw) == "null" {
+ return zero, fmt.Errorf("missing %s field", u.PayloadField)
+ }
+
+ result := factory()
+ if err := json.Unmarshal(payloadRaw, result); err != nil {
+ return zero, fmt.Errorf("failed to unmarshal %s for %q: %w", u.PayloadField, discValue, err)
+ }
+
+ return result, nil
+}
+
+// ParseWithType parses a payload with an already-known type.
+// Returns an error if payload is null/empty since the OpenAPI schema marks it required.
+func (u NestedUnionDef[T]) ParseWithType(typeName string, payload json.RawMessage) (T, error) {
+ var zero T
+
+ factory, ok := u.Variants[typeName]
+ if !ok {
+ return zero, fmt.Errorf("unknown type: %q", typeName)
+ }
+
+ if len(payload) == 0 || string(payload) == "null" {
+ return zero, fmt.Errorf("missing %s for type %q", u.PayloadField, typeName)
+ }
+
+ result := factory()
+ if err := json.Unmarshal(payload, result); err != nil {
+ return zero, fmt.Errorf("failed to unmarshal payload: %w", err)
+ }
+
+ return result, nil
+}
+
+// OpenAPI generates the OpenAPI schema for this nested union
+func (u NestedUnionDef[T]) OpenAPI() map[string]any {
+ payloadOneOf := make([]map[string]any, 0, len(u.Variants))
+ mapping := make(map[string]string)
+ enumValues := make([]string, 0, len(u.Variants))
+
+ for typeName, factory := range u.Variants {
+ variant := factory()
+ payloadOneOf = append(payloadOneOf, variant.Schema().OpenAPI())
+ mapping[typeName] = fmt.Sprintf("#/components/schemas/%s", typeName)
+ enumValues = append(enumValues, typeName)
+ }
+
+ return map[string]any{
+ "type": "object",
+ "properties": map[string]any{
+ u.Discriminator: map[string]any{
+ "type": "string",
+ "enum": enumValues,
+ },
+ u.PayloadField: map[string]any{
+ "oneOf": payloadOneOf,
+ },
+ },
+ "required": []string{u.Discriminator, u.PayloadField},
+ }
+}
+
+// ParseNestedUnionField parses a nested union from separate discriminator and payload fields
+func ParseNestedUnionField[T Union](discriminatorRaw, payloadRaw json.RawMessage, target *T, parser NestedUnionDef[T]) error {
+ if len(discriminatorRaw) == 0 || string(discriminatorRaw) == "null" {
+ return nil
+ }
+
+ var discriminator string
+ if err := json.Unmarshal(discriminatorRaw, &discriminator); err != nil {
+ return fmt.Errorf("invalid discriminator: %w", err)
+ }
+
+ parsed, err := parser.ParseWithType(discriminator, payloadRaw)
+ if err != nil {
+ return err
+ }
+ *target = parsed
+ return nil
+}
+
+// UnionFromSchema provides a connected union experience - parsing, validation, and OpenAPI in one.
+// It binds a json.RawMessage field to a parsed union target.
+type UnionFromSchema[T Union] struct {
+ rawPtr *json.RawMessage
+ targetPtr *T
+ parser UnionDef[T]
+ required bool
+ defaultVariant string
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+}
+
+// UnionFrom creates a schema that parses a union from raw JSON during validation.
+// The raw JSON is read from rawPtr, parsed using the parser, and stored in targetPtr.
+// This provides a connected experience: OpenAPI generation + parsing + validation in one schema.
+//
+// Example:
+//
+// type Request struct {
+// TargetRaw json.RawMessage `json:"target"`
+// Target WebhookTarget `json:"-"`
+// }
+//
+// func (r *Request) Schema() *api.ObjectSchema {
+// return api.Object(map[string]api.Schema{
+// "target": api.UnionFrom(&r.TargetRaw, &r.Target, WebhookTargetParser).Required(),
+// })
+// }
+func UnionFrom[T Union](rawPtr *json.RawMessage, targetPtr *T, parser UnionDef[T]) *UnionFromSchema[T] {
+ return &UnionFromSchema[T]{
+ rawPtr: rawPtr,
+ targetPtr: targetPtr,
+ parser: parser,
+ }
+}
+
+func (s *UnionFromSchema[T]) Required() *UnionFromSchema[T] {
+ s.required = true
+ return s
+}
+
+func (s *UnionFromSchema[T]) Optional() *UnionFromSchema[T] {
+ s.required = false
+ return s
+}
+
+// DefaultVariant sets the discriminator value to use when the field is absent.
+// The variant will be created with its own field defaults applied.
+func (s *UnionFromSchema[T]) DefaultVariant(discriminator string) *UnionFromSchema[T] {
+ s.defaultVariant = discriminator
+ return s
+}
+
+func (s *UnionFromSchema[T]) Example(val any) *UnionFromSchema[T] {
+ s.example = val
+ return s
+}
+
+func (s *UnionFromSchema[T]) Title(val string) *UnionFromSchema[T] {
+ s.title = val
+ return s
+}
+
+func (s *UnionFromSchema[T]) Description(val string) *UnionFromSchema[T] {
+ s.description = val
+ return s
+}
+
+func (s *UnionFromSchema[T]) Deprecated() *UnionFromSchema[T] {
+ s.deprecated = true
+ return s
+}
+
+func (s *UnionFromSchema[T]) Nullable() *UnionFromSchema[T] {
+ s.nullable = true
+ return s
+}
+
+func (s *UnionFromSchema[T]) IsRequired() bool {
+ return s.required
+}
+
+func (s *UnionFromSchema[T]) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *UnionFromSchema[T]) IsPresent() bool {
+ return s.rawPtr != nil && len(*s.rawPtr) > 0 && string(*s.rawPtr) != "null"
+}
+
+func (s *UnionFromSchema[T]) Validate() []ValidationError {
+ // Check if raw data is present
+ hasData := s.rawPtr != nil && len(*s.rawPtr) > 0 && string(*s.rawPtr) != "null"
+
+ if !hasData {
+ // No data - check for default variant
+ if s.defaultVariant != "" {
+ factory, ok := s.parser.Variants[s.defaultVariant]
+ if !ok {
+ return []ValidationError{{
+ Code: "invalid_default",
+ Message: fmt.Sprintf("unknown default variant: %q", s.defaultVariant),
+ }}
+ }
+ variant := factory()
+ *s.targetPtr = variant
+
+ // Apply defaults to variant fields
+ variantSchema := variant.Schema()
+ applySchemaDefaults(variantSchema)
+
+ // Validate the variant
+ return variantSchema.Validate()
+ }
+
+ if s.required {
+ return []ValidationError{{Code: "required", Message: "is required"}}
+ }
+ return nil
+ }
+
+ // Parse the union from raw JSON
+ parsed, err := s.parser.Parse(*s.rawPtr)
+ if err != nil {
+ return []ValidationError{{Code: "invalid_union", Message: err.Error()}}
+ }
+
+ *s.targetPtr = parsed
+
+ // Apply defaults to variant fields
+ variantSchema := parsed.Schema()
+ applySchemaDefaults(variantSchema)
+
+ // Validate the variant
+ return variantSchema.Validate()
+}
+
+func (s *UnionFromSchema[T]) OpenAPI() map[string]any {
+ schema := s.parser.OpenAPI()
+
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+ if s.defaultVariant != "" {
+ schema["default"] = map[string]any{s.parser.Discriminator: s.defaultVariant}
+ }
+
+ return schema
+}
+
+// applySchemaDefaults applies default values to body fields in an ObjectSchema.
+// This is used for union variants after parsing.
+func applySchemaDefaults(schema *ObjectSchema) {
+ for _, fieldSchema := range schema.properties {
+ switch s := fieldSchema.(type) {
+ case *IntSchema:
+ if s.defaultVal != nil {
+ val, _ := s.value()
+ if val == 0 {
+ if s.ptr != nil {
+ *s.ptr = int(*s.defaultVal)
+ }
+ if s.ptr64 != nil {
+ *s.ptr64 = *s.defaultVal
+ }
+ }
+ }
+ case *StringSchema:
+ if s.defaultVal != nil && s.ptr != nil && *s.ptr == "" {
+ *s.ptr = *s.defaultVal
+ }
+ case *BoolSchema:
+ // For bool, only apply default if we have a way to track "not set"
+ // Since false is a valid value, we skip this for now
+ case *FloatSchema:
+ if s.defaultVal != nil && s.ptr != nil && *s.ptr == 0 {
+ *s.ptr = *s.defaultVal
+ }
+ }
+ }
+}
+
+// UnionSchema creates a Schema for a union field
+type UnionSchema[T Union] struct {
+ parser UnionDef[T]
+ ptr *T
+ required bool
+ example any
+ title string
+ description string
+ deprecated bool
+ nullable bool
+}
+
+func UnionField[T Union](ptr *T, parser UnionDef[T]) *UnionSchema[T] {
+ return &UnionSchema[T]{
+ parser: parser,
+ ptr: ptr,
+ }
+}
+
+func (s *UnionSchema[T]) Required() *UnionSchema[T] {
+ s.required = true
+ return s
+}
+
+func (s *UnionSchema[T]) Optional() *UnionSchema[T] {
+ s.required = false
+ return s
+}
+
+func (s *UnionSchema[T]) Example(val any) *UnionSchema[T] {
+ s.example = val
+ return s
+}
+
+func (s *UnionSchema[T]) Title(val string) *UnionSchema[T] {
+ s.title = val
+ return s
+}
+
+func (s *UnionSchema[T]) Description(val string) *UnionSchema[T] {
+ s.description = val
+ return s
+}
+
+func (s *UnionSchema[T]) Deprecated() *UnionSchema[T] {
+ s.deprecated = true
+ return s
+}
+
+func (s *UnionSchema[T]) Nullable() *UnionSchema[T] {
+ s.nullable = true
+ return s
+}
+
+func (s *UnionSchema[T]) IsRequired() bool {
+ return s.required
+}
+
+func (s *UnionSchema[T]) GetSource() ParamSource {
+ return SourceBody
+}
+
+func (s *UnionSchema[T]) IsPresent() bool {
+ return s.ptr != nil && any(*s.ptr) != nil
+}
+
+func (s *UnionSchema[T]) Validate() []ValidationError {
+ var errs []ValidationError
+
+ if s.ptr == nil || any(*s.ptr) == nil {
+ if s.required {
+ errs = append(errs, ValidationError{Code: "required", Message: "is required"})
+ }
+ return errs
+ }
+
+ unionVal := *s.ptr
+ schema := unionVal.Schema()
+ if schema != nil {
+ errs = append(errs, schema.Validate()...)
+ }
+
+ return errs
+}
+
+func (s *UnionSchema[T]) OpenAPI() map[string]any {
+ schema := s.parser.OpenAPI()
+
+ if s.example != nil {
+ schema["example"] = s.example
+ }
+ if s.title != "" {
+ schema["title"] = s.title
+ }
+ if s.description != "" {
+ schema["description"] = s.description
+ }
+ if s.deprecated {
+ schema["deprecated"] = true
+ }
+ if s.nullable {
+ schema["nullable"] = true
+ }
+
+ return schema
+}
+
+// BodyUnionBuilder helps build ObjectSchema with root-level body unions
+type BodyUnionBuilder[T Union] struct {
+ rawPtr *json.RawMessage
+ targetPtr *T
+ parser UnionDef[T]
+ fields map[string]Schema
+}
+
+// BodyUnion creates an ObjectSchema where the request body IS a union.
+// Use this when the entire request body is a discriminated union, not wrapped in a field.
+//
+// Example:
+//
+// type LoginRequest struct {
+// OrgSlug string `json:"-"`
+// BodyRaw json.RawMessage `json:"-"`
+// Auth AuthMethod `json:"-"`
+// }
+//
+// func (r *LoginRequest) Schema() *api.ObjectSchema {
+// return api.BodyUnion(&r.BodyRaw, &r.Auth, AuthMethodParser).
+// WithFields(map[string]api.Schema{
+// "orgSlug": api.String(&r.OrgSlug).Required().From(api.SourcePath),
+// })
+// }
+func BodyUnion[T Union](rawPtr *json.RawMessage, targetPtr *T, parser UnionDef[T]) *BodyUnionBuilder[T] {
+ return &BodyUnionBuilder[T]{
+ rawPtr: rawPtr,
+ targetPtr: targetPtr,
+ parser: parser,
+ }
+}
+
+// WithFields adds non-body fields (path, query, header params) to the schema
+func (b *BodyUnionBuilder[T]) WithFields(fields map[string]Schema) *ObjectSchema {
+ unionSchema := UnionFrom(b.rawPtr, b.targetPtr, b.parser).Required()
+
+ order := make([]string, 0, len(fields))
+ for k := range fields {
+ order = append(order, k)
+ }
+
+ return &ObjectSchema{
+ properties: fields,
+ propertyOrder: order,
+ bodyUnion: &bodyUnionConfig{
+ rawPtr: b.rawPtr,
+ targetPtr: b.targetPtr,
+ parser: b.parser,
+ schema: unionSchema,
+ },
+ }
+}
+
+// Build creates the ObjectSchema with just the body union (no extra fields)
+func (b *BodyUnionBuilder[T]) Build() *ObjectSchema {
+ return b.WithFields(nil)
+}
diff --git a/backend-go/pkg/api/union_helpers_test.go b/backend-go/pkg/api/union_helpers_test.go
new file mode 100644
index 0000000000..79ad6bc2b4
--- /dev/null
+++ b/backend-go/pkg/api/union_helpers_test.go
@@ -0,0 +1,430 @@
+package api
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "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 ---
+
+type PetRequest struct {
+ Name string `json:"name"`
+ PetRaw json.RawMessage `json:"pet"`
+ Pet Animal `json:"-"`
+}
+
+func (r *PetRequest) UnmarshalJSON(data []byte) error {
+ type Plain PetRequest
+ if err := json.Unmarshal(data, (*Plain)(r)); err != nil {
+ return err
+ }
+ return ParseUnionField(r.PetRaw, &r.Pet, AnimalParser)
+}
+
+func TestParseUnionField_InRequest(t *testing.T) {
+ data := []byte(`{
+ "name": "Buddy",
+ "pet": {"type": "dog", "breed": "Golden Retriever"}
+ }`)
+
+ var req PetRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Equal(t, "Buddy", req.Name)
+ require.NotNil(t, req.Pet)
+
+ dog, ok := req.Pet.(*Dog)
+ require.True(t, ok)
+ assert.Equal(t, "Golden Retriever", dog.Breed)
+}
+
+func TestParseUnionField_InRequest_NullPet(t *testing.T) {
+ data := []byte(`{
+ "name": "NoPet",
+ "pet": null
+ }`)
+
+ var req PetRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Equal(t, "NoPet", req.Name)
+ assert.Nil(t, req.Pet)
+}
+
+func TestParseUnionField_InRequest_MissingPet(t *testing.T) {
+ data := []byte(`{
+ "name": "NoPet"
+ }`)
+
+ var req PetRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Equal(t, "NoPet", req.Name)
+ assert.Nil(t, req.Pet)
+}
+
+// --- NestedUnionDef Tests ---
+
+// Test types for nested union
+type NestedAuthMethod interface {
+ Union
+ nestedAuthMarker()
+}
+
+type PasswordPayload struct {
+ Username string `json:"username"`
+ Password string `json:"password"`
+}
+
+func (p *PasswordPayload) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "username": String(&p.Username).Required().MinLength(1),
+ "password": String(&p.Password).Required().MinLength(8),
+ })
+}
+
+func (p *PasswordPayload) unionMarker() {}
+func (p *PasswordPayload) nestedAuthMarker() {}
+
+type OAuthPayload struct {
+ Provider string `json:"provider"`
+ AccessToken string `json:"accessToken"`
+}
+
+func (o *OAuthPayload) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "provider": String(&o.Provider).Required().Enum("google", "github"),
+ "accessToken": String(&o.AccessToken).Required(),
+ })
+}
+
+func (o *OAuthPayload) unionMarker() {}
+func (o *OAuthPayload) nestedAuthMarker() {}
+
+var NestedAuthParser = NestedUnionDef[NestedAuthMethod]{
+ Discriminator: "method",
+ PayloadField: "payload",
+ Variants: map[string]func() NestedAuthMethod{
+ "password": func() NestedAuthMethod { return &PasswordPayload{} },
+ "oauth": func() NestedAuthMethod { return &OAuthPayload{} },
+ },
+}
+
+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}`)
+
+ _, err := NestedAuthParser.Parse(data)
+ require.Error(t, err)
+}
+
+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")
+}
+
+func TestNestedUnionDef_ParseWithType_Null(t *testing.T) {
+ payload := json.RawMessage(`null`)
+
+ // 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")
+}
+
+func TestNestedUnionDef_OpenAPI(t *testing.T) {
+ openapi := NestedAuthParser.OpenAPI()
+
+ 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)
+ assert.Equal(t, "string", methodProp["type"])
+
+ 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)
+ _, hasOneOf := payloadProp["oneOf"]
+ assert.True(t, hasOneOf)
+
+ // Check required fields
+ required, ok := openapi["required"].([]string)
+ require.True(t, ok)
+ assert.Contains(t, required, "method")
+ assert.Contains(t, required, "payload")
+}
+
+// --- ParseNestedUnionField Tests ---
+
+type NestedLoginRequest struct {
+ ClientID string `json:"clientId"`
+ MethodRaw json.RawMessage `json:"method"`
+ PayloadRaw json.RawMessage `json:"payload"`
+ Auth NestedAuthMethod `json:"-"`
+}
+
+func (r *NestedLoginRequest) UnmarshalJSON(data []byte) error {
+ type Plain NestedLoginRequest
+ if err := json.Unmarshal(data, (*Plain)(r)); err != nil {
+ return err
+ }
+ return ParseNestedUnionField(r.MethodRaw, r.PayloadRaw, &r.Auth, NestedAuthParser)
+}
+
+func TestParseNestedUnionField_InRequest(t *testing.T) {
+ data := []byte(`{
+ "clientId": "app-123",
+ "method": "password",
+ "payload": {"username": "john", "password": "secret123"}
+ }`)
+
+ var req NestedLoginRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Equal(t, "app-123", req.ClientID)
+ require.NotNil(t, req.Auth)
+
+ 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"}
+ }`)
+
+ var req NestedLoginRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Nil(t, req.Auth) // Discriminator is null, so no auth
+}
+
+func TestParseNestedUnionField_MissingDiscriminator(t *testing.T) {
+ data := []byte(`{
+ "clientId": "app-123",
+ "payload": {"username": "john", "password": "secret123"}
+ }`)
+
+ var req NestedLoginRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Nil(t, req.Auth) // Discriminator missing, so no auth
+}
+
+// --- Multiple Union Fields Test ---
+
+type MultiUnionRequestHelper struct {
+ PetRaw json.RawMessage `json:"pet"`
+ AuthRaw json.RawMessage `json:"auth"`
+ Pet Animal `json:"-"`
+ Auth NestedAuthMethod `json:"-"`
+}
+
+func (r *MultiUnionRequestHelper) UnmarshalJSON(data []byte) error {
+ type Plain MultiUnionRequestHelper
+ if err := json.Unmarshal(data, (*Plain)(r)); err != nil {
+ return err
+ }
+
+ if err := ParseUnionField(r.PetRaw, &r.Pet, AnimalParser); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func TestMultipleUnionFields_Helper(t *testing.T) {
+ data := []byte(`{
+ "pet": {"type": "cat", "color": "black"},
+ "auth": null
+ }`)
+
+ var req MultiUnionRequestHelper
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ require.NotNil(t, req.Pet)
+ cat, ok := req.Pet.(*Cat)
+ require.True(t, ok)
+ assert.Equal(t, "black", cat.Color)
+}
diff --git a/backend-go/pkg/api/union_test.go b/backend-go/pkg/api/union_test.go
new file mode 100644
index 0000000000..3a27fd07ff
--- /dev/null
+++ b/backend-go/pkg/api/union_test.go
@@ -0,0 +1,451 @@
+package api
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// --- Test Union Types ---
+
+type Animal interface {
+ Union
+ animalMarker()
+}
+
+type Dog struct {
+ Type string `json:"type"`
+ Breed string `json:"breed"`
+}
+
+func (d *Dog) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "type": String(&d.Type).Required(),
+ "breed": String(&d.Breed).Required().MinLength(1),
+ })
+}
+
+func (d *Dog) unionMarker() {}
+func (d *Dog) animalMarker() {}
+
+type Cat struct {
+ Type string `json:"type"`
+ Color string `json:"color"`
+}
+
+func (c *Cat) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "type": String(&c.Type).Required(),
+ "color": String(&c.Color).Required().MinLength(1),
+ })
+}
+
+func (c *Cat) unionMarker() {}
+func (c *Cat) animalMarker() {}
+
+var AnimalParser = UnionDef[Animal]{
+ Discriminator: "type",
+ Variants: map[string]func() Animal{
+ "dog": func() Animal { return &Dog{} },
+ "cat": func() Animal { return &Cat{} },
+ },
+}
+
+// --- UnionDef.Parse Tests ---
+
+func TestUnionDef_Parse_Dog(t *testing.T) {
+ data := json.RawMessage(`{"type": "dog", "breed": "Labrador"}`)
+
+ animal, err := AnimalParser.Parse(data)
+ 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 TestUnionDef_Parse_Cat(t *testing.T) {
+ data := json.RawMessage(`{"type": "cat", "color": "orange"}`)
+
+ animal, err := AnimalParser.Parse(data)
+ 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 TestUnionDef_Parse_UnknownType(t *testing.T) {
+ data := json.RawMessage(`{"type": "bird", "wingspan": 2}`)
+
+ _, err := AnimalParser.Parse(data)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "unknown type value")
+ assert.Contains(t, err.Error(), "bird")
+}
+
+func TestUnionDef_Parse_MissingDiscriminator(t *testing.T) {
+ data := json.RawMessage(`{"breed": "Labrador"}`)
+
+ _, err := AnimalParser.Parse(data)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "missing discriminator")
+}
+
+func TestUnionDef_Parse_InvalidJSON(t *testing.T) {
+ data := json.RawMessage(`{invalid}`)
+
+ _, err := AnimalParser.Parse(data)
+ require.Error(t, err)
+}
+
+func TestUnionDef_Parse_Null(t *testing.T) {
+ data := json.RawMessage(`null`)
+
+ animal, err := AnimalParser.Parse(data)
+ require.NoError(t, err)
+ assert.Nil(t, animal)
+}
+
+func TestUnionDef_Parse_Empty(t *testing.T) {
+ var data json.RawMessage
+
+ animal, err := AnimalParser.Parse(data)
+ require.NoError(t, err)
+ assert.Nil(t, animal)
+}
+
+// --- Custom Discriminator Field ---
+
+type Vehicle interface {
+ Union
+ vehicleMarker()
+}
+
+type Car struct {
+ Kind string `json:"kind"`
+ Doors int `json:"doors"`
+}
+
+func (c *Car) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "kind": String(&c.Kind).Required(),
+ "doors": Int(&c.Doors).Required(),
+ })
+}
+
+func (c *Car) unionMarker() {}
+func (c *Car) vehicleMarker() {}
+
+type Bike struct {
+ Kind string `json:"kind"`
+ Gears int `json:"gears"`
+}
+
+func (b *Bike) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "kind": String(&b.Kind).Required(),
+ "gears": Int(&b.Gears).Required(),
+ })
+}
+
+func (b *Bike) unionMarker() {}
+func (b *Bike) vehicleMarker() {}
+
+var VehicleParser = UnionDef[Vehicle]{
+ Discriminator: "kind",
+ Variants: map[string]func() Vehicle{
+ "car": func() Vehicle { return &Car{} },
+ "bike": func() Vehicle { return &Bike{} },
+ },
+}
+
+func TestUnionDef_Parse_CustomDiscriminator(t *testing.T) {
+ data := json.RawMessage(`{"kind": "car", "doors": 4}`)
+
+ vehicle, err := VehicleParser.Parse(data)
+ require.NoError(t, err)
+
+ car, ok := vehicle.(*Car)
+ require.True(t, ok)
+ assert.Equal(t, "car", car.Kind)
+ assert.Equal(t, 4, car.Doors)
+}
+
+// --- ParseUnions Helper Tests ---
+
+type CreatePetRequest struct {
+ Name string `json:"name"`
+ Animal Animal `json:"-"`
+}
+
+func (r *CreatePetRequest) UnmarshalJSON(data []byte) error {
+ type Plain CreatePetRequest
+ if err := json.Unmarshal(data, (*Plain)(r)); err != nil {
+ return err
+ }
+ return ParseUnions(data,
+ U("animal", &r.Animal, AnimalParser),
+ )
+}
+
+func TestParseUnions_SingleField(t *testing.T) {
+ data := []byte(`{
+ "name": "Buddy",
+ "animal": {"type": "dog", "breed": "Golden Retriever"}
+ }`)
+
+ var req CreatePetRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Equal(t, "Buddy", req.Name)
+ require.NotNil(t, req.Animal)
+
+ dog, ok := req.Animal.(*Dog)
+ require.True(t, ok)
+ assert.Equal(t, "Golden Retriever", dog.Breed)
+}
+
+func TestParseUnions_NullField(t *testing.T) {
+ data := []byte(`{
+ "name": "NoAnimal",
+ "animal": null
+ }`)
+
+ var req CreatePetRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Equal(t, "NoAnimal", req.Name)
+ assert.Nil(t, req.Animal)
+}
+
+func TestParseUnions_MissingField(t *testing.T) {
+ data := []byte(`{
+ "name": "NoAnimal"
+ }`)
+
+ var req CreatePetRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ assert.Equal(t, "NoAnimal", req.Name)
+ assert.Nil(t, req.Animal)
+}
+
+func TestParseUnions_InvalidUnion(t *testing.T) {
+ data := []byte(`{
+ "name": "Invalid",
+ "animal": {"type": "unknown"}
+ }`)
+
+ var req CreatePetRequest
+ err := json.Unmarshal(data, &req)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "animal")
+}
+
+// --- Multiple Union Fields ---
+
+type MultiUnionRequest struct {
+ Pet Animal `json:"-"`
+ Vehicle Vehicle `json:"-"`
+}
+
+func (r *MultiUnionRequest) UnmarshalJSON(data []byte) error {
+ return ParseUnions(data,
+ U("pet", &r.Pet, AnimalParser),
+ U("vehicle", &r.Vehicle, VehicleParser),
+ )
+}
+
+func TestParseUnions_MultipleFields(t *testing.T) {
+ data := []byte(`{
+ "pet": {"type": "cat", "color": "black"},
+ "vehicle": {"kind": "bike", "gears": 21}
+ }`)
+
+ var req MultiUnionRequest
+ err := json.Unmarshal(data, &req)
+ require.NoError(t, err)
+
+ cat, ok := req.Pet.(*Cat)
+ require.True(t, ok)
+ assert.Equal(t, "black", cat.Color)
+
+ bike, ok := req.Vehicle.(*Bike)
+ require.True(t, ok)
+ assert.Equal(t, 21, bike.Gears)
+}
+
+// --- UnionDef.OpenAPI Tests ---
+
+func TestUnionDef_OpenAPI(t *testing.T) {
+ openapi := AnimalParser.OpenAPI()
+
+ oneOf, ok := openapi["oneOf"].([]map[string]any)
+ require.True(t, ok)
+ assert.Len(t, oneOf, 2)
+
+ disc, ok := openapi["discriminator"].(map[string]any)
+ require.True(t, ok)
+ assert.Equal(t, "type", disc["propertyName"])
+ // mapping is omitted for inline schemas
+ _, hasMapping := disc["mapping"]
+ assert.False(t, hasMapping)
+}
+
+// --- UnionSchema Tests ---
+
+func TestUnionSchema_Validate_Required(t *testing.T) {
+ var animal Animal
+ schema := UnionField(&animal, AnimalParser).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+}
+
+func TestUnionSchema_Validate_Optional(t *testing.T) {
+ var animal Animal
+ schema := UnionField(&animal, AnimalParser).Optional()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestUnionSchema_Validate_WithValue(t *testing.T) {
+ dog := &Dog{Type: "dog", Breed: "Poodle"}
+ var animal Animal = dog
+ schema := UnionField(&animal, AnimalParser).Required()
+
+ errs := schema.Validate()
+ assert.Empty(t, errs)
+}
+
+func TestUnionSchema_Validate_InvalidValue(t *testing.T) {
+ dog := &Dog{Type: "dog", Breed: ""} // Breed is required, minlength 1
+ var animal Animal = dog
+ schema := UnionField(&animal, AnimalParser).Required()
+
+ errs := schema.Validate()
+ require.Len(t, errs, 1)
+ assert.Equal(t, "required", errs[0].Code)
+}
+
+func TestUnionSchema_OpenAPI(t *testing.T) {
+ var animal Animal
+ schema := UnionField(&animal, AnimalParser).
+ Required().
+ Title("Pet").
+ Description("The animal").
+ Deprecated().
+ Nullable()
+
+ openapi := schema.OpenAPI()
+
+ assert.NotNil(t, openapi["oneOf"])
+ assert.NotNil(t, openapi["discriminator"])
+ assert.Equal(t, "Pet", openapi["title"])
+ assert.Equal(t, "The animal", openapi["description"])
+ assert.Equal(t, true, openapi["deprecated"])
+ assert.Equal(t, true, openapi["nullable"])
+}
+
+func TestUnionSchema_IsRequired(t *testing.T) {
+ var animal Animal
+ schema := UnionField(&animal, AnimalParser).Required()
+ assert.True(t, schema.IsRequired())
+
+ schema = UnionField(&animal, AnimalParser).Optional()
+ assert.False(t, schema.IsRequired())
+}
+
+// --- Nested Union Tests ---
+
+type NestedAnimal interface {
+ Union
+ nestedAnimalMarker()
+}
+
+type WildDog struct {
+ Type string `json:"type"`
+ Breed string `json:"breed"`
+ Region string `json:"region"`
+}
+
+func (w *WildDog) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "type": String(&w.Type).Required(),
+ "breed": String(&w.Breed).Required(),
+ "region": String(&w.Region).Required(),
+ })
+}
+
+func (w *WildDog) unionMarker() {}
+func (w *WildDog) nestedAnimalMarker() {}
+
+type DomesticDog struct {
+ Type string `json:"type"`
+ Breed string `json:"breed"`
+ Owner string `json:"owner"`
+}
+
+func (d *DomesticDog) Schema() *ObjectSchema {
+ return Object(map[string]Schema{
+ "type": String(&d.Type).Required(),
+ "breed": String(&d.Breed).Required(),
+ "owner": String(&d.Owner).Required(),
+ })
+}
+
+func (d *DomesticDog) unionMarker() {}
+func (d *DomesticDog) nestedAnimalMarker() {}
+
+var NestedDogParser = UnionDef[NestedAnimal]{
+ Discriminator: "type",
+ Variants: map[string]func() NestedAnimal{
+ "wild": func() NestedAnimal { return &WildDog{} },
+ "domestic": func() NestedAnimal { return &DomesticDog{} },
+ },
+}
+
+type Shelter struct {
+ Name string `json:"name"`
+ Animal NestedAnimal `json:"-"`
+}
+
+func (s *Shelter) UnmarshalJSON(data []byte) error {
+ type Plain Shelter
+ if err := json.Unmarshal(data, (*Plain)(s)); err != nil {
+ return err
+ }
+ return ParseUnions(data,
+ U("animal", &s.Animal, NestedDogParser),
+ )
+}
+
+func TestNestedUnion_Parse(t *testing.T) {
+ data := []byte(`{
+ "name": "Happy Paws",
+ "animal": {"type": "wild", "breed": "Wolf", "region": "Alaska"}
+ }`)
+
+ var shelter Shelter
+ err := json.Unmarshal(data, &shelter)
+ require.NoError(t, err)
+
+ assert.Equal(t, "Happy Paws", shelter.Name)
+
+ wild, ok := shelter.Animal.(*WildDog)
+ require.True(t, ok)
+ assert.Equal(t, "Wolf", wild.Breed)
+ assert.Equal(t, "Alaska", wild.Region)
+}
diff --git a/backend-go/pkg/example/main.go b/backend-go/pkg/example/main.go
new file mode 100644
index 0000000000..2a43cd5bcc
--- /dev/null
+++ b/backend-go/pkg/example/main.go
@@ -0,0 +1,541 @@
+//go:build ignore
+
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "log"
+ "net/http"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/go-chi/chi/v5/middleware"
+ "github.com/google/uuid"
+ "github.com/infisical/api/pkg/api"
+)
+
+// =============================================================================
+// Union Types for Webhook Targets
+// =============================================================================
+
+// WebhookTarget is the union interface for delivery targets.
+// All variants must embed api.UnionBase and implement Schema().
+type WebhookTarget interface {
+ api.Union
+ Deliver(payload []byte) error
+}
+
+// HTTPTarget delivers webhooks via HTTP
+type HTTPTarget struct {
+ api.UnionBase
+ Type string `json:"type"`
+ URL string `json:"url"`
+ Method string `json:"method"`
+ Headers map[string]string `json:"headers,omitempty"`
+}
+
+func (h *HTTPTarget) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "type": api.Const("http"),
+ "url": api.String(&h.URL).Required().URL(),
+ "method": api.String(&h.Method).Required().Enum("POST", "PUT"),
+ "headers": api.Map(api.String(nil)).Optional(),
+ })
+}
+
+func (h *HTTPTarget) Deliver(payload []byte) error {
+ log.Printf("HTTP %s to %s", h.Method, h.URL)
+ return nil
+}
+
+// SlackTarget delivers webhooks to Slack
+type SlackTarget struct {
+ api.UnionBase
+ Type string `json:"type"`
+ WebhookURL string `json:"webhookUrl"`
+ Channel string `json:"channel,omitempty"`
+}
+
+func (s *SlackTarget) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "type": api.Const("slack"),
+ "webhookUrl": api.String(&s.WebhookURL).Required().URL(),
+ "channel": api.String(&s.Channel).Optional().Pattern(`^#[a-z0-9_-]+$`),
+ })
+}
+
+func (s *SlackTarget) Deliver(payload []byte) error {
+ log.Printf("Slack to %s", s.Channel)
+ return nil
+}
+
+// DiscordTarget delivers webhooks to Discord
+type DiscordTarget struct {
+ api.UnionBase
+ Type string `json:"type"`
+ WebhookURL string `json:"webhookUrl"`
+}
+
+func (d *DiscordTarget) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "type": api.Const("discord"),
+ "webhookUrl": api.String(&d.WebhookURL).Required().URL(),
+ })
+}
+
+func (d *DiscordTarget) Deliver(payload []byte) error {
+ log.Printf("Discord webhook")
+ return nil
+}
+
+// WebhookTargetParser parses webhook target union
+var WebhookTargetParser = api.UnionDef[WebhookTarget]{
+ Discriminator: "type",
+ Variants: map[string]func() WebhookTarget{
+ "http": func() WebhookTarget { return &HTTPTarget{} },
+ "slack": func() WebhookTarget { return &SlackTarget{} },
+ "discord": func() WebhookTarget { return &DiscordTarget{} },
+ },
+}
+
+// =============================================================================
+// Union Types for Auth Methods
+// =============================================================================
+
+type AuthMethod interface {
+ api.Union
+ GetIdentifier() string
+}
+
+type PasswordAuth struct {
+ api.UnionBase
+ Method string `json:"method"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+}
+
+func (p *PasswordAuth) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "method": api.Const("password"),
+ "username": api.String(&p.Username).Required().MinLength(1),
+ "password": api.String(&p.Password).Required().MinLength(8),
+ })
+}
+
+func (p *PasswordAuth) GetIdentifier() string { return p.Username }
+
+type SAMLAuth struct {
+ api.UnionBase
+ Method string `json:"method"`
+ SAMLResponse string `json:"samlResponse"`
+}
+
+func (s *SAMLAuth) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "method": api.Const("saml"),
+ "samlResponse": api.String(&s.SAMLResponse).Required(),
+ })
+}
+
+func (s *SAMLAuth) GetIdentifier() string { return "saml-user" }
+
+type OIDCAuth struct {
+ api.UnionBase
+ Method string `json:"method"`
+ Code string `json:"code"`
+ RedirectURI string `json:"redirectUri"`
+}
+
+func (o *OIDCAuth) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "method": api.Const("oidc"),
+ "code": api.String(&o.Code).Required(),
+ "redirectUri": api.String(&o.RedirectURI).Required().URL(),
+ })
+}
+
+func (o *OIDCAuth) GetIdentifier() string { return "oidc-user" }
+
+var AuthMethodParser = api.UnionDef[AuthMethod]{
+ Discriminator: "method",
+ Variants: map[string]func() AuthMethod{
+ "password": func() AuthMethod { return &PasswordAuth{} },
+ "saml": func() AuthMethod { return &SAMLAuth{} },
+ "oidc": func() AuthMethod { return &OIDCAuth{} },
+ },
+}
+
+// =============================================================================
+// Request/Response Types
+// =============================================================================
+
+type ListUsersRequest struct {
+ OrgID uuid.UUID `json:"-"`
+ Page int `json:"-"`
+ PageSize int `json:"-"`
+ Role string `json:"-"`
+}
+
+func (r *ListUsersRequest) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "orgId": api.UUID(&r.OrgID).Required().From(api.SourcePath),
+ "page": api.Int(&r.Page).Optional().Min(1).Default(1).From(api.SourceQuery),
+ "pageSize": api.Int(&r.PageSize).Optional().Min(1).Max(100).Default(20).From(api.SourceQuery),
+ "role": api.String(&r.Role).Optional().Enum("admin", "member", "viewer").From(api.SourceQuery),
+ })
+}
+
+type CreateUserRequest struct {
+ OrgID uuid.UUID `json:"-"`
+ Email string `json:"email"`
+ Name string `json:"name"`
+ Role string `json:"role"`
+}
+
+func (r *CreateUserRequest) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "orgId": api.UUID(&r.OrgID).Required().From(api.SourcePath),
+ "email": api.String(&r.Email).Required().EmailStrict(),
+ "name": api.String(&r.Name).Required().MinLength(1).MaxLength(100),
+ "role": api.String(&r.Role).Required().Enum("admin", "member", "viewer"),
+ })
+}
+
+// PATCH request with tri-state nullable fields
+type UpdateUserRequest struct {
+ OrgID uuid.UUID `json:"-"`
+ UserID uuid.UUID `json:"-"`
+ Name api.JsonNullable[string] `json:"name"`
+ Role api.JsonNullable[string] `json:"role"`
+}
+
+func (r *UpdateUserRequest) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "orgId": api.UUID(&r.OrgID).Required().From(api.SourcePath),
+ "userId": api.UUID(&r.UserID).Required().From(api.SourcePath),
+ "name": api.Nullable(&r.Name, api.String(&r.Name.Value).MinLength(1).MaxLength(100)).Optional(),
+ "role": api.Nullable(&r.Role, api.String(&r.Role.Value).Enum("admin", "member", "viewer")).Optional(),
+ })
+}
+
+// Request with union type - connected experience
+type CreateWebhookRequest struct {
+ ProjectID uuid.UUID `json:"-"`
+ Name string `json:"name"`
+ Events []string `json:"events"`
+ TargetRaw json.RawMessage `json:"target"`
+ Target WebhookTarget `json:"-"` // Parsed automatically by UnionFrom
+ Enabled bool `json:"enabled"`
+}
+
+func (r *CreateWebhookRequest) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "projectId": api.UUID(&r.ProjectID).Required().From(api.SourcePath),
+ "name": api.String(&r.Name).Required().MinLength(1).MaxLength(100),
+ "events": api.Array(api.String(nil).Enum("secret.created", "secret.updated", "secret.deleted")).Required(),
+ // Connected union: parses TargetRaw → Target, validates variant, generates OpenAPI
+ "target": api.UnionFrom(&r.TargetRaw, &r.Target, WebhookTargetParser).Required(),
+ "enabled": api.Bool(&r.Enabled).Optional().Default(true),
+ })
+}
+
+type LoginRequest struct {
+ OrgSlug string `json:"-"`
+ AuthMethodRaw json.RawMessage `json:"authMethod"`
+ Auth AuthMethod `json:"-"` // Parsed automatically by UnionFrom
+}
+
+func (r *LoginRequest) Schema() *api.ObjectSchema {
+ return api.Object(map[string]api.Schema{
+ "orgSlug": api.String(&r.OrgSlug).Required().From(api.SourcePath).Pattern(`^[a-z0-9-]+$`),
+ // Connected union: parses AuthMethodRaw → Auth, validates variant, generates OpenAPI
+ "authMethod": api.UnionFrom(&r.AuthMethodRaw, &r.Auth, AuthMethodParser).Required(),
+ })
+}
+
+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
+// =============================================================================
+
+type JWTValidator struct{}
+
+func (v *JWTValidator) Validate(ctx context.Context, r *http.Request) (any, error) {
+ auth := r.Header.Get("Authorization")
+ if auth == "" || len(auth) < 7 || auth[:7] != "Bearer " {
+ return nil, api.ErrSkipToNextAuth
+ }
+ return map[string]any{"sub": "user-123"}, nil
+}
+
+type APIKeyValidator struct{}
+
+func (v *APIKeyValidator) Validate(ctx context.Context, r *http.Request) (any, error) {
+ if r.Header.Get("X-API-Key") == "" {
+ return nil, api.ErrSkipToNextAuth
+ }
+ return map[string]any{"keyId": "key-123"}, nil
+}
+
+// =============================================================================
+// Handlers
+// =============================================================================
+
+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,
+ })
+}
+
+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,
+ })
+}
+
+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
+ }
+
+ // Tri-state PATCH handling
+ changes := map[string]any{}
+ if req.Name.IsSet() {
+ changes["name"] = req.Name.Value
+ } else if req.Name.Null {
+ changes["name"] = nil // explicitly clear
+ }
+ // !req.Name.Present = don't touch
+
+ if req.Role.IsSet() {
+ changes["role"] = req.Role.Value
+ }
+
+ writeJSON(w, http.StatusOK, map[string]any{"changes": changes})
+}
+
+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
+ }
+
+ // req.Target is already parsed and validated by UnionFrom!
+ switch t := req.Target.(type) {
+ case *HTTPTarget:
+ log.Printf("Creating HTTP webhook: %s %s", t.Method, t.URL)
+ case *SlackTarget:
+ log.Printf("Creating Slack webhook: %s", t.Channel)
+ case *DiscordTarget:
+ log.Printf("Creating Discord webhook")
+ }
+
+ writeJSON(w, http.StatusCreated, map[string]any{
+ "id": uuid.New(),
+ "name": req.Name,
+ "target": req.Target,
+ "enabled": req.Enabled,
+ })
+}
+
+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
+ }
+
+ // req.Auth is already parsed and validated by UnionFrom!
+ switch auth := req.Auth.(type) {
+ case *PasswordAuth:
+ log.Printf("Password login: %s", auth.Username)
+ case *SAMLAuth:
+ log.Printf("SAML login")
+ case *OIDCAuth:
+ 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())
+ }
+}
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+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 writeError(w http.ResponseWriter, status int, code, msg string) {
+ writeJSON(w, status, ErrorResponse{Error: msg, Code: code})
+}
+
+// =============================================================================
+// Main
+// =============================================================================
+
+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{},
+ })
+
+ // 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{},
+ })
+
+ // 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
+ })
+
+ // 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)"},
+ },
+ })
+ spec.AddEndpoints(root.Endpoints())
+
+ // Chi router
+ r := chi.NewRouter()
+ r.Use(middleware.Logger)
+ r.Use(middleware.Recoverer)
+
+ 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)
+ }
+ }
+ })
+
+ log.Println("Server: http://localhost:8080")
+ log.Println("OpenAPI: http://localhost:8080/openapi.json")
+ log.Println("")
+ log.Println("Examples:")
+ log.Println(` curl -X POST localhost:8080/auth/acme/login -H "Content-Type: application/json" \`)
+ log.Println(` -d '{"authMethod":{"method":"password","username":"alice","password":"secret123"}}'`)
+ log.Println("")
+ log.Println(` curl -X POST localhost:8080/projects/$(uuidgen)/webhooks -H "Authorization: Bearer x" \`)
+ log.Println(` -H "Content-Type: application/json" \`)
+ log.Println(` -d '{"name":"Hook","events":["secret.created"],"target":{"type":"slack","webhookUrl":"https://hooks.slack.com/x","channel":"#alerts"}}'`)
+ 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.Fatal(http.ListenAndServe(":8080", r))
+}
diff --git a/backend-go/pkg/example/openapi.json b/backend-go/pkg/example/openapi.json
new file mode 100644
index 0000000000..b67eaacbb1
--- /dev/null
+++ b/backend-go/pkg/example/openapi.json
@@ -0,0 +1,501 @@
+{
+ "components": {
+ "securitySchemes": {
+ "apiKey": {
+ "in": "header",
+ "name": "X-API-Key",
+ "type": "apiKey"
+ },
+ "bearer": {
+ "bearerFormat": "JWT",
+ "scheme": "bearer",
+ "type": "http"
+ }
+ }
+ },
+ "info": {
+ "description": "Demonstrates unions, tri-state PATCH, validation, and OpenAPI generation",
+ "title": "Example API",
+ "version": "1.0.0"
+ },
+ "openapi": "3.0.3",
+ "paths": {
+ "/auth/{orgSlug}/login": {
+ "post": {
+ "operationId": "login",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "orgSlug",
+ "required": true,
+ "schema": {
+ "pattern": "^[a-z0-9-]+$",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "properties": {
+ "authMethod": {
+ "discriminator": {
+ "propertyName": "method"
+ },
+ "oneOf": [
+ {
+ "properties": {
+ "method": {
+ "enum": [
+ "password"
+ ],
+ "type": "string"
+ },
+ "password": {
+ "minLength": 8,
+ "type": "string"
+ },
+ "username": {
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [
+ "username",
+ "password"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "method": {
+ "enum": [
+ "saml"
+ ],
+ "type": "string"
+ },
+ "samlResponse": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "samlResponse"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "code": {
+ "type": "string"
+ },
+ "method": {
+ "enum": [
+ "oidc"
+ ],
+ "type": "string"
+ },
+ "redirectUri": {
+ "format": "url",
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "redirectUri"
+ ],
+ "type": "object"
+ }
+ ]
+ }
+ },
+ "required": [
+ "authMethod"
+ ],
+ "type": "object"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful response"
+ }
+ },
+ "summary": "Login (union: password|saml|oidc)",
+ "tags": [
+ "auth"
+ ]
+ }
+ },
+ "/orgs/{orgId}/users": {
+ "get": {
+ "operationId": "listUsers",
+ "parameters": [
+ {
+ "in": "query",
+ "name": "role",
+ "required": false,
+ "schema": {
+ "enum": [
+ "admin",
+ "member",
+ "viewer"
+ ],
+ "type": "string"
+ }
+ },
+ {
+ "in": "path",
+ "name": "orgId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ },
+ {
+ "in": "query",
+ "name": "page",
+ "required": false,
+ "schema": {
+ "default": 1,
+ "format": "int64",
+ "minimum": 1,
+ "type": "integer"
+ }
+ },
+ {
+ "in": "query",
+ "name": "pageSize",
+ "required": false,
+ "schema": {
+ "default": 20,
+ "format": "int64",
+ "maximum": 100,
+ "minimum": 1,
+ "type": "integer"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful response"
+ }
+ },
+ "security": [
+ {
+ "bearer": []
+ },
+ {
+ "apiKey": []
+ }
+ ],
+ "summary": "List users",
+ "tags": [
+ "users"
+ ]
+ },
+ "post": {
+ "operationId": "createUser",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "orgId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "properties": {
+ "email": {
+ "format": "email-strict",
+ "type": "string"
+ },
+ "name": {
+ "maxLength": 100,
+ "minLength": 1,
+ "type": "string"
+ },
+ "role": {
+ "enum": [
+ "admin",
+ "member",
+ "viewer"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "email",
+ "name",
+ "role"
+ ],
+ "type": "object"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful response"
+ }
+ },
+ "security": [
+ {
+ "bearer": []
+ },
+ {
+ "apiKey": []
+ }
+ ],
+ "summary": "Create user",
+ "tags": [
+ "users"
+ ]
+ }
+ },
+ "/orgs/{orgId}/users/{userId}": {
+ "patch": {
+ "operationId": "updateUser",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "orgId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ },
+ {
+ "in": "path",
+ "name": "userId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "properties": {
+ "name": {
+ "maxLength": 100,
+ "minLength": 1,
+ "nullable": true,
+ "type": "string"
+ },
+ "role": {
+ "enum": [
+ "admin",
+ "member",
+ "viewer"
+ ],
+ "nullable": true,
+ "type": "string"
+ }
+ },
+ "type": "object"
+ }
+ }
+ },
+ "required": false
+ },
+ "responses": {
+ "200": {
+ "description": "Successful response"
+ }
+ },
+ "security": [
+ {
+ "bearer": []
+ },
+ {
+ "apiKey": []
+ }
+ ],
+ "summary": "Update user (PATCH with tri-state)",
+ "tags": [
+ "users"
+ ]
+ }
+ },
+ "/projects/{projectId}/webhooks": {
+ "post": {
+ "operationId": "createWebhook",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "projectId",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "properties": {
+ "enabled": {
+ "default": true,
+ "type": "boolean"
+ },
+ "events": {
+ "items": {
+ "enum": [
+ "secret.created",
+ "secret.updated",
+ "secret.deleted"
+ ],
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "name": {
+ "maxLength": 100,
+ "minLength": 1,
+ "type": "string"
+ },
+ "target": {
+ "discriminator": {
+ "propertyName": "type"
+ },
+ "oneOf": [
+ {
+ "properties": {
+ "channel": {
+ "pattern": "^#[a-z0-9_-]+$",
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "slack"
+ ],
+ "type": "string"
+ },
+ "webhookUrl": {
+ "format": "url",
+ "type": "string"
+ }
+ },
+ "required": [
+ "webhookUrl"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "type": {
+ "enum": [
+ "discord"
+ ],
+ "type": "string"
+ },
+ "webhookUrl": {
+ "format": "url",
+ "type": "string"
+ }
+ },
+ "required": [
+ "webhookUrl"
+ ],
+ "type": "object"
+ },
+ {
+ "properties": {
+ "headers": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ "method": {
+ "enum": [
+ "POST",
+ "PUT"
+ ],
+ "type": "string"
+ },
+ "type": {
+ "enum": [
+ "http"
+ ],
+ "type": "string"
+ },
+ "url": {
+ "format": "url",
+ "type": "string"
+ }
+ },
+ "required": [
+ "url",
+ "method"
+ ],
+ "type": "object"
+ }
+ ]
+ }
+ },
+ "required": [
+ "target",
+ "name",
+ "events"
+ ],
+ "type": "object"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful response"
+ }
+ },
+ "security": [
+ {
+ "bearer": []
+ }
+ ],
+ "summary": "Create webhook (union: http|slack|discord)",
+ "tags": [
+ "webhooks"
+ ]
+ }
+ }
+ },
+ "servers": [
+ {
+ "url": "http://localhost:8080"
+ }
+ ],
+ "tags": [
+ {
+ "description": "Authentication (password, SAML, OIDC)",
+ "name": "auth"
+ },
+ {
+ "description": "User management",
+ "name": "users"
+ },
+ {
+ "description": "Webhooks (HTTP, Slack, Discord)",
+ "name": "webhooks"
+ }
+ ]
+}