Skip to content

AI-4429: standardize router API input validation - #2729

Merged
tbarbugli merged 4 commits into
mainfrom
tommaso/ai-4429-standardize-router-api-input-validation-with
Nov 30, 2026
Merged

tbarbugli merged 4 commits into
mainfrom
tommaso/ai-4429-standardize-router-api-input-validation-with

Conversation

@tbarbugli

Copy link
Copy Markdown
Member

Why

Router HTTP handlers in acceleration/internal/api mixed struct tags, hand-written Body == nil checks, manual ServerSideFrom guards, UnmarshalJSON validation (SessionQuery), and ad-hoc invalidRequest(...) calls inside controllers. This PR standardizes input validation behind one pipeline so invalid inputs and client-side misuse of server-only fields are rejected automatically with structured huma.ErrorDetail errors before handlers run (AI-4429).

How it works

HTTP request
  ├─ 1. Huma decode + struct tags (value Body = required, *T = optional)
  │     └─ failure -> 400 validation_failed (field locations)
  ├─ 2. huma.Resolver / ResolverWithPath on request structs
  │     ├─ *huma.ErrorDetail -> 400 validation_failed (field locations)
  │     └─ APIError          -> preserved status & code (e.g. budget_moved)
  ├─ 3. register() wrapper walks `serverside:"<reason>"` tags
  │     └─ non-server caller sent tagged field -> 403 server_side_only
  └─ 4. Handler (only stored-state and runtime checks remain)
Change Result Proof
register + serverside tag (internal/api/validate.go) Client-side requests sending server-only fields fail with 403 server_side_only before the handler; WebSocket calls refuseServerSideFields TestAFieldOnlyABackendMaySendIsRefusedFromADevice
Value Body T on ~70 required-body requests Missing bodies fail at decode; removes required:"true" tags and nil checks TestAResolverRefusalNamesTheFieldAndIsABadRequest, TestRequestsFollowTheValidationRules
huma.ResolverWithPath on request types Cross-field and format checks run before handlers with huma.ErrorDetail locations TestAResolverRefusalNamesTheFieldAndIsABadRequest, TestARefusalThatNeedsItsOwnCodeIsAnsweredAsItIs
SessionQuery.Resolve + additionalProperties: false Drops UnmarshalJSON validation and SkipValidateBody TestAQueryIsRefusedForAKeyOrALimitItDoesNotTake
Lint ratchet across all registered operations Fails on SkipValidateBody, non-nullable serverside fields, blank reasons, or Body *T with required:"true" TestRequestsFollowTheValidationRules

Changes

  • Added acceleration/internal/api/validate.go (register, reflective serverside tag walker with sorted map keys, refuseServerSideFields, validationRefusal, invalid, problems, blankProblem) and switched every operation registration from huma.Register to register.
  • Converted ~70 required request bodies from *T to value T, dropping required:"true" tags and hand-written nil checks. Nine DLC, channel, and suspension operations gained required: true in acceleration/api/openapi.yaml; regenerated all SDKs (plugins/stream, sdks/js, sdks/ruby, sdks/rust updated; Go, Kotlin, .NET, PHP, Dart, Swift unchanged).
  • Tagged server-side-only fields with serverside:"..." across session create, update, fork, start voice, search, and scheduled task update, and kept HTTP and WebSocket session-create validation messages aligned via a shared body path prefix.
  • Moved pure request validation into Resolve methods for session create, search, detection, images, OCR, classify, responses, respond, say, rewind, voices, transcription/speech, skills, policies, DLC review, phone call placement, campaigns, scheduled tasks, agent configs/patch/sync, and session query.
  • Removed SessionQuery.UnmarshalJSON validation and SkipValidateBody.
  • Documented the validation contract in AGENTS.md ("HTTP API") and .claude/skills/go/SKILL.md.
  • Note on remaining work: store-backed and runtime-dependent validators (such as limits.go, routerconfigs.go, and config store-lookup complaints) remain in handlers for follow-up passes.

Validation

  • go vet -tags=integration ./internal/api/ in acceleration/ — passed (all unit and integration test files compile cleanly).
  • go test -count=1 ./... in acceleration/ — passed across all Go packages (earlier single flake in internal/sts/openairealtime TestRealtimeSuite passed 3/3 on rerun).
  • go run ./cmd/openapi and all SDK generators (go, plugins/stream, kotlin, js, dotnet, php, rust, ruby, dart) — clean and committed.
  • Integration test suites (//go:build integration) — not run locally (handled by CI); assertion updates verified by go vet -tags=integration and static audit against every changed code/message.

…ide fields

Requests are structs: a required body is a value, an optional field a
pointer, and Huma checks the tags before a handler runs. A rule a tag
cannot say is a huma.Resolver that returns huma.ErrorDetails located at the
field. A field only a backend may send carries a serverside tag, and
register refuses a client-side request that sends it with a 403
server_side_only, so no handler checks it by hand. The session socket uses
the same check.

The session query no longer validates in UnmarshalJSON or skips Huma's body
check, and the lint test TestRequestsFollowTheValidationRules keeps the rules.

Nine DLC, channel and suspension request bodies are now required values, so
openapi.yaml marks them required: true; the SDKs need regenerating.
Move policy, voice, DLC review, phone call, campaign, scheduled task and
agent config/patch/sync input checks into huma.Resolver methods. Sort map
keys in sentServerSideFields for deterministic errors, push the body
prefix in refuseSessionRequest so HTTP and WebSocket errors match, update
integration test expectations for validation_failed/serverside messages,
and regenerate the SDKs from api/openapi.yaml.
@tbarbugli
tbarbugli marked this pull request as ready for review November 30, 2026 09:33
Comment thread .claude/skills/go/api.md
type CreateWidgetRequest struct {
// --- Scalar field validation ---
// Required fields are value types; optional fields are pointers.
Name string `json:"name" minLength:"1" maxLength:"80" pattern:"^[a-zA-Z0-9_-]+$" patternDescription:"letters, digits, _ and -"`

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shall we prefix validator stuff do we dont pollute tag space? validator_maxLengh:"..."

Comment thread .claude/skills/go/api.md
// Runs automatically after Huma checks struct tags, before the handler.
// Keep it free of DB/store lookups; return huma.ErrorDetail (via invalid) for
// 400 validation_failed, or an APIError when a custom status/code is needed.
func (r *CreateWidgetRequest) Resolve(_ huma.Context, prefix *huma.PathBuffer) []error {

@thesyncim thesyncim Nov 30, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldnt we handle this with reflection and validator libraries, and only use custom validator code for complex stuff?

it would also help us to describe validation the required validation for open api spec

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes thats what we do Resolve is only for cross fields / more complex validation

@tbarbugli
tbarbugli merged commit 72b95fb into main Nov 30, 2026
28 of 31 checks passed
@tbarbugli
tbarbugli deleted the tommaso/ai-4429-standardize-router-api-input-validation-with branch November 30, 2026 11:11
kanat added a commit that referenced this pull request Nov 30, 2026
createSession's request is still refused by its Resolve and its serverside
tags, as #2729 made it. humabind runs the same check register does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 30, 2026
## Why

Today every API operation is a method on `Server`, in one large package,
and can reach everything the server holds. This PR shows what a
controller looks like in the new layout and how it is registered, using
one operation: `createSession` (`POST /v1/agents/sessions`). The API
itself does not change, `openapi.yaml` is the same as on `main`.

## How it works

### The controller

Every operation becomes a struct that implements one interface:

```go
type Controller[Input, Output any] interface {
	// Spec describes the operation without needing runtime dependencies.
	Spec() Spec
	Handle(ctx context.Context, in Input) (Output, error)
}
```

`Spec` says what the operation is and `Handle` does the work. A
controller does not know about `Server`.

This is `createSession`, without the body of `Handle`:

```go
type CreateSession struct {
	Deps Deps
}

func (CreateSession) Spec() endpoint.Spec {
	return endpoint.Spec{
		Name:              "createSession",
		Summary:           "Join a call as a voice agent",
		Description:       "The whole conversation runs here: ...",
		Status:            http.StatusCreated,
		StatusDescription: "The agent is in the call",
		Access:            endpoint.AccessClientAccessible,
		Errors: map[int]string{
			http.StatusBadRequest: "",
			http.StatusConflict:   "A session with that id already exists, ...",
			// 401, 403 and 404 as well
		},
	}
}

func (c CreateSession) Handle(ctx context.Context, in *payload.CreateSessionInput) (*payload.CreateSessionOutput, error) {
	// the same steps as before, in the same order
}
```

The input and output are structs with a `Body` field, because Huma reads
the request body from a field with that name. Path, query and header
parameters go next to it:

```go
type CreateSessionInput struct {
	Body CreateSessionRequest
}

type CreateSessionOutput struct {
	Body Session
}
```

### What the spec is for

The spec keeps everything we declare about an operation in one place,
next to its code. It is plain data with no Huma types in it, and it can
be read without a running server, which is how `openapi.yaml` is
generated.

| Field | What it is used for |
| --- | --- |
| `Name`, `Summary`, `Description`, `Tags`, `Deprecated` | The operation
in `openapi.yaml`, which the SDKs are generated from |
| `Status`, `StatusDescription` | The status of a successful answer |
| `Access` | Whether an end user's device may call it. An operation that
does not say so is server-side only |
| `Errors` | The errors we document. An empty string keeps the standard
description |
| `Events` | The events an operation can emit. This is a placeholder,
nothing fills or reads it yet |

### How a controller is registered

Each feature has a `routes.go` with its paths:

```go
func Register(api *humabind.API, deps controller.Deps) {
	humabind.Post(api, "/v1/agents/sessions", controller.CreateSession{Deps: deps})
}
```

`newAPI` in `openapi.go` wraps the Huma API once and adds the validators
next to the middleware:

```go
api := humabind.New(humachi.New(router, config))
api.UseMiddleware(nameHumaOperation)
api.UseMiddleware(s.requireStaffKey(api))
api.UseMiddleware(requireCustomer(api))
api.UseValidator(validators...)
```

```
openapi.go: sessions.Register(api, sessionDeps{server: s})
  -> sessions/routes.go: humabind.Post(api, path, CreateSession{Deps: deps})
       -> humabind: turns the Spec into a huma.Operation
            -> RegisterOperation: the validators, then CreateSession.Handle
```

`humabind` also has `Get`, `Put`, `Patch` and `Delete`.

### How the request is checked

The checks from [#2729](#2729)
stay as they are, so `createSession` answers the same errors as on
`main`:

```
request -> Huma decodes it and checks the field tags
        -> CreateSessionRequest.Resolve
        -> serverside tags (validateServerSideFields, 403)
        -> CreateSession.Handle
```

- The validators are one list in `internal/api/validate.go`. The
controllers get it from `UseValidator`, and the other operations from
`register`, so neither can skip the `serverside` tags. `UseValidator`
has to come before the operations, as `UseMiddleware` does. Today the
list holds only `validateServerSideFields`.
- `Resolve` is on the type in `payload`. Its rules read the caller,
which only `internal/api` knows, so `internal/api` sets them in
`payload.CreateSessionProblems`. This is a workaround, like `Deps`.

`TestRequestsFollowTheValidationRules` no longer needs a hook in
production code. It reads the types of the request bodies from the
schema registry of Huma. The registry does not hold path, query and
header parameters, or whether `Body` is a pointer, so the new
`TestRequestStructsFollowTheValidationRules` checks those in the source.

### Dependencies (not final)

A controller gets its dependencies when it is constructed, as
`CreateSession{Deps: deps}`.

**The `Deps` interface in this PR is a workaround, please do not review
it as the final design.** `createSession` calls many helpers on
`Server`, and `Deps` is the quick way to move those calls out of the
controller. `session_deps.go` implements it by calling the existing
helpers.

Dependencies do not have to look like this. Later they may return layers
that several controllers can share, instead of one method for each
helper `createSession` happens to need.

### Folders

```
internal/api/
├─ endpoint/     Spec, Access and the Controller interface
├─ humabind/     turns a Spec into a Huma operation and registers it
├─ events/       placeholder for the events an operation can emit
├─ schema/       types several operations share (Greeting, FloorControl)
├─ sessions/
│  ├─ controller/create_session.go   CreateSession: Spec and Handle
│  ├─ controller/deps.go             Deps
│  ├─ payload/session.go             CreateSessionInput, CreateSessionOutput
│  └─ routes.go                      POST /v1/agents/sessions
└─ session_deps.go                   implements Deps with the Server
```

## Changes

It is easier to review the commits one by one.

- [`38570a9bf`](38570a9bf)
only moves types. A controller in its own package cannot import
`internal/api` without an import cycle, so the types it uses moved out,
and `internal/api` keeps an alias for each one.
- [`55e8ce933`](55e8ce933)
adds the new layout. This is the commit to read closely.
- [`4136c79e9`](4136c79e9)
addresses the review: `humabind.register` is unexported and
`endpoint.go` is now `controller.go`.
- [`3830ff94e`](3830ff94e)
keeps the request checks of #2729 after the rebase.
- [`81653ebd8`](81653ebd8),
[`14c5a659d`](14c5a659d) and
[`a408b0aad`](a408b0aad) name
those checks validators and list them in one place, in `validate.go`.
- [`52c472b2d`](52c472b2d)
passes that list to `sessions.Register`.
- [`140ccf9b4`](140ccf9b4)
makes `Validator` an interface and adds `ValidateFunc`, which turns a
function into a `Validator`.
- [`bb34d0716`](bb34d0716)
makes a validator a plain function, `ValidateFunc`, and removes the
`Validator` interface again.
- [`768d7ebfb`](768d7ebfb)
adds `humabind.New` and `UseValidator`, so `sessions.Register` no longer
takes the validators.
- [`9118cc0d8`](9118cc0d8),
[`6161455f3`](6161455f3) and
[`4f677c536`](4f677c536)
remove the global hook that only `TestRequestsFollowTheValidationRules`
used, and add `TestRequestStructsFollowTheValidationRules`.

All the other operations stay where they are.

## Validation

| Check | Result |
| --- | --- |
| `go build ./...`, `go vet ./internal/api/...`, also with `-tags
integration`, at `4f677c536` | pass |
| `go test ./internal/api/...` at `4f677c536` | pass |
| `go test -tags integration ./internal/api` at `3830ff94e`, before the
validator commits | 2 tests of `TestResponsesAskedSuite` fail because
`ffmpeg` is not installed on my machine, and the same 2 fail on `main`
(`07fa7a972`). No other test fails |
| `go run ./cmd/openapi` at `4f677c536` | `openapi.yaml` is identical to
`main` |
| 75 requests to `createSession` (25 bodies, as an anonymous caller, a
user and a backend), at `3830ff94e`, before the validator commits | the
same answers as on `main` |

`TestCreateSessionRefusesItsRequestOverHTTP` fails when `createSession`
skips the `serverside` tags or `Resolve`. The existing HTTP tests in
`internal/api` cover the rest.

<details><summary>What each new test in <code>humabind_test.go</code>
catches</summary>

| Defect | Test |
| --- | --- |
| The status or the body is not passed through |
`TestBodyControllerDecodesRequestAndWritesStatusAndResponse` |
| A registered controller skips a validator, or they run out of order |
`TestValidatorsRefuseInOrderBeforeTheController` |
| A missing body reaches the controller |
`TestBodyControllerRefusesMissingRequestBody` |
| The envelope shows up in the OpenAPI schemas, or a described error
loses its text | `TestBodyControllerUsesWireDTOComponentsInOpenAPI` |
| A server-only operation is marked `x-client-accessible` |
`TestAccessControlsClientAccessibleOpenAPIExtension` |
| A typo in `Access` is accepted |
`TestUnknownAccessPanicsAtRegistration` |
| An error's status is lost | `TestControllerErrorSetsHTTPStatus` |
| Path parameters do not reach the controller |
`TestNonBodyControllerReceivesPathParametersDirectly` |

</details>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants