Skip to content

fix(logpipe): prevent pgaudit records being silently dropped by zap sampler - #11109

Closed
akashbhujbalwebsite wants to merge 6 commits into
cloudnative-pg:mainfrom
akashbhujbalwebsite:fix/pgaudit-audit-log-sampling-drop
Closed

akashbhujbalwebsite wants to merge 6 commits into
cloudnative-pg:mainfrom
akashbhujbalwebsite:fix/pgaudit-audit-log-sampling-drop

Conversation

@akashbhujbalwebsite

@akashbhujbalwebsite akashbhujbalwebsite commented Jul 1, 2026 •

Copy link
Copy Markdown

Fixes a silent audit-log loss in LogRecordWriter. Every PostgreSQL audit record it emits shares the same log message key ("record"), so the zap sampler controller-runtime installs in production mode (passing the first 100 identical messages per second, then roughly 1 in 100 after that) treats a burst of audit activity as duplicates and drops most of it, including security-relevant events such as DDL errors or privilege escalations, with no indication of the gap.

LogRecordWriter now writes through a dedicated logger with sampling disabled, built once when the log pipe starts and reused across every reconnect. That logger otherwise mirrors the global instance-manager logger for Info-level output: the same JSON/RFC3339Nano encoding, the same effective --log-level, and the same --log-field-level/--log-field-timestamp remapping, so audit records only differ from the rest of the pod's log lines in that they're never sampler-dropped.

Fixes #10815


Root cause

// writer.go (before)
const logRecordKey = "record" // constant — never varies

func (writer *LogRecordWriter) Write(record NamedRecord) {
    log.WithName(record.GetName()).Info(logRecordKey, logRecordKey, record)
    //                                  ^^^^^^^^^^^^
    //             every audit record uses msg="record" → sampler treats all as duplicates
}

controller-runtime v0.24.1 adds this sampler automatically when Development=false:

zap.WrapCore(func(core zapcore.Core) zapcore.Core {
    return zapcore.NewSamplerWithOptions(core, time.Second, 100, 100)
})

That's fine for operator reconcile-loop noise. It's not fine for audit records, where every entry represents a distinct real-world database event.

How to verify

  1. Deploy a cluster with pgaudit.log: all and shared_preload_libraries: pgaudit
  2. Fire a burst of 500+ SQL statements within a single second:
    DO $$ DECLARE i INT; BEGIN
      FOR i IN 1..500 LOOP EXECUTE 'SELECT ' || i; END LOOP;
    END $$;
    CREAT TABLE marker_should_appear(id int); -- intentional typo
  3. Check pod logs: kubectl logs <pod> -c postgres | grep marker_should_appear
    • Before fix: 0 results (marker event dropped by sampler)
    • After fix: 1 result (all records forwarded)

Tests

writer_test.go calls buildUnsampledLogger directly: one spec floods it with a burst and confirms every record is forwarded, another confirms it honors the effective level of the global instance-manager logger, and two more cover applyFieldRemap's key-renaming logic. A separate spec demonstrates the underlying zap sampler dropping records in isolation (not through CNPG code) to document why the bug is real.

Add to the release notes:

Fixed an issue where a burst of PostgreSQL audit activity (pgaudit) could cause most audit records to be silently dropped from the pod's log stream due to log sampling.

@akashbhujbalwebsite
akashbhujbalwebsite requested a review from a team July 1, 2026 09:06
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. bug 🐛 Something isn't working release-1.28 release-1.29 release-1.30 security 👮 labels Jul 1, 2026
@cnpg-bot cnpg-bot added the backport-requested ◀️ This pull request should be backported to all supported releases label Jul 1, 2026
@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

❗ By default, the pull request is configured to backport to all release branches.

  • To stop backporting this pr, remove the label: backport-requested ◀️ or add the label 'do not backport'
  • To stop backporting this pr to a certain release branch, remove the specific branch label: release-x.y

@akashbhujbalwebsite
akashbhujbalwebsite force-pushed the fix/pgaudit-audit-log-sampling-drop branch from 8127307 to 38a0d0d Compare July 1, 2026 09:38
@mnencia
mnencia force-pushed the fix/pgaudit-audit-log-sampling-drop branch from e6fe659 to 20644e7 Compare July 5, 2026 15:41
@mnencia

mnencia commented Jul 5, 2026

Copy link
Copy Markdown
Member

/test

@github-actions

github-actions Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

@cnpg-bot cnpg-bot added the ok to merge 👌 This PR can be merged label Jul 5, 2026
@mnencia
mnencia force-pushed the fix/pgaudit-audit-log-sampling-drop branch from 418f5ab to 4f77c5b Compare July 6, 2026 07:46
akashbhujbalwebsite and others added 6 commits July 6, 2026 11:08
…ampler

Every PostgreSQL audit record emitted by LogRecordWriter uses an identical
log message key ("record"). The zap sampler installed by controller-runtime in
production mode (100 initial pass-through, then 1-in-100 per second) treats
these as duplicates and silently drops all records beyond the first 100 within
any given second.

For a cluster with pgaudit.log=all a short burst of SQL activity can easily
exceed this threshold, causing security-relevant events such as DDL errors or
privilege escalations to be lost from the pod's log stream with no indication
of the gap.

Fix by constructing a dedicated unsampled logger for LogRecordWriter via
zap.NewProductionConfig() with cfg.Sampling = nil. The logger is initialized
once with sync.Once and shares the same JSON encoding and RFC3339Nano
timestamps as the global instance-manager logger so log aggregators see a
consistent schema.

Add unit tests that (a) confirm the unsampled logger emits all records during
a burst of 200 identical messages, and (b) confirm that a sampler-enabled
logger WOULD drop records under the same conditions, proving the fix is
necessary.

Fixes cloudnative-pg#10815

Signed-off-by: Akash Bhujbal <[email protected]>
go-logr/zapr is now a direct import but was still marked indirect,
and gci flagged the import grouping in both files.

Signed-off-by: Marco Nenciarini <[email protected]>
buildUnsampledLogger hardcoded zap.NewProductionConfig(), so audit
records always logged at Info regardless of --log-level and always
used the stock level/timestamp field names regardless of
--log-field-level/--log-field-timestamp, diverging from the rest of
the pod's log stream. It now reads the effective level off the
global instance-manager logger (via zapr.Underlier) and reuses
machinery's GetFieldsRemapFlags() for the field remapping, so audit
records only differ from other log lines by never being
sampler-dropped. --log-destination isn't handled: it's never passed
to the instance run process, only to the wal-archive/wal-restore
subcommands.

Building the core directly instead of going through zap.Config.Build()
also drops the silent fallback to the sampled global logger on build
error (there's no error path left) and stops adding caller info that
the rest of the pod's logs don't have.

Extended writer_test.go to call buildUnsampledLogger directly instead
of only exercising zap's sampler in isolation, so a regression in the
level-lookup or the no-sampling behavior is actually caught.

Signed-off-by: Marco Nenciarini <[email protected]>
applyFieldRemap read log.GetFieldsRemapFlags() internally, so its
only real logic (the two TrimPrefix branches) never ran in a go test
binary, since no --log-field-* flags are ever parsed there. Take the
flags as a parameter instead so a test can drive them directly.

Also assert on globalLoggerLevel() itself in the existing "honors the
effective level" spec, and tighten buildUnsampledLogger's docstring:
it mirrors the global logger's encoding for Info-level output only,
it doesn't replicate the custom Warning/Debug/Trace level-name
encoding machinery/pkg/log installs (LogRecordWriter never logs above
Info, so this was already dead code, just previously overclaimed).

Signed-off-by: Marco Nenciarini <[email protected]>
getRecordLogger's sync.Once-backed package-level singleton was lazy
self-initializing global state: whichever goroutine happened to log
the first audit record built and cached the logger for the rest of
the process. LogPipe.Start is only ever called once per process (it's
a controller-runtime Runnable), so there's already a well-defined
single point to build it eagerly instead.

LogRecordWriter now takes its logger via NewLogRecordWriter instead of
building one lazily on first use. LogPipe builds it once in Start, as
a local variable, before the collection goroutine is spawned, and
threads it through every retry of collectLogsFromFile (which
previously constructed a fresh &LogRecordWriter{} - and, before this
PR, a session with the sampler - on every reconnect). It's a plain
local captured by the closures rather than a struct field, so there's
no mutable shared state to reason about: the value is fixed before any
goroutine that reads it is started, and Go's happens-before guarantee
for goroutine starts covers every retry, not just the first.

Signed-off-by: Marco Nenciarini <[email protected]>
NewLogRecordWriter's and applyFieldRemap's doc comments each restated
the same "why" already explained in full on buildUnsampledLogger,
where the design decision actually lives. collectLogsFromFile's
comment repeated the "reused across every retry" reasoning already
given at the call site in Start. Trimmed all three to state contracts
without repeating the justification.

Write's comment still described the pre-refactor behavior of routing
through the shared global logger; it now writes through the writer's
own dedicated logger. buildUnsampledLogger's --log-destination note
overstated the guarantee as enforced when it's only true by current
deployment convention.

Signed-off-by: Marco Nenciarini <[email protected]>
@mnencia

mnencia commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

Closing this in favor of #11131, which fixes the same issue at the process level rather than inside the log pipe. Credit to you and to @willmurnane, whose diagnosis in #10815 identified the sampler mechanism from the start, it's cited directly in #11131's description and is what made that fix possible. Thanks for digging into this.

@mnencia mnencia closed this Jul 28, 2026
@github-project-automation github-project-automation Bot moved this from Todo to Done in Security Map Jul 28, 2026
@github-actions

Copy link
Copy Markdown
Contributor

❗ By default, the pull request is configured to backport to all release branches.

  • To stop backporting this pr, remove the label: backport-requested ◀️ or add the label 'do not backport'
  • To stop backporting this pr to a certain release branch, remove the specific branch label: release-x.y

mnencia added a commit that referenced this pull request Jul 28, 2026
Every process the manager binary runs inside a Cluster's pods now logs
without sampling. The controller keeps the duplicate-message sampler
that controller-runtime applies to every operator.

The manager's logger passed only the first 100 messages sharing the same
(level, message) pair each second, and roughly 1 in 100 afterwards.
Every PostgreSQL record forwarded by the instance manager's log pipe is
logged with the same message (`record`), so a burst of database
activity, such as pgaudit output under load, was silently collapsed and
most records were lost from the pod's log stream with no indication of
the gap.

The sampler is installed by the controller-runtime zap builder at
construction time and cannot be stripped afterwards, so the fix lives in
machinery: `ConfigureLogging` gained a `WithDisabledSampling()` option,
and the manager now passes it for every subcommand except `controller`.
The operator keeps sampling, since a reconciliation storm can repeat one
message well beyond the threshold, which is the case the sampler exists
for.

Credit to @willmurnane for the initial diagnosis in #10815, and to
@akashbhujbalwebsite for narrowing it down to the sampler mechanism in
#11109.

Closes #10815

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Marco Nenciarini <[email protected]>
Co-authored-by: Marco Nenciarini <[email protected]>
cnpg-bot pushed a commit to cloudnative-pg/api that referenced this pull request Jul 28, 2026
…pg/cloudnative-pg#11131)

Every process the manager binary runs inside a Cluster's pods now logs
without sampling. The controller keeps the duplicate-message sampler
that controller-runtime applies to every operator.

The manager's logger passed only the first 100 messages sharing the same
(level, message) pair each second, and roughly 1 in 100 afterwards.
Every PostgreSQL record forwarded by the instance manager's log pipe is
logged with the same message (`record`), so a burst of database
activity, such as pgaudit output under load, was silently collapsed and
most records were lost from the pod's log stream with no indication of
the gap.

The sampler is installed by the controller-runtime zap builder at
construction time and cannot be stripped afterwards, so the fix lives in
machinery: `ConfigureLogging` gained a `WithDisabledSampling()` option,
and the manager now passes it for every subcommand except `controller`.
The operator keeps sampling, since a reconciliation storm can repeat one
message well beyond the threshold, which is the case the sampler exists
for.

Credit to @willmurnane for the initial diagnosis in cloudnative-pg/cloudnative-pg#10815, and to
@akashbhujbalwebsite for narrowing it down to the sampler mechanism in
cloudnative-pg/cloudnative-pg#11109.

Closes cloudnative-pg/cloudnative-pg#10815

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Marco Nenciarini <[email protected]>
Co-authored-by: Marco Nenciarini <[email protected]>

(cherry picked from commit cloudnative-pg/cloudnative-pg@bf07333)
cnpg-bot pushed a commit that referenced this pull request Jul 28, 2026
Every process the manager binary runs inside a Cluster's pods now logs
without sampling. The controller keeps the duplicate-message sampler
that controller-runtime applies to every operator.

The manager's logger passed only the first 100 messages sharing the same
(level, message) pair each second, and roughly 1 in 100 afterwards.
Every PostgreSQL record forwarded by the instance manager's log pipe is
logged with the same message (`record`), so a burst of database
activity, such as pgaudit output under load, was silently collapsed and
most records were lost from the pod's log stream with no indication of
the gap.

The sampler is installed by the controller-runtime zap builder at
construction time and cannot be stripped afterwards, so the fix lives in
machinery: `ConfigureLogging` gained a `WithDisabledSampling()` option,
and the manager now passes it for every subcommand except `controller`.
The operator keeps sampling, since a reconciliation storm can repeat one
message well beyond the threshold, which is the case the sampler exists
for.

Credit to @willmurnane for the initial diagnosis in #10815, and to
@akashbhujbalwebsite for narrowing it down to the sampler mechanism in
#11109.

Closes #10815

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Marco Nenciarini <[email protected]>
Co-authored-by: Marco Nenciarini <[email protected]>
(cherry picked from commit bf07333)
cnpg-bot pushed a commit that referenced this pull request Jul 28, 2026
Every process the manager binary runs inside a Cluster's pods now logs
without sampling. The controller keeps the duplicate-message sampler
that controller-runtime applies to every operator.

The manager's logger passed only the first 100 messages sharing the same
(level, message) pair each second, and roughly 1 in 100 afterwards.
Every PostgreSQL record forwarded by the instance manager's log pipe is
logged with the same message (`record`), so a burst of database
activity, such as pgaudit output under load, was silently collapsed and
most records were lost from the pod's log stream with no indication of
the gap.

The sampler is installed by the controller-runtime zap builder at
construction time and cannot be stripped afterwards, so the fix lives in
machinery: `ConfigureLogging` gained a `WithDisabledSampling()` option,
and the manager now passes it for every subcommand except `controller`.
The operator keeps sampling, since a reconciliation storm can repeat one
message well beyond the threshold, which is the case the sampler exists
for.

Credit to @willmurnane for the initial diagnosis in #10815, and to
@akashbhujbalwebsite for narrowing it down to the sampler mechanism in
#11109.

Closes #10815

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Marco Nenciarini <[email protected]>
Co-authored-by: Marco Nenciarini <[email protected]>
(cherry picked from commit bf07333)
cnpg-bot pushed a commit that referenced this pull request Jul 28, 2026
Every process the manager binary runs inside a Cluster's pods now logs
without sampling. The controller keeps the duplicate-message sampler
that controller-runtime applies to every operator.

The manager's logger passed only the first 100 messages sharing the same
(level, message) pair each second, and roughly 1 in 100 afterwards.
Every PostgreSQL record forwarded by the instance manager's log pipe is
logged with the same message (`record`), so a burst of database
activity, such as pgaudit output under load, was silently collapsed and
most records were lost from the pod's log stream with no indication of
the gap.

The sampler is installed by the controller-runtime zap builder at
construction time and cannot be stripped afterwards, so the fix lives in
machinery: `ConfigureLogging` gained a `WithDisabledSampling()` option,
and the manager now passes it for every subcommand except `controller`.
The operator keeps sampling, since a reconciliation storm can repeat one
message well beyond the threshold, which is the case the sampler exists
for.

Credit to @willmurnane for the initial diagnosis in #10815, and to
@akashbhujbalwebsite for narrowing it down to the sampler mechanism in
#11109.

Closes #10815

Signed-off-by: Armando Ruocco <[email protected]>
Signed-off-by: Marco Nenciarini <[email protected]>
Co-authored-by: Marco Nenciarini <[email protected]>
(cherry picked from commit bf07333)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-requested ◀️ This pull request should be backported to all supported releases bug 🐛 Something isn't working ok to merge 👌 This PR can be merged release-1.28 release-1.30 security 👮 size:M This PR changes 30-99 lines, ignoring generated files.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

[Bug]: PG audit logs are dropped

3 participants