Skip to content

fix(audit): forward raw transport evidence with audit events - #30

Merged
PMQ9 merged 3 commits into
wiki-v2from
fix/320-fork-client-evidence
Sep 16, 2026
Merged

PMQ9 merged 3 commits into
wiki-v2from
fix/320-fork-client-evidence

Conversation

@PMQ9

@PMQ9 PMQ9 commented Sep 16, 2026 •

Copy link
Copy Markdown

TL;DR

Forward raw transport evidence — the socket peer and the unparsed X-Forwarded-For header — with each audit event, so the audit sink resolves the client address using its own trusted-proxy configuration instead of relying on an address this service computed.

A proxy-aware decision belongs with the component that knows the proxy topology. This service does not, so it now reports what it observed rather than its conclusion.

What changed

  • platform-audit.service.ts — a private clientEvidence() reads the request from CLS_REQ and returns { socketPeer, forwardedFor }, attached to every forwarded event including updateRetention.
  • platform-audit.client.ts — AuditIngestEvent gains clientEvidence, typed by a new exported AuditClientEvidence. ipAddress is documented as legacy.
  • authorization-service.openapi.json — declares clientEvidence via a new AuditClientEvidence schema. AuditEvent is additionalProperties: false and did not list the field, so the published document did not admit something the sink accepts.
  • platform-audit.wiring.spec.ts (new) — pins the hook ordering this depends on, plus the evidence-construction cases.

No upstream file is touched

nestjs-cls stores the request under CLS_REQ (saveReq defaults to true, and ClsModule.forRoot is mounted globally in app.module.ts), and Nest runs every middleware through middie with the raw node request. So the socket peer and header are reachable from PlatformAuditService, which already injects ClsService.

Reading them there rather than widening AuditContext keeps apps/server/src/common/middlewares/audit-context.middleware.ts byte-identical to v0.95.0 and needs no UPSTREAM_MODIFICATIONS.md entry. Every file here sits under an existing EXCLUDE_PREFIXES path (apps/server/src/authz/, docs/integrations/), so the upstream boundary check is unaffected.

Why the ordering is pinned by a test

Which hook defines request.ip — Nest's middie or the fastify-ip plugin — depends on registration order in main.ts, and the two produce different answers. That ordering is invisible at the call site and would survive any amount of unit testing of the forwarder itself, so platform-audit.wiring.spec.ts boots a real Nest app wired the way main.ts wires one and asserts it directly. If a future change reorders registration, the spec fails rather than the behaviour silently shifting.

Behaviour and compatibility

  • Together-or-neither. The sink treats supplied evidence as authoritative, so a half-populated object would be misread. With no usable socket peer the object is omitted entirely and the sink falls back to the legacy field.
  • Exactly two keys. The sink validates strictly and rejects the whole batch on an unknown nested key, which this fire-and-forget client swallows as a warn. The spec pins the key set.
  • Legacy ipAddress is still sent, so an older sink keeps working; it is preferred only when no evidence is present.
  • Header normalisation. x-forwarded-for is typed string | string[]; Node comma-joins repeated lines, so the array branch is unreachable at runtime, but it is narrowed rather than cast, and pinned by a test.
  • No config, no migration, no new dependency.

How this was tested

$ npx jest src/authz
Test Suites: 25 passed, 25 total
Tests:       253 passed, 253 total

Every behaviour is mutation-checked — each of these previously passed and now reds only its own tests:

Mutation Result
clientEvidence() always returns undefined 5 red
use request.ip instead of the socket peer 5 red
drop the together-or-neither guard 3 red
drop array normalisation 1 red
toEvent stops attaching evidence 5 red

Pre-existing and untouched: three TS2322 errors in src/service-bridge/*.pg.spec.ts, and prettier --check warnings on the two audit files. Both reproduce identically on the base commit (verified by stashing), and no CI job gates fork formatting.

Deploy note

Paired with a downstream submodule repoint, which is what actually ships this. The sink-side support is already released, and both components ship in the same task definition, so there is no version-skew window; the ordering constraint is merge order only.

The audit sink resolves a forwarded event's client address itself, using
its own trusted-proxy configuration, rather than relying on an address
this service computed. This change sends it the inputs to do that.

What is sent: socketPeer (the peer address of the socket we served the
request on) and forwardedFor (the raw X-Forwarded-For header, unparsed).
Both together or neither, and exactly those two keys -- a proxy-aware
decision belongs with the component that knows the proxy topology, and
this service does not.

No upstream file is touched. nestjs-cls stores the request under CLS_REQ
(saveReq defaults to true, and ClsModule.forRoot is mounted globally), and
Nest runs middleware through middie with the raw node request, so the
socket peer and header are reachable from this module, which already
injects ClsService. Reading them here rather than widening AuditContext
keeps common/middlewares/audit-context.middleware.ts byte-identical to
v0.95.0 and needs no UPSTREAM_MODIFICATIONS.md entry.

platform-audit.wiring.spec.ts pins the middleware/plugin hook ordering this
depends on against a real Nest app wired the way main.ts wires one, because
that ordering is invisible at the call site and would otherwise survive any
amount of unit testing of the forwarder.

Contract: AuditEvent in the published authorization-service.openapi.json is
additionalProperties:false and did not list clientEvidence, so the document
did not admit a field the sink accepts. It now declares it via a new
AuditClientEvidence schema.

Compatibility: the legacy ipAddress is still sent, so an older sink keeps
working; the sink prefers clientEvidence when present. With no usable
socket peer the object is omitted entirely rather than sent half-populated.

Tests: 25 suites / 253 authz specs pass, each behaviour mutation-checked.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@PMQ9
PMQ9 force-pushed the fix/320-fork-client-evidence branch from 5fd39a9 to c77865a Compare September 16, 2026 03:44
@PMQ9 PMQ9 changed the title fix(audit): forward raw client evidence so the platform decides the IP (#320) fix(audit): forward raw transport evidence with audit events Sep 16, 2026
PMQ9 and others added 2 commits September 15, 2026 23:45
Review of the two-PR set found 2 merge-blocking and 7 non-blocking
Level-3 findings. The fork-side fixes:

- Declare clientEvidence in the published request EXAMPLE, not just the
  schema. Both contract suites derive their fixtures from the example and
  never read components.schemas, so the schema alone was prose to CI: a
  one-sided field rename kept both repos green while every batch 400d
  under the sink's forbidNonWhitelisted and was swallowed as a warn.
  Verified the example is now load-bearing -- renaming the field in it
  reds the provider contract spec, which posts it through the real pipe.

- Pin the two preconditions that make CLS_REQ readable. Reading the
  request from CLS is what keeps this change out of upstream files, but it
  trades a documented upstream EDIT for an undocumented dependency on
  upstream CONFIGURATION (app.module.ts mounting ClsModule) and a
  third-party DEFAULT (saveReq). Both lived only in a comment, and every
  other test injects a fake ClsService -- so if either lapsed, evidence
  would silently stop, the sink would fall back to the forgeable legacy
  field, and the suite would stay green. Now pinned by source assertions
  plus a real-boot probe that proves the library default still populates
  CLS_REQ with the socket and headers intact.

- Scope evidence to the CLS-derived path. logWithContext /
  logBatchWithContext mean "I am telling you the context"; also reading
  ambient CLS would take the actor from the caller and the network origin
  from whatever request was on the stack, then hash-chain the result.
  Benign today (the only caller is the queue-backed import worker) but
  IAuditService is upstream-owned, so a future caller could run
  mid-request. Now tested in both directions.

- Give the dropped-forward warning an AUDIT_FORWARD_FAILED token. The
  forward is fire-and-forget, so a systematic rejection drops every event
  while the request path stays healthy; the line had no UPPER_SNAKE opener,
  so it was neither greppable nor alarmable. The paired metric filter and
  alarm land in the downstream repoint.

- Correct the published schema: socketPeer is now `required`, and the
  prose no longer says "send both fields together" when the forwarder
  legitimately sends {socketPeer} alone on a request with no
  X-Forwarded-For. A third party following the old wording literally would
  have fallen back to the forgeable path.

- Fix an overstated comment: the main.ts source pins are what catch a
  reordering; the boot block builds its own adapter and is a dependency
  canary, not an observer of main.ts.

Also covered: updateRetention's evidence line, previously mutation-proven
untested.

Tests: 25 suites / 258 specs. Four new mutations each red exactly one test
(ClsModule mount removed, saveReq disabled, ambient evidence leaking into
logWithContext, updateRetention dropping evidence).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- Remove `required: ["socketPeer"]` from the published AuditClientEvidence.
  It was the round-1 defect with the sign flipped: the schema constrains
  what a SINK must accept, and ours deliberately accepts a peerless object
  and records it as a refusal -- a tested invariant that stops a caller
  choosing the forgeable resolver by omitting the peer. Declaring the shape
  invalid invites a conformant sink to 400 it, losing a whole batch over
  one malformed entry. The producer obligation is stated in prose, enforced
  in code, and tested; it does not belong in `required`.

- Same correction to the AuditClientEvidence jsdoc, which still said "send
  both fields together" while the forwarder legitimately sends
  { socketPeer } alone on a request with no X-Forwarded-For.

- Tighten the saveReq pin from `saveReq: false` to any `saveReq:` at all.
  `saveReq: process.env.NODE_ENV !== 'production'` disabled it in
  production with the whole suite green -- the same silent-disarm shape the
  block exists to prevent, one level up. Mutation-confirmed.

- Assert the AUDIT_FORWARD_FAILED token is actually EMITTED on both failure
  paths. The alarm's entire trigger is that substring, and this PR reworded
  both warn lines; a whole-file grep proves the token exists somewhere, not
  that the failure path emits it. Rewording the line now reds.

- Anchor the trustProxy pin to a code line so it cannot be satisfied by the
  word appearing in a comment.

Tests: 25 suites / 260 specs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@PMQ9
PMQ9 merged commit eda4794 into wiki-v2 Sep 16, 2026
@PMQ9
PMQ9 deleted the fix/320-fork-client-evidence branch September 16, 2026 12:22
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