Repository navigation
🐛 fix(audit): suppress security scan lifecycle churn - #520
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important Review skippedNo new commits to review since the last review. ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughAdds in-memory, TTL-based container lifecycle audit state keyed by derived container identity. Lifecycle additions seed state, updates record audits only when normalized signatures change, and removals clear cached state. The implementation supports scoped identities, compose siblings, stale-state pruning, cache clearing, and fail-open behavior without stable identity. Tests now register lifecycle handlers and cover deduplication, transitions, policy normalization, cleanup, fleet size, and identity handling. 🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
app/event/audit-subscriptions.ts (1)
376-412: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winCommit changed lifecycle state only after the audit insert succeeds.
Both addition and changed-update paths advance the cache before
insertAudit. If insertion throws, a later identical update can be suppressed even though no audit row was persisted.Proposed ordering
- setContainerLifecycleAuditState(identity, signature); - return { record: previousState?.signature !== signature, identity }; + if (previousState?.signature === signature) { + setContainerLifecycleAuditState(identity, signature); + return { record: false, identity }; + } + return { record: true, identity, signature };auditStore.insertAudit({ ... }); + if (lifecycleUpdate.identity && lifecycleUpdate.signature) { + setContainerLifecycleAuditState( + lifecycleUpdate.identity, + lifecycleUpdate.signature, + ); + } getAuditCounter()?.inc({ action: 'container-update' });Move the
container-addedcache seed after its successful insertion as well.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/event/audit-subscriptions.ts` around lines 376 - 412, Move the setContainerLifecycleAuditState call in the container-added registrar so it runs only after auditStore.insertAudit completes successfully, matching the container-updated path’s persistence ordering. Keep the identity-key calculation and audit payload unchanged, and ensure failed inserts do not advance lifecycle cache state.
🧹 Nitpick comments (1)
app/event/audit-subscriptions.test.ts (1)
612-949: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated payload builders across ~9 test cases.
Nearly identical
baselineobject literals (id/name/watcher/agent/status/image/result) and near-duplicate local factories (updateFor,siblingFor) are redefined in almost every test (e.g. Lines 614-623, 661-669, 697-705, 724-735, 796-806, 819-829, 850-860, 880-889, 907-915, 931-939). A single shared builder would cut this down significantly and reduce drift risk across scenarios.♻️ Suggested shared helper
function makeLifecyclePayload( overrides: Partial<ContainerLifecycleEventPayload> = {}, ): ContainerLifecycleEventPayload { return { id: 'container-1', name: 'web', watcher: 'docker', agent: 'edge-a', status: 'running', image: { name: 'library/nginx' }, result: { tag: '1.27.0', digest: 'sha256:one' }, ...overrides, } as unknown as ContainerLifecycleEventPayload; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/event/audit-subscriptions.test.ts` around lines 612 - 949, Introduce a shared makeLifecyclePayload helper for the repeated default lifecycle fields, then replace the local baseline objects and simple updateFor/siblingFor builders in the listed tests with helper calls and targeted overrides. Preserve each test’s unique identity, compose, status, security, policy, and other scenario-specific values while removing duplicated payload construction.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@app/event/audit-subscriptions.ts`:
- Around line 376-412: Move the setContainerLifecycleAuditState call in the
container-added registrar so it runs only after auditStore.insertAudit completes
successfully, matching the container-updated path’s persistence ordering. Keep
the identity-key calculation and audit payload unchanged, and ensure failed
inserts do not advance lifecycle cache state.
---
Nitpick comments:
In `@app/event/audit-subscriptions.test.ts`:
- Around line 612-949: Introduce a shared makeLifecyclePayload helper for the
repeated default lifecycle fields, then replace the local baseline objects and
simple updateFor/siblingFor builders in the listed tests with helper calls and
targeted overrides. Preserve each test’s unique identity, compose, status,
security, policy, and other scenario-specific values while removing duplicated
payload construction.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 029e0be9-dee4-4ea2-9e67-883f1bce0c66
⛔ Files ignored due to path filters (1)
CHANGELOG.mdis excluded by!CHANGELOG.md
📒 Files selected for processing (2)
app/event/audit-subscriptions.test.tsapp/event/audit-subscriptions.ts
c5e5315 to
a11e763
Compare
|
Addressed both findings in a11e763:
Validation: 312 focused integration tests, backend build, enforced pre-push gate, 100% app/UI coverage, and app/UI builds all pass. The isolated DinD operational smoke also held audits at 7 -> 7 and container-update at 0 across two on-demand refreshes and two scheduled cycles while scan/SBOM state advanced; no host socket was exposed and all smoke resources were removed. @coderabbitai review |
|
✅ Action performedReview finished.
|
## What Fixes the bug that failed the v1.6.0-rc.1 24-hour store-size acceptance run (Discussion #321 gate), plus two adjacent gaps found during the same root-cause investigation. 1. **Slow-path rebuild digest stickiness** (`docker-image-details-orchestration.ts`). A container whose stored doc carries `.error` is rebuilt from scratch on the next cycle; the rebuild reset `image.digest.value` to the raw local repo digest, discarding the registry-reconciled manifest digest that `handleDigestWatch` recorded on the last successful cycle. The rebuild now preserves the stored value unless the repo digest genuinely changed (a real re-pull) — the same stickiness the fast path (`refreshStoredContainerImageFields`) already applies. 2. **`updatePolicyOverrides` preservation** (same file). The same rebuild ran `applyDockerDeclarativeUpdatePolicy` on a fresh object, stamping `updatePolicyOverrides: {}`; since the incoming doc then *has* the key, the store merge keeps the empty object — silently destroying user snoozes/skip-tags for any container that ever had a watch error. Overrides are now seeded from the stored doc before declarative policy is re-applied. 3. **Bounded transient-network retry** (`http-retry.ts`). `withRetry` threw all response-less errors immediately, so registry timeouts/resets never retried (only 429/503 did). Response-less errors with a transient code (`ECONNABORTED`, `ETIMEDOUT`, `ECONNRESET`, `EAI_AGAIN`) now retry up to `maxNetworkRetries` (default 2, also capped by `maxRetries`) with exponential backoff. ## Why (the incident) During run #1 of the 24h acceptance, Docker Hub tarpitted requests intermittently. The failure margin was exactly ten audit rows written at 12:10:47: back-to-back errored cycles sent the redis fleet through the slow-path rebuild, which flipped `image.digest.value` from the reconciled `cd5f3…` to the raw `9d317…`. `image.digest.value` is not among the store-level change detector's inputs, so the corrupting write emitted nothing — but it changed the security scheduler's scan-group key (keyed purely on `image.digest.value`), forcing a fresh Trivy scan whose store write emitted, and the event payload carried the flipped digest into the lifecycle audit signature (#520), producing one spurious `container-update` row per container sharing the image. Live-doc corroboration: `security.sbom.subjectDigest` still held `cd5f3…` while `image.digest.value` read `9d317…`. The retry fix reduces how often consecutive cycles error at all; the digest fix removes the corruption for outages that outlast the retry budget. ## Considered and deferred (will be filed as issues at rc.1 cut) - The fast path's repair branch has the same blind `value` reset, but only runs on already-broken image references — out of scope here. - Errored docs repeat the full slow enumeration every cycle (2 extra Docker inspects per container per cron) — perf only. - Preserving `result` across error writes — must sequence *after* this fix (a stale `result.digest` against a freshly-corrected `image.digest.value` could flip `updateAvailable` spuriously). ## Tests - Regression tests seed the real-lifecycle state the two earlier forensic harnesses missed (stored `value` ≠ raw local digest), assert the slow-path rebuild preserves digest value + overrides, and pin the controls: a genuine re-pull still resets, local images still work, brand-new containers unaffected. - `withRetry` network-retry branches fully covered (retry-then-succeed, budget exhaustion, `maxRetries` cap, non-retryable/missing/non-string codes, empty code list, `retryDelayMs` override). - Full app + UI gates green at 100% coverage. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Changelog - 🐛 Fixed watcher rebuilds preserving stored reconciled `image.digest.value` and `updatePolicyOverrides` to prevent state corruption after error-triggered rebuilds. - ✨ Added bounded retries for response-less transient registry network errors in `withRetry`, using exponential backoff (or `retryDelayMs` override) and supporting retryable error `.code`s (e.g., `ECONNABORTED`, `ETIMEDOUT`, `ECONNRESET`, `EAI_AGAIN`). - ✨ Ensured network retries are budgeted independently from HTTP-status/Axios retries (via a dedicated network retry counter), while `maxRetries` still caps overall attempts. - 🔧 Extended `withRetry` options with `retryableNetworkErrorCodes?: string[]` and `maxNetworkRetries?: number`. - ✨ Added/expanded regression tests for digest/policy preservation behavior (including genuine re-pulls, local image scenarios, and new containers) and for retry behavior across retryable/non-retryable network errors and retry-delay overrides. - Verify digest reconciliation logic correctly distinguishes “repo digest unchanged” (preserve) vs “repo digest changed” (update) across missing/undefined and local/repull scenarios. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Summary
Root cause
Scheduled security scans update security.scan.scannedAt. The store correctly emits dd:container-updated so the UI refreshes, but the audit subscriber treated every event as a lifecycle transition. A 50-container scan therefore wrote 50 unchanged container-update audit rows per cycle and broke the #321 store-size acceptance bound.
Verification
Acceptance impact
This addresses the audit-growth failure found in the superseded #321 operational run. The final 24-hour NAS acceptance remains intentionally last, after all v1.6 code is frozen.
✨ Added
makeLifecyclePayload).🔧 Changed
container-updateaudit insertion is now conditional: recorded only when lifecycle/image/update/health/error/update-policy/policy-related transitions actually change, suppressing “security-only” scheduled scan refresh churn.container-updateddetails population was adjusted to avoid unnecessary/incorrect prior unconditional fields; status-derived transitions are tracked via signature comparison instead.🐛 Fixed
🗑️ Removed
container-updateaudit insertion behavior that caused audit churn.🔒 Security
Keeps security scan persistence/SBOM-related state advancing without generating noisy generic audit rows during scheduled refreshes.
Confirm lifecycle cache identity derivation is consistent at all production call sites (and that the legacy fallback cannot merge unrelated containers).
Verify persistence-ordering fix remains correct under retries/failure injection (no lifecycle advancement on failed audit writes).
Validate TTL pruning and container-removal cleanup don’t accidentally evict still-relevant lifecycle state for sibling/compose scenarios.
Ensure dedupe behavior “fails open” only when identity truly can’t be derived, without reintroducing churn.