Skip to content

feat(typescript): validate request parameters against schema patterns - #212

Open
TristanSpeakEasy wants to merge 6 commits into
mainfrom
feat/typescript-param-pattern-validation
Open

TristanSpeakEasy wants to merge 6 commits into
mainfrom
feat/typescript-param-pattern-validation

Conversation

@TristanSpeakEasy

@TristanSpeakEasy TristanSpeakEasy commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Why

TypeScript SDKs ignore pattern on parameter schemas, so an API author has no way to stop an SDK from sending a path, query or header value the API never accepts. For path parameters this matters beyond input hygiene. A spec that declares pattern: '^[a-z0-9_]+$' on an ID should stop a caller from passing arbitrary input, such as .., ABC or an untrusted value from an end user or a model tool call, before the SDK builds the URL.

The CLI and Terraform targets already enforce pattern. This brings TypeScript in line for request parameters. It complements #211, which rejects . and .. path segments by default whether or not a spec declares a pattern.

What changed

  • Operation parameters (in: path, query and header) of type: string that declare a portable pattern now get a refinement in the operation's request schema. The SDK already parses every request through that schema before building the URL, so a mismatch fails with SDKValidationError ("Input validation failed") and no request is sent:

    storeId: z.string().refine(matchesPattern$("^[a-z0-9_]+$"), {
      message: "Use lowercase letters, digits or underscores.",
    }),
  • Only portable patterns are enforced. The generator reuses the CLI's portable-subset check, now shared as isPortablePattern in common/common/patterns.ts. A pattern qualifies when Go's regexp and ECMA-262 Unicode mode (the JSON Schema dialect) read it the same way. Anything else, such as \p{L}, \A...\z, [[:alnum:]], \s or lookaheads, is left to the server, matching the CLI. The runtime helper matchesPattern in lib/primitives.ts compiles with the u flag and has no fallback mode.

  • Only the operation's own parameters are constrained. Properties of an object parameter (for example a deepObject query parameter) carry a parameter annotation too, and their model can be shared with a request body. Those properties are not refined, so a schema used both as a query parameter and as a body is never validated when sent as a body.

  • A default that violates its own pattern disables the refinement for that parameter. On zod v3 a refinement also runs on the default, so every call omitting the parameter would otherwise fail. The parameter is still sent with its default, as before.

  • Generated examples match the pattern. When a patterned parameter has no explicit example and the usual faked value doesn't match, the TypeScript example is now built from the pattern by a small deterministic generator for the portable subset (exampleForPortablePattern in common/common/patterns.ts): the first alternation branch, three items for unbounded repetition, and characters from a printable pool (for example storeId: "abc" rather than "<id>"). README snippets, docs and generated tests therefore call the SDK with values it accepts. Other targets' examples are unchanged.

  • x-speakeasy-pattern-error-message is used as the error message when present, matching the CLI. Otherwise the message is Value must match pattern <pattern>.

  • Works with zod v3, v4 and v4-mini through the existing z.refine helper. The none (no-zod) runtime has no schemas, so it is unchanged.

Out of scope: request body properties, properties of object parameters, response parsing, and string items of array parameters. Body and response schemas are unchanged, so a spec whose pattern is stricter than real data can't make an existing call fail when its response is parsed.

Review notes

  • This changes behaviour for existing SDKs whose specs declare portable parameter patterns: a value that doesn't match is now rejected client-side instead of sent. That is the intent, and it matches the CLI.
  • oneOf string parameters that the generator collapses into a single string get the merged pattern (for example (^[a-z]+$|^[0-9]+$)).
  • A default that violates its own pattern is a spec error. A validation-time lint rule would be the better place to report it. This PR only keeps such SDKs working.

Testing

  • TARGET=primary make test-typescriptv2 (zod v4-mini): 54 files, 819 tests passing. tests/primary/parameter_patterns_additional.test.ts uses the existing cli-pattern-error-message.yaml fragment to check that path, query and header mismatches are rejected before any request is sent, custom and default messages, valid values being sent, a lookahead pattern being left to the server, and body properties staying unconstrained.
  • TARGET=tertiary make test-typescriptv2 (zod v3): 29 files, 426 tests passing. A new tertiary/parameter-pattern-validation.yaml fragment and tests/tertiary/parameter_patterns_additional.test.ts cover rejection on v3, an omitted patterned parameter sending its default, and a component used as both a deepObject query parameter and the request body being sent unchanged. The generated example for its unexampled path parameter matches the pattern.
  • TARGET=review and TARGET=no-zod for typescriptv2, TARGET=review make test-cli (854 tests, CLI output unchanged by the shared helper move), and make check-template-typescriptv2 pass.
  • Not run: TARGET=quaternary (zod v4), because the local environment has no pnpm version configured.
  • make lint: golangci-lint's gofmt check reports an alignment finding on an unrelated templates/perms.go entry; local gofmt makes no changes to the file.

Public-safety check

  • This change contains no credentials, customer documents, private repository URLs, private filesystem paths, or unredacted private logs.
  • Title, body, comments, and commit messages name no customers or customer-derived identifiers, private paths or trackers, or workflow provenance, and are understandable without private context (.claude/skills/public-repo-communication/SKILL.md).
  • Generated fixtures and review SDK changes are public-safe.
  • I reviewed git diff --check.

Summary by cubic

TypeScript SDKs now validate path, query, and header string parameters against schema pattern declarations before building the request, and generate examples that match those patterns. Previously those values were sent unchecked, so a caller could pass input like .. that the API never accepts; a mismatch now raises SDKValidationError and no request is sent, aligning TypeScript with the CLI and Terraform targets.

  • Enforces only patterns deemed portable, meaning they behave identically in Go's regexp and ECMA-262 Unicode mode; patterns that can't be confirmed portable, such as lookaheads, are left to the server.
  • Uses x-speakeasy-pattern-error-message for the error message when declared, otherwise defaults to Value must match pattern <pattern>.
  • Applies only to string parameters in the operation's own request model in path, query, and header positions; request body properties and object parameter properties shared with the body are unchanged.
  • Rejects values exceeding a declared maxLength before the pattern runs (including for defaults and generated examples), so the regex never sees arbitrarily long input and the default is still sent when it matches.
  • Replaces generated examples that would violate a pattern with a matching one, covering the full portable subset including alternation, character classes, anchors, escapes, and quantifiers.
  • Tests cover Unicode mode, uncompilable patterns, merged oneOf patterns, lookahead syntax, maxLength bounds, and rejection before a request is sent across all parameter positions.

Written for commit 15166b1. Summary will update on new commits.

View guided diff Turn on auto-fix

@TristanSpeakEasy
TristanSpeakEasy requested a review from a team as a code owner November 12, 2026 06:17
@TristanSpeakEasy TristanSpeakEasy added enhancement New feature or request typescript Trigger (168) snapshot tests for typescript labels Nov 12, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 9 files

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

@speakeasy-generator-bot

speakeasy-generator-bot Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Generator Snapshot Testing

Selector(s) Result Summary
snapshot-typescript ❌ Snapshot run failed

Snapshot results: https://github.com/speakeasy-api/openapi-generation-snapshots/issues/166#issuecomment-6910320087

Snapshot results are summarized above. Additional run context is linked for maintainers with access.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would not auto-approve. Auto-approval blocked by 1 unresolved issue from previous reviews.

View guided diff | Turn on auto-fix | Re-trigger cubic

@ThomasRooney ThomasRooney left a comment

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.

Holding: the primary path works, but three reachable cases reject values the API accepts.

(-Thomas + Fable 5.2)

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 14 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would auto-approve. Adds TS SDK validation of path/query/header string params against portable schema patterns (shared CLI helper; defaults/examples handled), tested across zod v3/v4; change is bounded to values the spec already excludes and matches CLI behavior.

View guided diff | Turn on auto-fix | Re-trigger cubic

@TristanSpeakEasy

Copy link
Copy Markdown
Member Author

@ThomasRooney re your non-blocking note on primitives.ts (patterns run unbounded on caller input):

Checking maxLength first, as the CLI does, would bound it.

Fixed in 3824f15. When a patterned parameter also declares maxLength, the schema now gets a withinMaxLength$(n) refinement ahead of the pattern ("Value must be at most n characters long"), and matchesPattern$(pattern, n) skips the regex for any value over the bound, so a backtracking-prone pattern only ever sees input up to maxLength code points. Length counts code points, matching JSON Schema and the CLI. A default that exceeds maxLength disables the refinement, the same as a default that fails the pattern, and pattern-derived examples are kept within maxLength.

Patterns without a maxLength are still unbounded, same as the CLI. Tests cover the helpers (including an ^(a+)+$ case over the bound) and an over-length path parameter in the primary fixture.

This comment didn't show up as a thread through the API, so I couldn't reply inline. Feel free to resolve it on your side.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 8 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

0 issues found across 3 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would auto-approve. Adds TS SDK validation of path/query/header string params against portable schema patterns, sharing the CLI check, with maxLength-bounded matching; bounded to spec-declared constraints, matches CLI behavior, and covered by tests.

View guided diff | Turn on auto-fix | Re-trigger cubic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request typescript Trigger (168) snapshot tests for typescript

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants