Skip to content

feat(ui-server): add source-aware gateway access policy - #1891

Merged
jerome-benoit merged 37 commits into
mainfrom
feat/ui-gateway-access-policy
Jun 14, 2026
Merged

jerome-benoit merged 37 commits into
mainfrom
feat/ui-gateway-access-policy

Conversation

@jerome-benoit

@jerome-benoit jerome-benoit commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Source-aware gateway access policy for the UI server. A common prologue runs before HTTP, MCP, and WebSocket request handling and evaluates the request against uiServer.accessPolicy once per request.

Configuration

uiServer.accessPolicy (all fields optional):

Field Type Default Description
requireTlsForNonLoopback boolean true Reject non-loopback plaintext requests.
trustedProxies string[] [] IPv4/IPv6 literals of immediate reverse proxies whose forwarded headers are honored. Hostnames and CIDR ranges are rejected at config load.
allowLoopbackProxy boolean false Honor forwarded headers when the immediate peer is loopback AND listed in trustedProxies (e.g. ['127.0.0.1', '::1']).
allowedHosts string[] [] Host header allowlist. When the listen host is loopback, all loopback aliases (localhost, 127.0.0.1, ::1) are added implicitly; when it is a single non-loopback address, the address itself is added. Wildcard listen hosts ('', 0.0.0.0, ::) add nothing implicit and require an explicit list. Entries are validated as host literals (no path, query, or fragment).
allowedOrigins string[] [] Origin header allowlist as origin URLs (no path/query/fragment). Empty falls back to matching the request Origin's hostname against allowedHosts.

accessPolicy is rejected at config load when nested under uiServer.options.

Behavior

  • Loopback request sources are allowed in plaintext.
  • Non-loopback sources require TLS termination upstream by a reverse proxy listed in trustedProxies that forwards X-Forwarded-Proto: https (or RFC 7239 Forwarded: proto=https).
  • Forwarded headers are honored only from trustedProxies; only single-hop chains are accepted. Multi-entry Forwarded and multi-value X-Forwarded-* are rejected.
  • Forwarded and the matching X-Forwarded-* header for the same dimension cannot both be present.
  • Empty forwarded values are treated as absent.
  • RFC 7239 hidden-identity forms in for= (unknown, obfuscated identifiers _<token>) resolve to the trusted proxy's remote address.
  • Decisions are memoized per request via a WeakMap.
  • Denied requests are accounted against the rate limiter.
  • HTTP/1.1 requestTimeout (30 s) and headersTimeout (5 s) bound slow-loris exposure. HTTP/2 streams self-protect.
  • Denial responses carry Connection: close on HTTP/1.1; HTTP/2 omits the header (RFC 7540 forbids it).

Denial reasons

tls-required, proxy-tls-required, host-not-allowed, origin-not-allowed, forwarded-from-untrusted-peer, loopback-proxy-disabled, duplicate-gateway-headers, ambiguous-forwarded-{header,client,host,protocol,parameter}, invalid-forwarded-client.

Defaults that change observable behavior

  • requireTlsForNonLoopback: true — plaintext non-loopback configurations are rejected unless TLS is terminated upstream by a proxy listed in trustedProxies forwarding X-Forwarded-Proto: https, or the field is set to false (only safe on private/loopback bindings).
  • Wildcard listen host ('', 0.0.0.0, ::) requires an explicit allowedHosts. The bundled docker/config.json sets "allowedHosts": ["localhost", "127.0.0.1", "::1"].
  • trustedProxies accepts only IP literals.
  • uiServer.options rejects an embedded accessPolicy key.
  • MCP transport-level error responses (404 Not Found, 400 Bad Request, 405 Method Not Allowed, 500 Internal Server Error) now carry a ${status} ${reasonPhrase} plaintext body and a Content-Type: text/plain header, matching the HTTP transport. Previously these responses were emitted with no body or Content-Type.

Validation

pnpm typecheck, pnpm lint, pnpm format, pnpm build, pnpm test — 0 fail, 6 skipped.

@hyperspace-pr-bot

Copy link
Copy Markdown
Contributor

Summary

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


Add Source-Aware Gateway Access Policy to UI Server

New Feature

✨ Introduces a uiServer.accessPolicy configuration section that enforces source-aware access control for the UI server across all transports (HTTP, MCP, and WebSocket). The policy enforces TLS requirements for non-loopback connections, validates trusted proxies and forwarded headers, and constrains browser-facing access via allowedHosts and allowedOrigins.

Changes

  • README.md: Updated uiServer configuration table to document the new accessPolicy field and its sub-options. Added security guidance for Docker deployments and reverse-proxy scenarios.
  • docker/config.json: Added accessPolicy block with loopback-only allowed hosts and requireTlsForNonLoopback: false for the local plaintext Docker path.
  • docker/docker-compose.yml: Constrained the UI server port binding to host loopback (127.0.0.1:8080:8080) instead of all interfaces.
  • src/assets/config-template.json: Added accessPolicy defaults with requireTlsForNonLoopback: true and empty proxy/host/origin lists.
  • src/charging-station/ui-server/AbstractUIServer.ts: Added authorizeAccess() and getRateLimitClientIp() base methods that delegate to the new evaluateUIServerAccess and getUIServerAccessClientAddress utilities.
  • src/charging-station/ui-server/UIHttpServer.ts: Enforces access gate before routing and uses the resolved client IP for rate limiting.
  • src/charging-station/ui-server/UIMCPServer.ts: Enforces access gate before route parsing; uses resolved client IP for rate limiting.
  • src/charging-station/ui-server/UIWebSocketServer.ts: Enforces access gate and rate limiting on WebSocket upgrade before handing off to the WS library.
  • src/charging-station/ui-server/UIServerUtils.ts: Core implementation — adds evaluateUIServerAccess, getUIServerAccessClientAddress, and a full suite of helpers for loopback detection, forwarded-header parsing, IP normalization, host/origin validation, and duplicate header detection.
  • src/utils/Configuration.ts: Adds accessPolicy defaults to defaultUIServerConfiguration; uses clone() to prevent shared mutable state.
  • src/utils/ConfigurationSchema.ts: Adds UIServerAccessPolicySchema (Zod) and a custom UIServerListenOptionsSchema that rejects misplaced accessPolicy keys under options.
  • src/utils/index.ts: Exports the new UIServerAccessPolicySchema.
  • tests/charging-station/ui-server/UIHttpServer.test.ts: New test verifying non-loopback plaintext requests are rejected with 403.
  • tests/charging-station/ui-server/UIMCPServer.test.ts: New access gate tests for malformed host headers and invalid ports.
  • tests/charging-station/ui-server/UIWebSocketServer.test.ts: New test verifying that non-loopback plaintext WebSocket upgrades are rejected with 403 before WebSocket handling.
  • tests/charging-station/ui-server/UIServerTestUtils.ts: Extended mock utilities — added destroy to MockServerResponse, emitUpgrade and waitUntilListening to TestableUIWebSocketServer, and accessPolicy defaults to createMockUIServerConfiguration.
  • tests/charging-station/ui-server/UIServerUtils.test.ts: Comprehensive test suite for evaluateUIServerAccess covering loopback, TLS, trusted proxies, forwarded headers, duplicate headers, host/origin validation, and IPv4-mapped addresses.
  • tests/utils/Configuration.test.ts: Asserts accessPolicy defaults are present in the built configuration section.
  • tests/utils/ConfigurationSchema.test.ts: Schema-level tests for valid policy, unknown keys, and misplaced accessPolicy under options.
  • tests/utils/ConfigurationValidation.test.ts: End-to-end validation test for docker/config.json including accessPolicy fields and the loopback port binding in docker-compose.yml.

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

Version: 1.22.5

  • Event Trigger: pull_request.opened
  • Summary Prompt: Default Prompt
  • LLM: anthropic--claude-4.6-sonnet
  • Output Template: Default Template
  • Correlation ID: 4f66fcb2-a795-435d-862d-7d2e28af2a5c
  • File Content Strategy: Full file content

@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 PR introduces a well-structured source-aware gateway access policy with good test coverage. However, there are a few substantive issues: a correctness bug in isSameHost where the || condition causes mixed hostname/IP comparisons to silently fail (should be &&); a performance/double-evaluation issue where getRateLimitClientIp redundantly re-runs the full policy evaluation after authorizeAccess already computed it; a subtle logic issue with res.destroy() being called immediately after res.end() in the HTTP server's forbidden path; and a performance issue in hasDuplicateHeaders where the raw header scan is repeated per header name instead of being pre-computed once.

PR Bot Information

Version: 1.22.5

req: IncomingMessage,
uiServerConfiguration: UIServerConfiguration
): string => {
return evaluateUIServerAccess(req, uiServerConfiguration).clientAddress || 'unknown'

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.

Logic Error: getRateLimitClientIp re-evaluates the full access policy on every request

getUIServerAccessClientAddress calls evaluateUIServerAccess internally, which means the entire policy evaluation runs twice per request — once in authorizeAccess and once in getRateLimitClientIp. Beyond the redundant work, if the result could ever differ between the two calls (e.g., mutable state), the client IP used for rate-limiting may not correspond to the decision already made.

Consider extracting the UIServerAccessDecision from the first evaluation and reusing decision.clientAddress directly in the callers, or caching the result on the request object.


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

if (forwardedHeadersPresent && !remoteAddressIsTrustedProxy) {
return deny(clientAddress, 'Forwarded headers are only accepted from trusted proxies')
}
if (forwardedHeadersPresent && remoteAddressIsLoopback && !allowLoopbackProxy) {

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.

Logic Error: Mixed condition — proxy check uses remoteAddressIsTrustedProxy but loopback guard uses remoteAddressIsLoopback

At line 156 the condition forwardedHeadersPresent && remoteAddressIsLoopback && !allowLoopbackProxy fires only when the remote address is a loopback address. But a loopback address is not necessarily in trustedProxies, so line 153 (!remoteAddressIsTrustedProxy) would have already denied the request before line 156 is ever reached — unless the operator explicitly adds 127.0.0.1 to trustedProxies. In that case the allowLoopbackProxy flag is redundant with the trustedProxies list. If the intent is to allow loopback peers to forward without being in trustedProxies, the guard at line 153 must also be bypassed for loopback addresses, which is not the case. Consider documenting this interaction explicitly, or restructuring so allowLoopbackProxy auto-adds loopback to trusted proxies.


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

}
const leftAddress = normalizeIPAddress(leftHost)
const rightAddress = normalizeIPAddress(rightHost)
if (leftAddress != null || rightAddress != null) {

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.

Logic Error: isSameHost returns false when exactly one side is an IP address

At line 383 the condition if (leftAddress != null || rightAddress != null) enters the IP comparison branch when either side resolved to an IP. If one side is a hostname (e.g. gateway.example.com) and the other is an IP literal, leftAddress and rightAddress will have different nullability, so leftAddress?.family === rightAddress?.family and leftAddress?.value === rightAddress?.value both evaluate to false even though they could legitimately match (or legitimately not match — but the comparison is skipped entirely for the hostname side). In particular, comparing a loopback alias like localhost (which normalizeIPAddress maps to 127.0.0.1) against the raw string localhost in allowedHosts would enter this branch and fail because normalizeIPAddress('localhost') returns { family: 'ipv4', value: '127.0.0.1' } while normalizeIPAddress of the right side also does the same — so that specific case is fine — but mixing an unresolvable hostname with an IP would silently return false rather than falling through to string comparison. The condition should be leftAddress != null && rightAddress != null to only do IP comparison when both sides resolved.

Suggested change
if (leftAddress != null || rightAddress != null) {
if (leftAddress != null && rightAddress != null) {

Double-check suggestion before committing. Edit this comment for amendments.


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

Comment on lines +108 to +116
const accessError = this.authorizeAccess(req)
if (accessError != null) {
res
.writeHead(StatusCodes.FORBIDDEN, {
'Content-Type': 'text/plain',
})
.end(`${StatusCodes.FORBIDDEN.toString()} Forbidden`)
res.destroy()
req.destroy()

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.

Bug: res.destroy() is called after res.end(), which can corrupt in-flight response data

Calling res.destroy() immediately after res.end(...) forcibly aborts the TCP connection before the HTTP response has been flushed to the client. This can result in the client receiving a truncated or no response at all. The destroy() call is unnecessary here — res.end() already signals the end of the response; Node.js will close the connection naturally. The same pattern exists for the rate-limiting and auth error paths in this file.

Consider removing the res.destroy() and req.destroy() calls after res.end() for the access-denied path, as was already the established pattern in the rate-limit and auth error paths higher in the file.

Suggested change
const accessError = this.authorizeAccess(req)
if (accessError != null) {
res
.writeHead(StatusCodes.FORBIDDEN, {
'Content-Type': 'text/plain',
})
.end(`${StatusCodes.FORBIDDEN.toString()} Forbidden`)
res.destroy()
req.destroy()
const accessError = this.authorizeAccess(req)
if (accessError != null) {
res
.writeHead(StatusCodes.FORBIDDEN, {
'Content-Type': 'text/plain',
})
.end(`${StatusCodes.FORBIDDEN.toString()} Forbidden`)
return
}

Double-check suggestion before committing. Edit this comment for amendments.


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

Comment on lines +283 to +302
const hasDuplicateHeaders = (req: IncomingMessage, headerNames: string[]): boolean => {
const distinctHeaders = Reflect.get(req, 'headersDistinct') as
| IncomingMessage['headersDistinct']
| undefined
for (const headerName of headerNames) {
if ((distinctHeaders?.[headerName]?.length ?? 0) > 1) {
return true
}
let rawHeaderCount = 0
const rawHeaders = (Reflect.get(req, 'rawHeaders') as string[] | undefined) ?? []
for (let index = 0; index < rawHeaders.length; index += 2) {
if (rawHeaders[index]?.toLowerCase() === headerName) {
++rawHeaderCount
}
}
if (rawHeaderCount > 1) {
return true
}
}
return false

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.

Logic Error: hasDuplicateHeaders contains a redundant raw-header scan that can produce false positives

The function first checks headersDistinct (Node.js ≥ 18.3 parsed headers with deduplication info), then also iterates over rawHeaders for every header name. When headersDistinct is present and already signals a duplicate, the raw scan adds no value. Worse, when headersDistinct is not present (older Node.js or mocked requests) the raw scan is the only check — which is correct. But for a header that appears once, both checks run unnecessarily, making the complexity O(headerNames × rawHeaders) instead of O(headerNames). More critically, the rawHeaders scan is nested inside the outer for loop over header names, so the entire raw scan is repeated for every header name regardless of whether headersDistinct already gave the answer. This means a request with many headers is scanned N times where N is the length of headerNames. Consider breaking early when headersDistinct conclusively answers, or restructuring the scan outside the per-name loop.

Suggested change
const hasDuplicateHeaders = (req: IncomingMessage, headerNames: string[]): boolean => {
const distinctHeaders = Reflect.get(req, 'headersDistinct') as
| IncomingMessage['headersDistinct']
| undefined
for (const headerName of headerNames) {
if ((distinctHeaders?.[headerName]?.length ?? 0) > 1) {
return true
}
let rawHeaderCount = 0
const rawHeaders = (Reflect.get(req, 'rawHeaders') as string[] | undefined) ?? []
for (let index = 0; index < rawHeaders.length; index += 2) {
if (rawHeaders[index]?.toLowerCase() === headerName) {
++rawHeaderCount
}
}
if (rawHeaderCount > 1) {
return true
}
}
return false
const hasDuplicateHeaders = (req: IncomingMessage, headerNames: string[]): boolean => {
const distinctHeaders = Reflect.get(req, 'headersDistinct') as
| IncomingMessage['headersDistinct']
| undefined
const rawHeaders = (Reflect.get(req, 'rawHeaders') as string[] | undefined) ?? []
// Build a raw count map once instead of re-scanning for every header name
const rawHeaderCounts = new Map<string, number>()
for (let index = 0; index < rawHeaders.length; index += 2) {
const name = rawHeaders[index]?.toLowerCase()
if (name != null) {
rawHeaderCounts.set(name, (rawHeaderCounts.get(name) ?? 0) + 1)
}
}
for (const headerName of headerNames) {
if ((distinctHeaders?.[headerName]?.length ?? 0) > 1) {
return true
}
if ((rawHeaderCounts.get(headerName) ?? 0) > 1) {
return true
}
}
return false
}

Double-check suggestion before committing. Edit this comment for amendments.


Please provide feedback on the review comment by checking the appropriate box:

  • 🌟 Awesome comment, a human might have missed that.
  • ✅ Helpful comment
  • 🤷 Neutral
  • ❌ This comment is not helpful

autofix-ci Bot and others added 18 commits June 11, 2026 22:25
- Replace stringly-typed denial reason with UIServerAccessDenialReason enum and
  DENIAL_MESSAGES rendering map; UIServerAccessDecision is a discriminated union
  narrowed by 'allowed'.
- Memoize the per-request access decision via WeakMap so the policy is evaluated
  once per request.
- Add runRequestPrologue template method on AbstractUIServer; rate-limit now
  accounts denied requests, closing pre-auth flood amplification.
- Validate accessPolicy.trustedProxies entries as IPv4/IPv6 literals at the
  schema layer; precompile the normalized set per UIServerConfiguration.
- Drop the dead httpServer.on('connect') listener in UIWebSocketServer; use
  StatusCodes consistently in UIMCPServer.
- README clarifies the binary loopback-vs-non-loopback model, single-hop XFF,
  TLS termination via reverse proxy only, and adds a migration note for the
  default requireTlsForNonLoopback: true.
- Split UIServerUtils.ts into UIServerAccessPolicy (decision, forwarded
  parsing, host/origin allowlists) and UIServerNet (IP/host normalization,
  loopback, header tokenization). UIServerUtils retains auth tokens and WS
  subprotocol negotiation only.
- Make evaluateUIServerAccess private; tests and runtime callers go through
  resolveUIServerAccess so the decision cache is always exercised.
- Move accessDecisionCache and trustedProxiesCache from module scope to a
  per-AbstractUIServer instance cache injected into resolveUIServerAccess.
- Quote-aware splitHeaderList honors RFC 7239 / RFC 7230 double-quoted
  values; commas inside "…" are preserved.
- Replace the {error?, value?} dialects in forwarded-header parsers with a
  discriminated ParseOutcome<T>; close the Forwarded params type to
  by/for/host/proto.
- Drop the unreachable isDirectTLSRequest helper and its TLSSocket import.
- Set HTTP server requestTimeout=30s and headersTimeout=5s on
  AbstractUIServer to bound slow-loris exposure on rejected upgrades.
- Ensure UIMCPServer.handleMcpRequest releases the transport and the MCP
  server in every error branch (idempotent cleanup).
- Promote MockUpgradeSocket to UIServerTestUtils.ts; replace the duplicate
  test factory createAccessPolicyConfiguration with the canonical
  createMockUIServerConfiguration.
- Cover the Docker dual-stack case where an IPv4-mapped IPv6 remote address
  matches an IPv4 trustedProxies entry.
- README accessPolicy cell switches to per-field sub-bullets, aligned with
  the log and worker rows.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
@file JSDoc is the test-suite convention (TEST_STYLE_GUIDE.md) and is
absent from the rest of src/. Align the new UIServerAccessPolicy and
UIServerNet modules with the existing source-tree style.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
- Drop README migration note and the duplicate access policy paragraph;
  the configuration table cell already specifies the policy.
- Tighten the Docker section access policy paragraph.
- Trim narrative meta-commentary in UIServerAccessPolicy and UIServerNet
  JSDoc; let constant and type names carry the rest.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
- isHostAllowed: when the immediate peer is a trusted proxy and
  X-Forwarded-Host is present, match it (not the immediate Host) against
  allowedHosts, so reverse proxies that rewrite Host to an internal
  upstream name are not rejected.
- isOriginAllowed: compare allowedOrigins via parsed URL protocol+host
  rather than literal string equality, so entries with a trailing slash or
  with a protocol-default port match the canonical browser-emitted Origin.
- UIMCPServer: destroy the response and request sockets after a denied
  prologue, mirroring UIHttpServer.
- evaluateUIServerAccess: parse the Forwarded header once and pass the
  outcome to getForwardedProtocol and getForwardedClientAddress.
- hasDuplicateHeaders: count rawHeaders in a single pass.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
The WebSocket upgrade denial path wrote only the HTTP/1.1 status line, so
rate-limit denials reached clients without the Retry-After header that
the HTTP and MCP transports already emit.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
- UIMCPServer: destroy the response and request sockets after a denied
  authentication, mirroring UIHttpServer.
- UIWebSocketServer: include the WWW-Authenticate header on auth-denied
  upgrades so RFC 7235 clients receive the Basic challenge that the HTTP
  and MCP transports already emit.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…igins

- AbstractUIServer: also call setTimeout() on the http server so the
  HTTP/2 transport (Http2Server lacks requestTimeout/headersTimeout) gets
  the same idle bound.
- UIHttpServer / UIMCPServer: emit Connection: close on prologue and auth
  denials and drop the explicit res.destroy()/req.destroy() calls; the
  body now flushes before the connection closes.
- UIWebSocketServer: destroy the upgrade socket from the write callback
  so the response bytes are flushed before teardown.
- UIServerAccessPolicySchema: refine allowedOrigins entries to reject
  paths, query strings, and fragments at config load instead of silently
  ignoring them at runtime.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
… rejection

- UIServerAccessPolicy: parse the Forwarded host parameter symmetrically
  with for and proto. Both Forwarded host=... and X-Forwarded-Host now
  feed isHostAllowed when the immediate peer is trusted, with a new
  AmbiguousForwardedHost denial reason when they conflict.
- UIWebSocketServer: build upgrade rejection responses through a single
  helper that always emits Connection: close and Content-Length: 0,
  matching the HTTP and MCP transports.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
Replace the fixed 50 ms waitForStreamFlush delay with await once(res,
'finish') in the UIHttpServer gzip tests. MockServerResponse already
emits 'finish' from end(), so the wait is now event-driven and stops
flaking on slow CI runners (notably Windows / Node 24.x).

Drop the now-unused waitForStreamFlush helper and GZIP_STREAM_FLUSH_DELAY_MS
constant.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…ed parser

- AbstractUIServer: drop the connection-wide setTimeout call. requestTimeout
  and headersTimeout already cover slow-loris on HTTP/1.1, and HTTP/2 streams
  are per-request and not vulnerable to the same pattern. The dropped 30 s
  socket-inactivity cap was killing legitimate long-running responses on
  the deprecated HTTP transport.
- UIServerAccessPolicy: split Forwarded pairs with quote awareness so that
  RFC 7239 quoted-string values containing semicolons are not truncated.
  Mirrors the quote handling already in splitHeaderList.
- UIWebSocketServer: place Connection: close after the extraHeaders spread
  in buildUpgradeRejectionResponse to match the HTTP and MCP transports
  and keep the close header non-overridable by callers.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…ed-peer denial reason

- AbstractUIServer: add getConnectionCloseHeader() returning an empty
  header set when the underlying server is HTTP/2. HTTP/2 forbids the
  Connection header as a connection-specific header; Node otherwise emits
  an UnsupportedWarning and silently drops the value. Streams are closed
  by res.end() on that path. HTTP/1.1 keeps the explicit Connection: close
  to terminate keep-alive on denial.
- UIHttpServer, UIMCPServer: route prologue-denial and auth-denial
  responses through the helper instead of hardcoding Connection: close.
- UIServerAccessPolicy: hoist the trusted-peer check above the protocol
  and host ambiguity checks. An untrusted peer sending forwarded headers
  is now denied as ForwardedFromUntrustedPeer regardless of duplicate
  proto/host metadata, so operator logs reflect the trust violation
  rather than a parser-level symptom. Duplicate-headers retains absolute
  priority. Tests added for the protocol- and host-ambiguity paths from
  an untrusted peer.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
Empty forwarded-header values were treated as present-with-empty-string,
which caused two misbehaviors when the immediate peer was a trusted proxy:

- An empty 'host=' parameter inside a Forwarded header (or an empty
  X-Forwarded-Host) shadowed the real Host header. The policy resolved
  the host to '' and denied the request as HostNotAllowed even though
  the actual Host was in allowedHosts.
- An empty X-Forwarded-Proto was rejected as AmbiguousForwardedProtocol
  (via splitHeaderList returning an empty array) instead of being
  treated as missing.

A nonEmpty() helper now normalizes empty/undefined header values to
undefined at parse time. parseSingleForwardedHeader skips empty
parameter values rather than recording them. The two getters fall
through to the next source when the upstream value is empty.

Tests cover the host fallback paths (Forwarded host= and
X-Forwarded-Host) and the protocol absent-vs-ambiguous distinction.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…warded parser

- UIServerAccessPolicy: recognize the RFC 7239 nodename forms 'unknown'
  and obfuscated identifiers ('_' followed by token characters) in the
  Forwarded 'for=' parameter and X-Forwarded-For header. Hidden-identity
  forms now resolve to ABSENT, so the access decision falls back to the
  trusted proxy's own remote address as the client identifier (used as
  the rate-limit bucket and the logged identity). Previously these
  values were rejected as InvalidForwardedClient even though the rest
  of the request (TLS, host, origin, trust) was valid.
- UIServerAccessPolicy: strip Forwarded parameter quotes only when the
  pair is balanced. The previous '/^"|"$/g' replace stripped the
  leading or trailing quote independently and silently accepted
  unbalanced inputs such as 'for="203.0.113.10'. The new
  '/^"(.*)"$/' anchors both ends in a single match.
- README: clarify that allowLoopbackProxy requires the loopback peer
  to also be listed in trustedProxies. allowLoopbackProxy alone has
  no effect because the trusted-peer check denies forwarded headers
  from peers absent from the trustedProxies list.
- Tests: positive path for allowLoopbackProxy=true; identity-hidden
  paths for Forwarded for=unknown, Forwarded for=_obfuscated, and
  X-Forwarded-For: unknown.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…th continuation pattern

- UIServerAccessPolicy: normalize an empty X-Forwarded-For header to
  undefined so the access decision falls back to the trusted proxy's own
  remote address rather than denying the request as InvalidForwardedClient
  or as AmbiguousForwardedClient when a Forwarded for= parameter is also
  present. Restores symmetry with X-Forwarded-Host and X-Forwarded-Proto
  empty-value handling.
- UIMCPServer: rewrite the auth path as a callback continuation. The
  previous capture-then-check pattern relied on authenticate() being
  synchronous and on the last next() call winning. The new shape
  matches UIHttpServer and UIWebSocketServer and continues to handle
  MCP requests only after a successful authentication callback.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…eaders as absent

- UIMCPServer: emit Connection: close on the 404 not-found and on the
  centralized sendErrorResponse helper (BAD_REQUEST, METHOD_NOT_ALLOWED,
  INTERNAL_SERVER_ERROR), aligning these paths with the post-prologue
  and auth denial responses. The connection-close header is omitted on
  HTTP/2 by the existing getConnectionCloseHeader() helper.
- UIServerAccessPolicy: hasForwardedHeaders now ignores empty header
  values, restoring symmetry with the downstream forwarded-header
  parsers that already map empty values to absent. Empty X-Forwarded-*
  headers from an untrusted peer no longer trigger
  ForwardedFromUntrustedPeer; an empty X-Forwarded-Proto from a
  non-loopback untrusted peer now denies as TlsRequired (no proxy
  proof of TLS). Empty headers from a loopback peer no longer block
  the request.
- README: clarify that requireTlsForNonLoopback honors X-Forwarded-Proto
  / Forwarded: proto= from a trusted proxy and does not detect native
  direct TLS; note that a compromised trustedProxies entry can bypass
  per-client rate limiting by varying X-Forwarded-For.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
- Drop module-level JSDoc on UIServerAccessPolicy and UIServerNet to
  match the codebase convention (no module-level JSDoc on peer files).
- Drop redundant inline comments whose content is already documented in
  the README or self-evident from the surrounding code: the empty
  X-Forwarded-For malformed branch, the allowedOrigins fallback, and
  the loopback-aliases derivation.
- Trim the verbose 'Discriminated by ...' prose on the UIServerAccessDecision
  and ParseOutcome types and remove the JSDoc on resolveUIServerAccess
  (function name and signature are self-explanatory; memoization is
  visible from the cache lookup).

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
- UIServerNet: factor the quote-aware splitter into splitQuoted(value,
  delimiter); splitHeaderList becomes a thin wrapper. The previously
  duplicated state machine in UIServerAccessPolicy (splitForwardedPairs)
  is replaced by a direct splitQuoted call on ';'.
- UIServerAccessPolicy: factor the X-Forwarded-* / Forwarded ambiguity
  pick into pickForwardedValue. The three getForwarded* helpers now
  share a single source of truth for the present/absent/ambiguous
  decision; transport-specific tail logic (multi-hop X-Forwarded-For
  rejection, X-Forwarded-Proto multi-value rejection, lowercasing)
  stays local.
- UIServerAccessPolicy: drop the unreachable string-trim fallback in
  normalizeIPAddress (every input that fails normalizeHost also fails
  the downstream IP checks), narrow isSecureForwardedProtocol's
  parameter to string | undefined (no caller passes null), and skip
  the redundant pre-pass through normalizeHost in isSameHost (the
  IP-address branch already calls normalizeHost internally).
- UIServerAccessPolicy: replace Reflect.get with direct property
  access on IncomingMessage.headersDistinct and rawHeaders (typed
  members on Node 18+).
- Tests: extend the createMockIncomingMessage and the policy test's
  createAccessPolicyRequest factories with headersDistinct and
  rawHeaders defaults so direct property access works against the
  mocks.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…o boolean

- AbstractUIServer: introduce renderDenial(res, payload) and
  getUnauthorizedDenial() so HTTP and MCP route every prologue, 401,
  and post-handler error response through the same code path. The
  helper centralizes Content-Type, Connection-close (HTTP/2-aware),
  and 'res.headersSent' guarding.
- AbstractUIServer: change authenticate(req) to return a boolean
  instead of invoking a continuation with an Error. The CPS shape was
  fully synchronous in practice — every caller did
  'if (err != null)' — and the BaseError allocation was dead. The
  three transports collapse to 'if (!this.authenticate(req)) { … }'.
- AbstractUIServer + UIServerUtils: replace hand-typed reason phrases
  with getReasonPhrase() from http-status-codes; the helper functions
  isValidBasicAuth / isValidProtocolBasicAuth and
  getUsernameAndPasswordFromAuthorizationToken drop their continuation
  parameter accordingly.
- UIServerSecurity: replace the chunk-counter createBodySizeLimiter()
  with a shared readLimitedBody(req, maxBytes): Promise<Buffer> helper
  and a typed PayloadTooLargeError. UIHttpServer reads the request
  body via the helper instead of an event-based loop, and UIMCPServer
  detects oversized payloads via 'instanceof PayloadTooLargeError'
  rather than string-matching the error message.
- UIMCPServer: route sendErrorResponse through renderDenial so all
  4xx/5xx error responses share the same headers and Connection
  semantics; preserve the path-filter-before-authenticate ordering
  with a comment so unknown paths return 404 without revealing
  whether authentication would have succeeded.
- UIWebSocketServer: use getUnauthorizedDenial() for the upgrade
  rejection on auth failure instead of inlining the WWW-Authenticate
  string and the 'Unauthorized' literal.
- Tests: align UIServerUtils.test, UIServerSecurity.test, and
  UIMCPServer.test with the new APIs (boolean signatures, new
  PayloadTooLargeError, new readLimitedBody).

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…llowedHosts entries

- ConfigurationSchema: introduce UI_SERVER_ACCESS_POLICY_DEFAULTS as the
  single source of truth for the access-policy field defaults
  (requireTlsForNonLoopback=true, allowLoopbackProxy=false, and the
  empty allowlists). The defaults previously lived inline in
  evaluateUIServerAccess.
- UIServerAccessPolicy: consume UI_SERVER_ACCESS_POLICY_DEFAULTS instead
  of the hardcoded literals so a default change propagates uniformly
  across the policy code, the schema, and the README.
- ConfigurationSchema: validate allowedHosts entries via normalizeHost
  so paths, queries, fragments, and other malformed Host values are
  rejected at config load. The previous z.string().min(1) accepted
  any non-empty string.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…ants

- UIServerTestUtils: introduce TRUSTED_PROXY_IP, EXTERNAL_CLIENT_IP, and
  GATEWAY_HOST constants from RFC 5737 / RFC 3849 reserved ranges;
  factor the recurrent gateway access-policy configurations into
  createGatewayConfigWithTrustedProxy() and
  createGatewayConfigWithoutTrustedProxies() so subsequent test
  additions inherit a single source of truth for the gateway shape.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…ions

- UIServerAccessPolicy.test: cover the previously untested denial
  reasons AmbiguousForwardedProtocol (multi-value X-Forwarded-Proto),
  AmbiguousForwardedHeader (multi-entry Forwarded), and
  AmbiguousForwardedParameter (duplicate parameter inside one entry);
  cover the InvalidForwardedClient branch for non-IP, non-hidden 'for='
  values; cover AmbiguousForwardedClient when 'Forwarded: for=unknown'
  collides with X-Forwarded-For; cover the headersDistinct path of
  hasDuplicateHeaders.
- UIServerAccessPolicy.test: cover the malformed Origin URL branch in
  isOriginAllowed and the allowedHosts-fallback branch when
  allowedOrigins is empty; pin the design choices for whitespace-padded
  Host normalization, uppercase X-Forwarded-Proto values, IPv4-mapped
  IPv6 loopback proxies under allowLoopbackProxy, and the policy's
  intentional non-detection of req.socket.encrypted without forwarded
  protocol headers.
- UIServerAccessPolicy.test: tighten the previously weak assertions on
  the accessPolicy-undefined paths (now check the denial reason and
  the resolved client address); rename the misleading
  'should reject empty-but-present X-Forwarded-For' test to reflect
  what it actually exercises (no parseable addresses); replace the
  trivial cache-isolation assertion with a real
  cacheA.decisions.has(req) / cacheB.decisions.has(req) check.
- UIMCPServer.test: drop the two malformed-host tests that re-tested
  policy logic already covered by UIServerAccessPolicy.test; the
  Connection: close tests in the same describe still anchor the
  transport-level rendering contract.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
…tified in second-pass audit

- ConfigurationSchema.test: validate the allowedHosts schema refine
  rejects malformed entries (excess colons, non-numeric port, port out
  of range, empty input) and accepts canonical hostnames and IP
  literals; lock the canonical UI_SERVER_ACCESS_POLICY_DEFAULTS map
  shape so a default change cannot drift silently.
- UIServerNet.test: cover normalizeHost directly (rejection branch is
  the boundary of the allowedHosts schema refine; previously only
  exercised indirectly through transport tests).
- UIServerSecurity.test: assert readLimitedBody propagates upstream
  stream errors (security-relevant fail-closed behavior).
- UIServerAccessPolicy.test: rename the misleading
  for=unknown collision test to reflect the actual code path
  (collision is generic, not unknown-specific); drop the duplicate
  encrypted-proxy plaintext rejection (the encrypted flag is ignored
  by the policy by design and a dedicated test already pins it);
  tighten the whitespace-padded Host test to use an explicit
  allowedHosts list so the trim path is genuinely exercised rather
  than the loopback alias fallback.
- UIServerTestUtils: drop the dead EXTERNAL_CLIENT_IP export and
  correct the RFC reference comment (RFC 5737 IPv4 / RFC 2606
  example.com — RFC 3849 covers IPv6 and is irrelevant here).
- UIWebSocketServer: add a brief comment documenting why
  buildUpgradeRejectionResponse stays separate from
  AbstractUIServer.renderDenial — pre-handshake WS rejections write
  raw HTTP/1.1 to a Duplex socket while renderDenial targets
  ServerResponse.
- src/utils/index: re-export UI_SERVER_ACCESS_POLICY_DEFAULTS so the
  defaults can be asserted from the schema test layer.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
- UIServerAccessPolicy: getForwardedHost rejects multi-value
  X-Forwarded-Host as AmbiguousForwardedHost, mirroring the symmetric
  guards in getForwardedProtocol and getForwardedClientAddress. The PR
  description's claim that 'multi-value X-Forwarded-* are rejected'
  now applies uniformly across the three forwarded dimensions.
- UIServerNet: normalizeHost validates the hostname charset against a
  conservative [a-z0-9._-]+ allowlist on the dot path. Inputs with
  commas, spaces, or unbalanced brackets are rejected at config-load
  time when used as allowedHosts entries, and at runtime as a
  defense-in-depth check on the Host header.
- UIServerNet: isValidPort rejects port 0 (RFC 6335 reserved). Port 0
  in a client-side Host header has no useful meaning; tightening to
  1..65535 matches common practice and the prior config-bind path is
  unaffected.
- README: requireTlsForNonLoopback wording corrected — non-loopback
  requests without forwarded protocol headers are denied as
  tls-required, not merely 'not detected', even when the underlying
  socket is encrypted.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
… warn

- UIServerAccessPolicy: parseSingleForwardedHeader normalises an empty
  Forwarded header value (e.g., 'Forwarded: ') to ABSENT instead of
  rejecting it as AmbiguousForwardedHeader. The PR description claim
  that 'empty forwarded values are treated as absent' now applies to
  the header value itself, not only to parameters inside the header.
- UIMCPServer: sendErrorResponse accepts an optional headers argument
  so 405 Method Not Allowed responses advertise 'Allow: GET, POST,
  DELETE' per RFC 9110 §15.5.6.
- AbstractUIServer: warn at startup when the UI server is bound to a
  wildcard host ('', '0.0.0.0', '::') with an empty
  accessPolicy.allowedHosts; the previously silent lockout (every
  request denied as host-not-allowed) now produces an actionable log
  line pointing at the configuration to adjust.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
- AbstractUIServer: warnIfMisconfigured now also fires when the UI
  server is bound to a non-loopback specific host with
  requireTlsForNonLoopback=true and no accessPolicy.trustedProxies;
  the previously silent path (every plaintext request denied as
  tls-required) now produces an actionable startup log line. Wildcard
  binding with empty allowedHosts retains its dedicated warning.
- AbstractUIServer: rate-limit denials now emit a warn log symmetric
  to the access-policy 403 path so operators can detect probing.
  Previously the 429 branch returned silently, which made abusive
  clients invisible from the logs.
- README: drop the 'even when the underlying socket is encrypted'
  caveat from the requireTlsForNonLoopback description; the simulator
  only listens via plaintext or h2c, so the scenario described was
  unreachable. The runtime behaviour is unchanged and the test that
  pins the design choice stays as defense in depth.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
@jerome-benoit
jerome-benoit merged commit 72bb3f0 into main Jun 14, 2026
44 checks passed
jerome-benoit added a commit that referenced this pull request Jun 14, 2026
)

* fix(ui-server): reject ports in allowedHosts, fix host normalization edges

- ConfigurationSchema: reject allowedHosts entries that carry a port
  (e.g., 'gateway.example.com:8080', '[::1]:8080'). Runtime host
  matching strips ports, so a port-bearing entry was silently
  equivalent to its host-only form. Operators are now forced to
  spell out host-only entries at config load time, matching how
  matching actually works.
- UIServerNet: normalizeHost strips a trailing dot after the colon
  split rather than from the whole input, so a Host header like
  'localhost.:80' now resolves to 'localhost' instead of leaving
  the trailing dot intact and failing the allowlist match.
- UIServerAccessPolicy: nonEmpty treats whitespace-only forwarded
  values as absent, and hasForwardedHeaders consumes nonEmpty so
  the two helpers agree. A whitespace-only X-Forwarded-Proto no
  longer flips forwardedHeadersPresent to true and triggers an
  Ambiguous* denial.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>

* fix(ui-server): attach socket error listener before WS upgrade rejection writes

The onSocketError listener was previously attached only after the
prologue and bad-header guards had already written their rejection
responses, and was removed before the auth-failure rejection write.
A client TCP-reset between an upgrade event and the destroy callback
could fire 'error' on the Duplex socket with no listener, which Node
escalates to an unhandled exception and crashes the process.

The listener is now attached at the top of the upgrade handler and
only removed once webSocketServer.handleUpgrade takes ownership of
the socket. All three rejection paths (bad upgrade headers, prologue
failure, auth failure) keep the listener until socket.destroy(),
neutralising the DoS vector.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>

* refactor(ui-server): tighten access-policy schema messages and forwarded parsing

- Schema: split UIServerListenOptions validation so non-object values
  surface 'must be a non-array object' instead of the misleading
  'accessPolicy must be configured under uiServer' message.
- Forwarded parser: unescape RFC 7230 quoted-pair sequences inside
  double-quoted Forwarded parameter values.
- getForwardedClientAddress: propagate forwarded.kind === 'error' before
  the trustedProxy gate, matching getForwardedProtocol and
  getForwardedHost (no behavioral change today; closes a latent
  asymmetry if the upstream untrusted-peer gate is reordered).
- UIServerAccessCache: document identity-based cache invalidation for
  trustedProxies; reload flows must construct a new configuration.
- getForwardedProtocol / getForwardedHost: distinguish length === 0
  (new InvalidForwardedProtocol / InvalidForwardedHost reasons) from
  length > 1 (existing Ambiguous reasons), matching the existing
  InvalidForwardedClient / AmbiguousForwardedClient pattern.

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>

---------

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
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