Skip to content

Add audit handler middleware that routes audit records to stdout - #565

Open
tgrunnagle wants to merge 3 commits into
mainfrom
pointed-tamarillo-cd760e33
Open

tgrunnagle wants to merge 3 commits into
mainfrom
pointed-tamarillo-cd760e33

Conversation

@tgrunnagle

@tgrunnagle tgrunnagle commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Related to #343 (covers the failed-write counter; the per-call failure result is not part of this PR)

Summary

Adds audit.HandlerMiddleware, a slog.Handler middleware for use with logging.WithHandlerMiddleware. A service can keep one logger: LevelAudit records go to a dedicated audit writer (stdout by default) as JSON, and every other record goes to the wrapped handler unchanged. Audit write failures are counted on an OpenTelemetry counter instead of being returned or logged.

Changes

audit (new handler.go)

  • HandlerMiddleware(opts ...MiddlewareOption) func(slog.Handler) slog.Handler, with options WithEnabled(bool) (default true), WithWriter(io.Writer) (default os.Stdout) and WithMeterProvider(metric.MeterProvider) (default otel.GetMeterProvider()).
  • WriteFailuresMetricName (stacklok.audit.write.failures), the exported name of the failed-write counter.
  • Enabled(ctx, LevelAudit) reports the gate alone and ignores the wrapped handler's level. Other levels defer to the wrapped handler.
  • Audit records are rendered as one JSON line, with level set to AUDIT and logger set to audit, regardless of the operator logger's format. The wrapped handler never sees them.
  • WithAttrs and WithGroup apply to the wrapped handler only, so an audit line carries only the event's fields plus time, level, msg and logger, all at the top level.
  • Each record is written with a single Write call under a mutex. Every handler built from one HandlerMiddleware result shares that sink and lock, so concurrent records do not interleave.
  • A failed or short write increments the stacklok.audit.write.failures counter by one, never returns an error to the caller and is never logged. After a short write, the next record is prefixed with a newline so it still parses as one JSON object. A write that lands only that newline counts as restoring the boundary.

Tests (new handler_test.go)

  • Tests for routing, operator-record passthrough, With/WithGroup handling, level independence, middleware ordering, the gate, failed and short writes, line-boundary transitions over a scripted writer, the no-op counter fallback, and 64 concurrent goroutines across two loggers sharing one middleware. The concurrency test detects overlapping writes directly as well as under the race detector.

Docs

  • audit/doc.go: new "Audit Handler Middleware" section covering registration as the last middleware, the gate, stdout routing, the failed-write counter, and an example. It also notes that only the middleware stamps logger=audit, not NewAuditLogger.
  • CLAUDE.md and README.md: added an audit row to the package tables.

Implementation Notes

  • The middleware must be registered last so it is the outermost handler. A middleware registered before it cannot see, change or drop audit records. One registered after it would see them, and the library cannot prevent that. This is documented in doc.go.
  • The JSON renderer is unexported, to avoid committing to an API for it. Its single entry point, renderAuditLine, returns the exact bytes written, so anything that later measures audit lines can use the same function.
  • Audit timestamps use slog's default time format, as NewAuditLogger does, so sub-second precision is kept.
  • NewAuditLogger now shares the AUDIT level-name constant. Its output is otherwise unchanged.
  • If the meter provider returns an error creating the counter, the middleware falls back to a no-op counter so a metrics problem never blocks audit output.

Verification

Run at 03c88d8:

  • task (golangci-lint, go vet, go test -race ./..., redisconn modules): exit 0, "0 issues.", no FAIL
  • task license-check: exit 0
  • audit package coverage: 97.9%

Acceptance criteria (tests in audit/handler_test.go):

  • An audit record is one JSON line on the audit writer with msg audit_event, level AUDIT and logger audit, and is absent from operator output: TestHandlerMiddleware_RoutesAuditRecordToAuditWriter
  • Debug, info, warn and error records are byte-for-byte unchanged and never reach the audit writer: TestHandlerMiddleware_LeavesOperatorRecordsUnchanged
  • With and WithGroup do not affect audit records and still apply to operator records: TestHandlerMiddleware_DropsWithAttrsAndGroups
  • Audit records are written at operator level warn and error, and info is still filtered: TestHandlerMiddleware_IgnoresOperatorLevel
  • Middleware registered before this one cannot stamp, alter or drop audit records, and audit lines stay JSON with a text operator format: TestHandlerMiddleware_InnerMiddlewareCannotTouchAuditRecords
  • With the gate off, nothing is written, Enabled returns false and operator records are unaffected: TestHandlerMiddleware_GateOff
  • A failing writer does not fail the log call, and the counter rises by exactly one per failed record: TestHandlerMiddleware_FailedWriteCounted
  • A failing writer writes nothing to operator output: TestHandlerMiddleware_FailedWriteNotLogged
  • After a short write, the next record starts on a new line and parses: TestHandlerMiddleware_ShortWriteRestoresLineBoundary
  • 64 goroutines logging 100 audit and 100 operator records each produce 6,400 whole JSON lines under -race: TestHandlerMiddleware_ConcurrentWritesWholeLines
  • logging is unchanged, and go.mod and go.sum are unchanged (OpenTelemetry API and SDK packages are already direct dependencies).

Additional Notes

🤖 Generated with Claude Code

Add audit.HandlerMiddleware, a slog handler middleware for
logging.WithHandlerMiddleware. A service keeps one logger: LevelAudit
records go to a dedicated audit writer (stdout by default) as one JSON
line each, with level "AUDIT" and logger=audit, while every other record
reaches the wrapped handler unchanged.

- Enabled(LevelAudit) answers from the gate alone, ignoring the operator
  level; WithEnabled(false) drops audit records.
- With/WithGroup apply to operator records only.
- Audit records never reach the wrapped handler, so inner middleware
  cannot see, change or drop them. Register the middleware last.
- A failed or short write is never returned or logged; it increments
  the audit.write.failures OpenTelemetry counter. After a short write
  the next record starts on a new line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Review

This is an additive feature in the Alpha audit package: HandlerMiddleware routes LevelAudit records to a dedicated JSON writer (stdout by default) behind an enable gate, passes everything else to the wrapped handler untouched, and counts failed writes on an OpenTelemetry counter. The design is sound. The gate, the outermost-handler placement, the single Write under a mutex, the short-write line repair and the no-op counter fallback all behave as documented, and the tests are thorough (routing, passthrough, ordering, gate, failures, 64-goroutine concurrency). No finding rises above LOW. The points worth weighing before merge are that the AUDIT level rewrite is now duplicated with NewAuditLogger (and the two diverge), that each application of the middleware gets its own sink while doc.go states an unqualified no-interleaving guarantee, and that a few doc claims overstate what LogTo saves when the gate is off.

Cross-cutting observations

  • Compatibility: purely additive, no exported signature changes, go.mod unchanged (the OTel metric packages are already direct dependencies). The CLAUDE.md and README rows match their neighbours.
  • The metric name audit.write.failures becomes an operator-facing contract; deciding on the stacklok. prefix while the package is Alpha is cheap.
  • The CLAUDE.md change only adds a package-table row; it asks nothing new of contributors.

How to test

  • go test -race ./audit/... should pass; golangci-lint run ./audit/... and task license-check should stay clean.
  • Add a middleware to a logging.New(...) logger and emit event.LogTo(ctx, logger, audit.LevelAudit) at slog.LevelWarn: expect one JSON line on stdout with "level":"AUDIT" and "logger":"audit", and nothing on stderr.
  • Pass a writer whose Write always errors: the log call must return normally, and the audit.write.failures counter should rise by one per record.
  • Deliberately break it: remove s.mu.Lock() in auditSink.write and TestHandlerMiddleware_ConcurrentWritesWholeLines should fail only under -race; change if n > 0 to an unconditional assignment and no test fails (see the midLine coverage finding).

Recommendation: APPROVE (no HIGH findings). The review is posted as a comment because the PR is a draft.

Findings

# Severity Finding Location Raised by
1 LOW LogTo still builds every attribute when the gate is off audit/doc.go:115 documentation
2 LOW "Exactly the fields of its event" omits time, level, msg and logger audit/doc.go:119 documentation
3 LOW Metric name lacks the stacklok. prefix and is not exported audit/handler.go:35 api-design
4 LOW WithAuditWriter repeats the package name and differs from logging.WithOutput audit/handler.go:58 api-design
5 LOW Each application of the middleware gets its own sink, so a shared writer has no common lock audit/handler.go:107 correctness, documentation
6 LOW The no-op counter fallback is never exercised audit/handler.go:177 tests
7 LOW A short write that lands only the repair newline leaves midLine set audit/handler.go:204 correctness
8 LOW The AUDIT level rewrite and line format are duplicated in NewAuditLogger and differ audit/handler.go:212 readability, api-design
9 LOW The 2*(i+1) failure count is unexplained audit/handler_test.go:336 readability
10 LOW midLine transitions beyond one short-write sequence are untested audit/handler_test.go:361 tests
11 LOW The concurrency test passes without the sink mutex unless run under -race audit/handler_test.go:390 tests

Reviewed by dev:review-pr (finders: correctness, readability, api-design, tests, documentation). Generated with Claude Code.

Comment thread audit/doc.go Resolved
Comment thread audit/doc.go Resolved
Comment thread audit/handler.go Resolved
Comment thread audit/handler.go Resolved
Comment thread audit/handler.go Resolved
Comment thread audit/handler.go Resolved
Comment thread audit/handler.go Resolved
Comment thread audit/handler_test.go Resolved
Comment thread audit/handler_test.go Resolved
Comment thread audit/handler_test.go Resolved
@tgrunnagle
tgrunnagle marked this pull request as ready for review November 24, 2026 15:07
tgrunnagle and others added 2 commits November 24, 2026 07:10
Addresses #565 review comments:
- LOW audit/doc.go:115 (4681864469): say slog skips constructing the record when the gate is off, not that LogTo skips building attributes
- LOW audit/doc.go:119 (4681864487): list time, level, msg and logger=audit alongside the event's fields
- LOW audit/handler.go:35 (4681864502): rename the counter to stacklok.audit.write.failures and export it as WriteFailuresMetricName
- LOW audit/handler.go:58 (4681864515): rename WithAuditWriter to WithWriter
- LOW audit/handler.go:107 (4681864524): build one sink per HandlerMiddleware result so every application shares its lock
- LOW audit/handler.go:204 (4681864558): clear midLine when only the repair newline was written
- LOW audit/handler.go:212 (4681864570): share levelAuditName with NewAuditLogger and document that only the middleware stamps logger=audit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Addresses #565 review comments:
- LOW audit/handler.go:177 (4681864542): test the no-op counter fallback with a meter provider whose counter creation fails
- LOW audit/handler_test.go:336 (4681864584): name the two failures per iteration
- LOW audit/handler_test.go:361 (4681864605): table-driven scripted-writer test over midLine transitions
- LOW audit/handler_test.go:390 (4681864620): detect overlapping writes directly, across two loggers sharing one middleware

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@tgrunnagle tgrunnagle left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Review

Incremental review of the 2 commits since the last review. Those commits settle every finding from the previous review, and the new code and tests turned up nothing at or above MEDIUM severity.

The shared sink is now built once in HandlerMiddleware, so all handlers from one result serialize on one lock and one counter; the repair-newline accounting in auditSink.write is correct for every (midLine, n, err) combination; and the new tests (scripted-writer line-boundary table, overlap-detecting writer, failing meter provider) each fail when the behavior they pin is removed. The rename to WithWriter and the exported WriteFailuresMetricName leave NewAuditLogger output unchanged.

Resolved since the last review

  • LogTo still builds every attribute when the gate is off (audit/doc.go)
  • "Exactly the fields of its event" omits time, level, msg and logger (audit/doc.go)
  • Metric name lacks the stacklok. prefix and is not exported (audit/handler.go)
  • WithAuditWriter repeats the package name and differs from logging.WithOutput (audit/handler.go)
  • Each application of the middleware gets its own sink, so a shared writer has no common lock (audit/handler.go)
  • The no-op counter fallback is never exercised (audit/handler.go)
  • A short write that lands only the repair newline leaves midLine set (audit/handler.go)
  • The AUDIT level rewrite and line format are duplicated in NewAuditLogger and differ (audit/handler.go)
  • The 2*(i+1) failure count is unexplained (audit/handler_test.go)
  • midLine transitions beyond one short-write sequence are untested (audit/handler_test.go)
  • The concurrency test passes without the sink mutex unless run under -race (audit/handler_test.go)

How to test

  • go test -race ./audit/... should pass; golangci-lint run ./audit/... and task license-check should stay clean.
  • Remove s.mu.Lock() in auditSink.write: TestHandlerMiddleware_ConcurrentWritesWholeLines should fail even without -race.
  • Make if n > 0 unconditional in auditSink.write: TestHandlerMiddleware_LineBoundaryTransitions should fail.

Recommendation: APPROVE (no HIGH findings). Posted as a comment because the reviewer is the PR author.


Reviewed by dev:review-pr (finders: correctness, readability, api-design, tests). Generated with Claude Code.

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.

2 participants