Skip to content

Comments

refactor: audit log record#1654

Merged
yottahmd merged 5 commits intomainfrom
audit-log-record
Feb 12, 2026
Merged

refactor: audit log record#1654
yottahmd merged 5 commits intomainfrom
audit-log-record

Conversation

@yottahmd
Copy link
Collaborator

@yottahmd yottahmd commented Feb 12, 2026

Summary by CodeRabbit

  • New Features

    • Added audit logging for file cleanup operations, capturing retention details and purged file information.
    • Introduced "system" audit category for tracking system-level events.
  • Refactor

    • Consolidated audit logging across API operations for agents, API keys, authentication, DAG operations, user management, and webhooks into a unified logging approach.
    • Enhanced audit entry creation with improved user data extraction and error handling.

@coderabbitai
Copy link

coderabbitai bot commented Feb 12, 2026

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR introduces an audit callback mechanism to the file cleaner, adds a new CategorySystem audit category, and refactors audit logging across API endpoints to use a unified logAudit method instead of specialized audit logging helpers.

Changes

Cohort / File(s) Summary
File Cleaner Audit Integration
internal/persis/fileaudit/cleaner.go, internal/persis/fileaudit/cleaner_test.go, internal/persis/fileaudit/store.go
Introduces appendFn callback to record cleanup events in audit log. New appendFn type stores function for logging purged files with details (purged_from, purged_to, files_removed, retention_days). Constructor updated to accept and initialize callback. Tests verify audit entry creation when files are purged and no entry when nothing purged.
Audit Category Expansion
internal/service/audit/entry.go
Adds CategorySystem constant ("system") to the existing audit category enum, expanding observable categories from 7 to 8 types.
API Audit Logging Refactoring
internal/service/frontend/api/v1/api.go
Renames logAuditEntry to logAudit with enhanced functionality: extracts userID and username from context (permitting empty values), marshals details map with fallback to "{}" on error, logs failures via slog.Warn instead of silently failing. Updated imports include log/slog.
Agent and DAG Management Audit Updates
internal/service/frontend/api/v1/agent_config.go, internal/service/frontend/api/v1/agent_models.go, internal/service/frontend/api/v1/dags.go, internal/service/frontend/api/v1/dagruns.go
Consolidates audit logging: removes specialized helpers (logDAGAudit, logDAGRunAudit), replaces calls with logAudit using appropriate categories and detail maps. Preserves functional behavior while centralizing audit logging path.
Additional API Audit Consolidation
internal/service/frontend/api/v1/apikeys.go, internal/service/frontend/api/v1/auth.go, internal/service/frontend/api/v1/sync.go, internal/service/frontend/api/v1/users.go, internal/service/frontend/api/v1/webhooks.go
Replaces custom audit logging implementations with centralized logAudit calls. Removes JSON marshaling dependencies and specialized helpers (logWebhookAudit). Details now passed as maps directly to logAudit with appropriate categories.

Sequence Diagram

sequenceDiagram
    participant Ticker as File Cleaner<br/>(Ticker Loop)
    participant Purge as purgeExpiredFiles()
    participant AuditLog as appendFn Callback
    participant AuditSvc as Audit Service

    Ticker->>Purge: Periodically trigger purge
    Purge->>Purge: Scan expired files
    alt Files Found
        Purge->>Purge: Delete files, collect purgedDates
        Purge->>AuditLog: Call appendFn with details<br/>(purged_from, purged_to,<br/>files_removed, retention_days)
        AuditLog->>AuditSvc: audit.NewEntry() + Log()
        AuditSvc-->>AuditLog: Audit entry recorded
    else No Files
        Purge-->>Ticker: Return (no audit call)
    end
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly Related PRs

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'refactor: audit log record' is vague and does not clearly convey the main changes. The PR involves significant audit logging infrastructure refactoring including a new cleaner mechanism, centralized logAudit consolidation, new audit categories, and widespread audit call refactoring across multiple API files. Use a more specific title that captures the main refactoring scope, such as: 'refactor: consolidate audit logging with centralized logAudit and file cleanup auditing' or 'refactor: unify audit logging implementation and add audit cleanup tracking'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch audit-log-record

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@internal/service/frontend/api/v1/auth.go`:
- Line 128: The password-change audit call a.logAudit(ctx, audit.CategoryUser,
"password_change", nil) may omit the user's IP like the login case; update the
password-change path to include IP information by extracting the client IP from
the request context (use the same helper used for login, e.g. getIPFromContext
or requestIPFromCtx) and pass it into logAudit (or include it in the audit
payload) so the logAudit function receives the IP—ensure you update the
a.logAudit invocation in auth.go and, if necessary, the logAudit
signature/handling to accept or read the IP field.

In `@internal/service/frontend/api/v1/users.go`:
- Around line 199-206: The audit details omit the is_disabled change; update the
changes map before calling a.logAudit by checking the request/update input's
disable flag (e.g., input.IsDisabled or the field used to represent is_disabled)
and, when non-nil, add changes["is_disabled"] = *input.IsDisabled (or the
appropriate dereference/type conversion) so the a.logAudit(..., changes) call
includes the disabled/enabled state alongside username and role.
🧹 Nitpick comments (5)
internal/service/frontend/api/v1/sync.go (1)

297-297: Inconsistent details map type: map[string]string vs map[string]any.

All other logAudit call sites in this file (and across the PR) pass map[string]any for the details argument. This call passes map[string]string. While it compiles (the parameter is likely typed as any), using a consistent type reduces confusion and avoids issues if logAudit ever adds type-specific handling.

Suggested fix
-	a.logAudit(ctx, audit.CategoryGitSync, "sync_discard", map[string]string{"dag_id": req.Name})
+	a.logAudit(ctx, audit.CategoryGitSync, "sync_discard", map[string]any{"dag_id": req.Name})
internal/service/frontend/api/v1/webhooks.go (1)

121-124: Minor inconsistency: map[string]string used here while map[string]any is used elsewhere.

Same observation as in sync.go — these three call sites use map[string]string while Line 233 in this file and the vast majority of other logAudit calls across the PR use map[string]any. Consider aligning for consistency.

Also applies to: 160-164, 194-197

internal/service/frontend/api/v1/apikeys.go (1)

92-96: Inconsistent detail map types across API key operations.

CreateAPIKey and DeleteAPIKey use map[string]string, while UpdateAPIKey uses map[string]any. Although json.Marshal handles both, using a consistent type improves readability. Consider using map[string]any everywhere for uniformity (as done in users.go and dags.go).

internal/persis/fileaudit/cleaner_test.go (1)

155-155: Note: newCleaner starts a background goroutine.

newCleaner(dir, 7, nil) launches go c.run() which calls purgeExpiredFiles() immediately before the test calls c.stop(). Since this test is specifically about idempotent stop, it works — but there's a potential race where the goroutine's initial purgeExpiredFiles() runs concurrently. In practice this is benign (empty temp dir), but if this test becomes flaky, consider using newTestCleaner (which doesn't start the goroutine) plus explicit c.stop() / double-close testing on stopCh.

internal/persis/fileaudit/cleaner.go (1)

122-135: Silently discarded json.Marshal error.

Line 123 discards the error from json.Marshal. While practically safe here (basic types only), the centralized logAudit in api.go logs a warning on marshal failure. Consider logging for consistency, or add a brief comment explaining why the error is safe to ignore.

@yottahmd yottahmd merged commit f48ecc0 into main Feb 12, 2026
5 checks passed
@yottahmd yottahmd deleted the audit-log-record branch February 12, 2026 13:29
@codecov
Copy link

codecov bot commented Feb 12, 2026

Codecov Report

❌ Patch coverage is 65.21739% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.20%. Comparing base (5c7afbb) to head (d375610).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/persis/fileaudit/cleaner.go 63.63% 5 Missing and 3 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1654      +/-   ##
==========================================
- Coverage   70.21%   70.20%   -0.02%     
==========================================
  Files         344      344              
  Lines       38315    38332      +17     
==========================================
+ Hits        26902    26910       +8     
- Misses       9275     9281       +6     
- Partials     2138     2141       +3     
Files with missing lines Coverage Δ
internal/persis/fileaudit/store.go 72.89% <100.00%> (ø)
internal/service/audit/entry.go 100.00% <ø> (ø)
internal/persis/fileaudit/cleaner.go 71.62% <63.63%> (-5.58%) ⬇️

... and 10 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 5c7afbb...d375610. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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