Skip to content

fix(config): tighten Zod validation on uiServer.options.port (#1874) - #1901

Merged
jerome-benoit merged 2 commits into
mainfrom
fix/1874-zod-uiserver-port-validation
Jun 15, 2026
Merged

jerome-benoit merged 2 commits into
mainfrom
fix/1874-zod-uiserver-port-validation

Conversation

@jerome-benoit

Copy link
Copy Markdown
Contributor

Summary

The Zod schema introduced in #1874 promised fail-fast configuration
validation at boot, but uiServer.options was bridged with a permissive
z.custom<ListenOptions> that only checks the value is a non-array
object. As a result, primitive-typed fields like port and host were
not validated: a port: "not-a-number" accepts at boot, stations
register and exchange BootNotification, then the process crashes
inside node:net.Server.listen with
RangeError [ERR_SOCKET_BAD_PORT]: options.port should be >= 0 and < 65536.

This change replaces the permissive bridge with a typed object schema
piped after the existing structural refinement. Known primitive fields
are validated at boot; unknown keys are still passed through (.loose())
so the ListenOptions extension surface (e.g. signal: AbortSignal)
remains usable. The existing accessPolicy misplacement refinement is
preserved via .pipe().

Validation surface

Field Constraint
port integer in [0, 65535]
host non-empty string
backlog non-negative integer
path non-empty string (unix socket path)
exclusive boolean
ipv6Only boolean
readableAll boolean
writableAll boolean
other keys passed through (e.g. signal)

Reproduction (mandatory pre/post evidence)

Setup (identical for BEFORE and AFTER):

pnpm build && pnpm --filter cli build
cp dist/assets/config.json /tmp/config-backup.json
jq '.uiServer.options.port = "not-a-number"' /tmp/config-backup.json \
  > dist/assets/config.json

BEFORE (main @ 61026d7) — bug confirmed

Command:

timeout 8 node --enable-source-maps dist/start.js
echo "EXIT=$?"

Stderr (last lines) + exit code:

Startup error:  RangeError [ERR_SOCKET_BAD_PORT]: options.port should be >= 0 and < 65536. Received type string ('not-a-number').
    at Server.listen (node:net:2159:5)
    at Zi.startHttpServer (file:///.../dist/start.js:3:236957)
    at Zi.start (file:///.../dist/start.js:11:2782)
    at r.startUIServer (file:///.../dist/start.js:12:417)
    at file:///.../dist/start.js:12:14641
    ...
  code: 'ERR_SOCKET_BAD_PORT'
EXIT=124

EXIT=124 is the timeout(1) signal: the simulator boots successfully,
the UI server crashes with ERR_SOCKET_BAD_PORT, but the process
keeps running (no fail-fast) until timeout kills it after 8s.

AFTER (this PR) — fail-fast at boot

Command:

timeout 8 node --enable-source-maps dist/start.js > /dev/null 2> stderr.log
echo "node-exit=$?"
cat stderr.log

Stderr + exit code:

6/15/2026, 4:53:47 PM Simulator configuration | ConfigurationValidation: Configuration validation failed [schema] for '/.../dist/assets/config.json':
  - uiServer.options.port: Invalid input: expected number, received string
node-exit=1
  • Exit code 1 (non-zero) — fail-fast.
  • Wall-clock time to error: ~1.6 s (most of which is node + tsx startup).
  • Error path: uiServer.options.port — structured, machine-readable.
  • Routed through ConfigurationValidationError (phase: 'schema') — the
    existing typed error machinery, not a raw Error.

Tests

tests/utils/ConfigurationSchema.test.ts (10 new cases under
uiServer.options.port and uiServer.options.host describes):

Case Expected
port = "not-a-number" reject (path)
port = -1 reject (path)
port = 65536 reject (path)
port = 3.14 reject (path)
port = 8080 accept
port = 0 (OS-picked) accept
port = 65535 (max) accept
host = "" reject (path)
host = "localhost" accept
host = 1234 (non-string) reject (path)

tests/utils/ConfigurationValidation.test.ts (1 new integration case)
asserts the end-to-end pipeline surfaces uiServer.options.port in
ConfigurationValidationError.fieldErrors with phase: 'schema'.

Quality gates

Command Result
pnpm --filter . typecheck exit 0
pnpm --filter . lint exit 0
pnpm format exit 0
pnpm test 2730 pass / 0 fail / 6 skipped
pnpm circular-deps 62 cycles (= baseline)
Reproduction (BEFORE) exit 124, ERR_SOCKET_BAD_PORT
Reproduction (AFTER) exit 1, structured Zod error

Out of scope

  • OCPP wire schema and station templates — not touched.
  • BaseError / OCPPError class hierarchy — not refactored.

Severity

MAJOR — boot-time validation gap.

Replace the permissive z.custom<ListenOptions> bridge under
uiServer.options with a typed object schema validating known primitive
fields, so bad transport-level values (e.g. port: "not-a-number")
fail at boot time in ConfigurationSchema.safeParse instead of later
inside node:net.Server.listen with ERR_SOCKET_BAD_PORT.

The existing accessPolicy refinement is preserved via .pipe(); unknown
keys are still passed through (.loose()) to keep the ListenOptions
extension surface (e.g. signal: AbortSignal) usable.

Validates:
- port: integer in [0, 65535]
- host: non-empty string
- backlog: non-negative integer
- path: non-empty string
- exclusive / ipv6Only / readableAll / writableAll: boolean

Tests: 10 new cases in tests/utils/ConfigurationSchema.test.ts and
1 integration assertion in tests/utils/ConfigurationValidation.test.ts
covering the structured Zod error path uiServer.options.port routed
through ConfigurationValidationError.
@hyperspace-pr-bot

Copy link
Copy Markdown
Contributor

Summary

The following content is AI-generated and provides a summary of the pull request:


fix(config): Tighten Zod Validation on uiServer.options.port

Bug Fix

🐛 Fixes a boot-time validation gap where uiServer.options accepted invalid primitive values (e.g., port: "not-a-number"), allowing the simulator to start successfully but later crash inside node:net.Server.listen with ERR_SOCKET_BAD_PORT. The simulator now fails fast at boot with a structured, machine-readable Zod error instead.

The root cause was the permissive z.custom<ListenOptions>() bridge that only checked the value was a non-array object, without validating individual fields. This PR replaces it with a typed object schema (UIServerListenOptionsObjectSchema) piped after the existing structural refinement.

Changes

  • src/utils/ConfigurationSchema.ts: Adds UIServerListenOptionsObjectSchema — a .loose() Zod object schema that validates known primitive fields (port, host, backlog, path, exclusive, ipv6Only, readableAll, writableAll) with precise constraints, while passing unknown keys through to preserve the ListenOptions extension surface (e.g., signal: AbortSignal). This schema is piped into the existing UIServerListenOptionsSchema after the accessPolicy misplacement refinement.

    Field Constraint
    port integer in [0, 65535]
    host non-empty string
    backlog non-negative integer
    path non-empty string
    exclusive, ipv6Only, readableAll, writableAll boolean
  • tests/utils/ConfigurationSchema.test.ts: Adds 10 new test cases covering rejection of string ports, negative ports, out-of-range ports, non-integer ports, empty host strings, non-string hosts, and acceptance of valid values (port: 8080, port: 0, port: 65535, host: "localhost").

  • tests/utils/ConfigurationValidation.test.ts: Adds 1 integration test asserting the end-to-end validation pipeline surfaces uiServer.options.port in ConfigurationValidationError.fieldErrors with phase: 'schema' and a matching error message.

Jira Issues (ONLY add this section if JIRA issues are available)

Related GitHub PR: #1874


  • 🔄 Regenerate and Update Summary
  • ✏️ Insert as PR Description (deletes this comment)
  • 🗑️ Delete comment
PR Bot Information

Version: 1.23.0

@hyperspace-pr-bot hyperspace-pr-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The pull request is well-structured and correctly solves the described boot-time validation gap. The only notable issue found is a misplaced JSDoc comment — the block named UIServerListenOptionsSchema describing the z.custom bridge now sits above UIServerListenOptionsObjectSchema instead, leaving the composite schema undocumented and the helper schema with an inaccurate comment. The UIServerConfigurationSchema JSDoc also remains partially stale (still says "the schema uses z.custom<ListenOptions>() to bridge the external surface" without mentioning the newly piped typed object stage). Both are documentation-only gaps with no correctness impact, and the implementation, tests, and integration assertion are all sound.

PR Bot Information

Version: 1.23.0

Comment thread src/utils/ConfigurationSchema.ts Resolved
Address review comment on #1901: the JSDoc above
UIServerListenOptionsObjectSchema was named after the composite
UIServerListenOptionsSchema, leaving the helper described under the
wrong name and the composite undocumented. UIServerConfigurationSchema
also still referenced the now-removed permissive z.custom<ListenOptions>
bridge.

- UIServerListenOptionsObjectSchema gets its own JSDoc describing the
  typed object layer (.loose() + primitive constraints).
- UIServerListenOptionsSchema gets a JSDoc describing the full chain:
  object guard → accessPolicy refinement → pipe to typed object.
- UIServerConfigurationSchema JSDoc updated to reference the new
  composite schema instead of the obsolete custom bridge.

No behavior change, no test change.
@jerome-benoit
jerome-benoit merged commit 19afcb2 into main Jun 15, 2026
44 checks passed
jerome-benoit added a commit that referenced this pull request Jun 15, 2026
…1903)

* fix(config): enforce Zod simulator-config validation at boot (#1874)

Audit pass over uiServer.* primitives that PR #1901 left under-constrained.
Each constraint closes a concrete fail-fast gap surfaced by a 3-angle design
review (schema completeness, fail-fast wiring, adversarial risk).

UIServerAuthenticationSchema:
- username: z.string().min(1).optional() — empty username currently passes;
  AbstractUIServer falls back to '' and authenticates against the empty
  configured value, silently bypassing Basic-Auth.
- password: z.string().min(1).optional() — same hole on password.
- username .refine(no ':') (RFC 7617) — lifts the runtime check at
  UIServerFactory.ts:48-54 into the schema layer.
- object-level .refine: enabled === true requires both username and password.
  Closes the silent-bypass when authentication is enabled with no creds.

UIServerAccessPolicySchema:
- object-level .refine: allowLoopbackProxy === true requires
  trustedProxies.length >= 1. With allowLoopbackProxy: true and an empty
  trustedProxies list, the proxy-trust check at runtime always evaluates
  against the empty allowlist, contradicting the operator's intent.

No wiring change: Configuration.ts:160 (boot, process.exit(1)) and
Configuration.ts:386-431 (hot-reload, rollback) already route
ConfigurationValidationError correctly. Schema tightening lands at parse
time without rewiring.

Test fixture update: tests/utils/ConfigurationSchema.test.ts unknown-key
test for uiServer.authentication now includes valid username/password
alongside bogusAuthKey so the unknown-key intent stays unambiguous after
the new object-level superRefine.

9 new test cases (5 reject + 3 accept regression-anchors + 1 cross-field
reject) covering rejection paths and the docker/config.json-shape
acceptance.

Designs that did NOT survive cross-validation are documented as
out-of-scope follow-ups: type×version coupling (coupled to in-place
mutation bug at UIServerFactory.ts:69), type×auth coupling (defense in
depth at runtime is intentional), options.{path,readableAll,writableAll,
ipv6Only} refinements (no shipped config exercises these), and the
TLS-non-loopback wildcard refine (would break docker/config.json:18).

* fix(config): refine auth schema error path and tighten test path checks

Address review feedback on #1903:

src/utils/ConfigurationSchema.ts
- UIServerAuthenticationSchema object-level .refine now carries
  path: ['username'], producing an error path of
  'uiServer.authentication.username' rather than 'uiServer.authentication'.
  Mirrors the path: ['allowLoopbackProxy'] convention already used on
  UIServerAccessPolicySchema and yields a more actionable message.
- JSDoc clarifies that the field-level constraints (min(1), no ':')
  apply unconditionally even when authentication.enabled is false:
  the schema is intentionally stricter than the runtime guard in
  UIServerFactory so a credentials value cannot ship under
  enabled: false and become a bypass the moment enabled flips on
  (e.g. via hot-reload).

tests/utils/ConfigurationSchema.test.ts
- Three .includes('uiServer.authentication') substring checks tightened
  to .startsWith('uiServer.authentication') so they cannot match a
  hypothetical sibling key like 'uiServer.authenticationFoo'. Affects
  the two object-level coupling tests and the unknown-key fixture
  assertion. Exact-element checks at lines 630/651 (specific leaf
  paths) and the leaf-specific .includes at line 671 are left as-is.

No behavior change. 114/114 schema tests pass, typecheck + lint clean.

* docs(config): tighten UIServerAuthenticationSchema JSDoc

Rewrite the JSDoc as a single factual paragraph matching the file
convention (LogConfigurationSchema, WorkerConfigurationSchema,
UIServerListenOptionsObjectSchema, ...) — 12 lines collapsed to 7,
no redundant phrasing, structured as: constraint definitions →
required-when-enabled coupling → unconditional-field-level rationale.
Per AGENTS.md 'Documentation conventions' (concision, structure).

* fix(config): emit per-field error paths on auth-required refine

Address sub-agent review feedback on #1903.

src/utils/ConfigurationSchema.ts
- Replace the .refine() with a fixed path: ['username'] by a
  .superRefine() that emits one issue per actually-missing field with
  the correct path. Configurations supplying only 'username' now
  surface the issue at 'uiServer.authentication.password' rather than
  'uiServer.authentication.username', and vice versa. Configurations
  missing both produce two issues, one per field.

tests/utils/ConfigurationSchema.test.ts
- 'should reject authentication enabled without username and password'
  now asserts both 'uiServer.authentication.username' and
  'uiServer.authentication.password' paths are present, locking the
  per-field issue contract.
- 'should reject authentication enabled with username but no password'
  now asserts 'uiServer.authentication.password' specifically — would
  catch the prior path-misanchoring regression.
- The 'should reject unknown key in uiServer.authentication section'
  regression-anchor now asserts i.code === 'unrecognized_keys' at the
  'uiServer.authentication' path, locking the unknown-key intent so a
  hypothetical future refine cannot satisfy the assertion by accident.

114/114 schema tests pass, typecheck + lint clean. No production-
runtime behavior change beyond per-field error paths.

* fix(ui-common): align authenticationConfigSchema with simulator auth schema

Apply the same defense-in-depth + per-field-error-path pattern shipped
on the simulator-side UIServerAuthenticationSchema in this PR. The Web
UI client schema (consumed by ui/web/src/main.ts and transitively by
ui/cli/src/config/loader.ts) carried the same set of defects:
- password lacked min(1) at the field level
- username regex /^[^:]*$/ accepted the empty string
- a single .refine combined type-check + presence + length, producing
  a generic error at the auth object root with no path
- empty creds shipped under enabled: false would become a Basic-Auth
  bypass the moment enabled is flipped on

ui/common/src/config/schema.ts
- password: z.string().min(1).optional()
- username: z.string().min(1).refine(no ':' RFC 7617).optional()
  (replaces the regex which silently accepted '')
- .refine(...) replaced by .superRefine(...) emitting one issue per
  actually-missing field with the correct path, only when
  enabled === true && type === PROTOCOL_BASIC_AUTH (existing
  type-check short-circuit preserved as future-proofing).
- JSDoc mirrors the simulator-side sibling, documenting the
  intentional stricter-than-runtime semantics.

ui/common/tests/config.test.ts
- 4 new tests: empty password rejected (path 'authentication.password'),
  username with ':' rejected (RFC 7617 message at
  'authentication.username'), password-only and username-only enabled
  configs each rejected at the missing field's path.
- 2 existing tests tightened: 'missing credentials' now asserts both
  username and password paths; 'empty username' now asserts the
  'authentication.username' path.
- 6 redundant 'if (result.success) return' narrowing guards removed —
  assert.strictEqual already narrows the result type.

118/118 ui-common tests pass, typecheck + lint clean. No production
behavior change for the only valid-config consumer ('admin'/'admin'
shape regression-anchored).

* fix(config): point accessPolicy refine error path at the actionable field

Address review feedback on #1903. The .refine() rejecting
'allowLoopbackProxy: true' with empty 'trustedProxies' attached its
issue at path ['allowLoopbackProxy'] — the trigger of the rejection,
but not the field the operator must edit. Move the path to
['trustedProxies'] so structured log scrapers and IDE jump-to-field
tooling steer the operator to the field that needs populating. The
message wording (which already names both fields) is unchanged.

Test 'should reject allowLoopbackProxy=true with empty trustedProxies'
tightened from a permissive substring check
('allowLoopbackProxy or trustedProxies') to an exact-path check on
'uiServer.accessPolicy.trustedProxies' so the path contract is locked.

A second review suggestion (gate the auth credentials-required
superRefine on type === PROTOCOL_BASIC_AUTH) was investigated and
declined: the server-side AuthenticationType enum has BASIC_AUTH AND
PROTOCOL_BASIC_AUTH (unlike the Web UI client's single-member enum),
both runtime paths require username/password
(AbstractUIServer.ts:358-381), and adding the type-gate would re-open
the silent Basic-Auth bypass on the legacy 'basic-auth' path that
this PR is closing on the modern path.

114/114 schema tests pass, typecheck + lint clean.

* docs(config): refine auth-schema JSDoc rationale and tighten RFC 7617 path check

Address sub-agent review feedback on #1903.

src/utils/ConfigurationSchema.ts + ui/common/src/config/schema.ts
- Drop the 'across hot-reload toggles of enabled' phrasing in the
  UIServerAuthenticationSchema and authenticationConfigSchema JSDoc.
  Hot-reload of uiServer.* is documented as a no-op in the PR body
  (R4: Bootstrap.ts:103,161 instantiates the UI server once), so the
  unconditional field-level constraints are an early-detection signal
  rather than a hot-reload mitigation. The accurate rationale is that
  empty placeholders cannot ship under enabled: false and become a
  Basic-Auth bypass on the next boot with enabled: true.
- The asymmetry between the two superRefines (server gates only on
  enabled; Web UI also gates on type === PROTOCOL_BASIC_AUTH) is
  preserved and intentional — server-side AuthenticationType has
  legacy BASIC_AUTH which is also credential-required at runtime
  (AbstractUIServer.ts isBasicAuthEnabled / isValidBasicAuth). The
  rationale is captured in this commit body and the prior
  86a6d4a commit body for git blame discoverability.

tests/utils/ConfigurationSchema.test.ts
- RFC 7617 username-rejection test now matches the issue path with
  i.path.join('.') === 'uiServer.authentication.username' (exact)
  instead of String.prototype.includes (substring), aligning with
  every other test in the file and with the ui-common sibling.

114/114 schema tests + 118/118 ui-common tests pass, typecheck +
lint clean. No behavior change.
@jerome-benoit
jerome-benoit deleted the fix/1874-zod-uiserver-port-validation branch June 15, 2026 19:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant