Repository navigation
Add audit handler middleware that routes audit records to stdout - #565
tgrunnagle wants to merge 3 commits into
Conversation
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
left a comment
There was a problem hiding this comment.
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.modunchanged (the OTel metric packages are already direct dependencies). TheCLAUDE.mdand README rows match their neighbours. - The metric name
audit.write.failuresbecomes an operator-facing contract; deciding on thestacklok.prefix while the package is Alpha is cheap. - The
CLAUDE.mdchange 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/...andtask license-checkshould stay clean.- Add a middleware to a
logging.New(...)logger and emitevent.LogTo(ctx, logger, audit.LevelAudit)atslog.LevelWarn: expect one JSON line on stdout with"level":"AUDIT"and"logger":"audit", and nothing on stderr. - Pass a writer whose
Writealways errors: the log call must return normally, and theaudit.write.failurescounter should rise by one per record. - Deliberately break it: remove
s.mu.Lock()inauditSink.writeandTestHandlerMiddleware_ConcurrentWritesWholeLinesshould fail only under-race; changeif n > 0to an unconditional assignment and no test fails (see themidLinecoverage 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.
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
left a comment
There was a problem hiding this comment.
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
LogTostill 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) WithAuditWriterrepeats the package name and differs fromlogging.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
midLineset (audit/handler.go) - The AUDIT level rewrite and line format are duplicated in
NewAuditLoggerand differ (audit/handler.go) - The
2*(i+1)failure count is unexplained (audit/handler_test.go) midLinetransitions 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/...andtask license-checkshould stay clean.- Remove
s.mu.Lock()inauditSink.write:TestHandlerMiddleware_ConcurrentWritesWholeLinesshould fail even without-race. - Make
if n > 0unconditional inauditSink.write:TestHandlerMiddleware_LineBoundaryTransitionsshould 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.
Related to #343 (covers the failed-write counter; the per-call failure result is not part of this PR)
Summary
Adds
audit.HandlerMiddleware, aslog.Handlermiddleware for use withlogging.WithHandlerMiddleware. A service can keep one logger:LevelAuditrecords 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(newhandler.go)HandlerMiddleware(opts ...MiddlewareOption) func(slog.Handler) slog.Handler, with optionsWithEnabled(bool)(default true),WithWriter(io.Writer)(defaultos.Stdout) andWithMeterProvider(metric.MeterProvider)(defaultotel.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.levelset toAUDITandloggerset toaudit, regardless of the operator logger's format. The wrapped handler never sees them.WithAttrsandWithGroupapply to the wrapped handler only, so an audit line carries only the event's fields plustime,level,msgandlogger, all at the top level.Writecall under a mutex. Every handler built from oneHandlerMiddlewareresult shares that sink and lock, so concurrent records do not interleave.stacklok.audit.write.failurescounter 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)With/WithGrouphandling, 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 stampslogger=audit, notNewAuditLogger.CLAUDE.mdandREADME.md: added anauditrow to the package tables.Implementation Notes
doc.go.renderAuditLine, returns the exact bytes written, so anything that later measures audit lines can use the same function.NewAuditLoggerdoes, so sub-second precision is kept.NewAuditLoggernow shares theAUDITlevel-name constant. Its output is otherwise unchanged.Verification
Run at 03c88d8:
task(golangci-lint,go vet,go test -race ./..., redisconn modules): exit 0, "0 issues.", no FAILtask license-check: exit 0auditpackage coverage: 97.9%Acceptance criteria (tests in
audit/handler_test.go):msgaudit_event,levelAUDITandloggeraudit, and is absent from operator output:TestHandlerMiddleware_RoutesAuditRecordToAuditWriterTestHandlerMiddleware_LeavesOperatorRecordsUnchangedWithandWithGroupdo not affect audit records and still apply to operator records:TestHandlerMiddleware_DropsWithAttrsAndGroupsTestHandlerMiddleware_IgnoresOperatorLevelTestHandlerMiddleware_InnerMiddlewareCannotTouchAuditRecordsEnabledreturns false and operator records are unaffected:TestHandlerMiddleware_GateOffTestHandlerMiddleware_FailedWriteCountedTestHandlerMiddleware_FailedWriteNotLoggedTestHandlerMiddleware_ShortWriteRestoresLineBoundary-race:TestHandlerMiddleware_ConcurrentWritesWholeLinesloggingis unchanged, andgo.modandgo.sumare unchanged (OpenTelemetry API and SDK packages are already direct dependencies).Additional Notes
🤖 Generated with Claude Code