Repository navigation
Conversation
…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
marked this pull request as ready for review
November 30, 2026 09:33
thesyncim
reviewed
Nov 30, 2026
| 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 -"` |
Member
There was a problem hiding this comment.
shall we prefix validator stuff do we dont pollute tag space? validator_maxLengh:"..."
thesyncim
reviewed
Nov 30, 2026
| // 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 { |
Member
There was a problem hiding this comment.
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
Member
Author
There was a problem hiding this comment.
yes thats what we do Resolve is only for cross fields / more complex validation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
Router HTTP handlers in
acceleration/internal/apimixed struct tags, hand-writtenBody == nilchecks, manualServerSideFromguards,UnmarshalJSONvalidation (SessionQuery), and ad-hocinvalidRequest(...)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 structuredhuma.ErrorDetailerrors before handlers run (AI-4429).How it works
register+serversidetag (internal/api/validate.go)server_side_onlybefore the handler; WebSocket callsrefuseServerSideFieldsTestAFieldOnlyABackendMaySendIsRefusedFromADeviceBody Ton ~70 required-body requestsrequired:"true"tags and nil checksTestAResolverRefusalNamesTheFieldAndIsABadRequest,TestRequestsFollowTheValidationRuleshuma.ResolverWithPathon request typeshuma.ErrorDetaillocationsTestAResolverRefusalNamesTheFieldAndIsABadRequest,TestARefusalThatNeedsItsOwnCodeIsAnsweredAsItIsSessionQuery.Resolve+additionalProperties: falseUnmarshalJSONvalidation andSkipValidateBodyTestAQueryIsRefusedForAKeyOrALimitItDoesNotTakeSkipValidateBody, non-nullableserversidefields, blank reasons, orBody *Twithrequired:"true"TestRequestsFollowTheValidationRulesChanges
acceleration/internal/api/validate.go(register, reflectiveserversidetag walker with sorted map keys,refuseServerSideFields,validationRefusal,invalid,problems,blankProblem) and switched every operation registration fromhuma.Registertoregister.*Tto valueT, droppingrequired:"true"tags and hand-written nil checks. Nine DLC, channel, and suspension operations gainedrequired: trueinacceleration/api/openapi.yaml; regenerated all SDKs (plugins/stream,sdks/js,sdks/ruby,sdks/rustupdated; Go, Kotlin, .NET, PHP, Dart, Swift unchanged).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 sharedbodypath prefix.Resolvemethods 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.SessionQuery.UnmarshalJSONvalidation andSkipValidateBody.AGENTS.md("HTTP API") and.claude/skills/go/SKILL.md.limits.go,routerconfigs.go, and config store-lookup complaints) remain in handlers for follow-up passes.Validation
go vet -tags=integration ./internal/api/inacceleration/— passed (all unit and integration test files compile cleanly).go test -count=1 ./...inacceleration/— passed across all Go packages (earlier single flake ininternal/sts/openairealtimeTestRealtimeSuitepassed 3/3 on rerun).go run ./cmd/openapiand all SDK generators (go,plugins/stream,kotlin,js,dotnet,php,rust,ruby,dart) — clean and committed.//go:build integration) — not run locally (handled by CI); assertion updates verified bygo vet -tags=integrationand static audit against every changed code/message.