Skip to content

fix: Request Id was empty whehn audit logs were disabled +remove redundant request ID logic from audit log middleware #101

Merged
SantiagoDePolonia merged 1 commit into
mainfrom
cleanup/remove-redundant-request-id-logic
Feb 25, 2026
Merged

fix: Request Id was empty whehn audit logs were disabled +remove redundant request ID logic from audit log middleware #101
SantiagoDePolonia merged 1 commit into
mainfrom
cleanup/remove-redundant-request-id-logic

Conversation

@SantiagoDePolonia

@SantiagoDePolonia SantiagoDePolonia commented Feb 25, 2026

Copy link
Copy Markdown
Contributor

The request ID middleware in http.go now always runs before audit logging, making the ID generation in middleware.go dead code. Also moves the response header echo outside the if block so client-provided IDs are echoed back for correlation — matching the previous audit log behavior.

Summary by CodeRabbit

  • New Features

    • Enhanced request tracking with automatic request ID generation and propagation across the system.
  • Tests

    • Added test coverage for request ID middleware, validating both automatic ID generation and header preservation.

The request ID middleware in http.go now always runs before audit logging,
making the ID generation in middleware.go dead code. Also moves the response
header echo outside the `if` block so client-provided IDs are echoed back
for correlation — matching the previous audit log behavior.

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

coderabbitai Bot commented Feb 25, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The changes centralize request ID management by moving X-Request-ID header generation from the audit log middleware to a new global HTTP middleware layer. The audit log middleware now only reads the request ID header, assuming it's already set by the earlier middleware.

Changes

Cohort / File(s) Summary
Request ID Generation Moved to Global Middleware
internal/server/http.go
Adds new middleware function that generates a UUID-based X-Request-ID when missing and sets it on both request and response headers.
Audit Log Middleware Simplified
internal/auditlog/middleware.go
Removes request ID generation and header-setting logic; middleware now only reads the pre-existing X-Request-ID header from the request.
Request ID Middleware Tests
internal/server/http_test.go
Introduces TestRequestIDMiddleware with two test cases: generating X-Request-ID when absent and preserving existing X-Request-ID from requests.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Feature: fix audit log 405 status #76: Modifies internal/auditlog/middleware.go to adjust request ID and error handling behavior, creating direct overlap with this PR's changes to the same middleware file.

Poem

🐰 A request arrives with no ID in sight,
Global middleware generates it bright,
No more request IDs in audit logs' care,
One layer to rule them, one ID to share! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title contains a typo ('whehn' instead of 'when') and uses awkward phrasing with '+' concatenation. While it addresses the main changes (request ID handling and removing redundant logic), the presentation is unprofessional and unclear. Revise the title to: 'fix: Ensure request ID is generated before audit logging and remove redundant logic from audit middleware' for clarity and professionalism.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cleanup/remove-redundant-request-id-logic

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/auditlog/middleware.go (1)

27-30: ⚠️ Potential issue | 🟡 Minor

Update the Middleware Go doc comment to document the new precondition.

The function's behavior changed: it no longer generates a fallback request ID and now silently produces a log entry with an empty RequestID if called without the request ID middleware preceding it. The exported doc comment must reflect this per coding guidelines.

📝 Proposed doc update
-// Middleware creates an Echo middleware for audit logging.
-// It captures request metadata at the start and response metadata at the end,
-// then writes the log entry asynchronously.
+// Middleware creates an Echo middleware for audit logging.
+// It captures request metadata at the start and response metadata at the end,
+// then writes the log entry asynchronously.
+//
+// Middleware assumes the X-Request-ID header is already set on the incoming
+// request (e.g. by the request ID middleware registered in server.New).
+// If the header is absent, RequestID in the log entry will be empty.
 func Middleware(logger LoggerInterface) echo.MiddlewareFunc {

As per coding guidelines: "Maintain Go doc comments on all exported types, functions, and interfaces; update when changing public APIs or function signatures/behavior."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/auditlog/middleware.go` around lines 27 - 30, Update the exported
doc comment for the Middleware function to document the new precondition: state
that Middleware requires the request ID middleware to have run earlier in the
chain (it no longer generates a fallback RequestID), and that if called without
that middleware the produced audit entry may have an empty RequestID; reference
the function name Middleware and keep the comment concise and on the exported
function.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/server/http_test.go`:
- Around line 29-32: The current check only verifies len(got)==36 which allows
non-UUID strings; replace it by parsing the value in variable got using a UUID
parser (e.g., uuid.Parse from github.com/google/uuid or uuid.Parse from
github.com/gofrs/uuid) and assert the parse returns no error (and optionally
assert the parsed UUID's Version()==4 if you want to enforce v4). Update the
test around the existing validation (the block that checks len(got) and
references got) to call uuid.Parse(got), fail the test on parse error, and
remove or keep a shorter length check only as a fallback.

---

Outside diff comments:
In `@internal/auditlog/middleware.go`:
- Around line 27-30: Update the exported doc comment for the Middleware function
to document the new precondition: state that Middleware requires the request ID
middleware to have run earlier in the chain (it no longer generates a fallback
RequestID), and that if called without that middleware the produced audit entry
may have an empty RequestID; reference the function name Middleware and keep the
comment concise and on the exported function.

ℹ️ Review info

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a4351f and 73add09.

📒 Files selected for processing (3)
  • internal/auditlog/middleware.go
  • internal/server/http.go
  • internal/server/http_test.go

Comment on lines +29 to +32
// Validate UUID format (8-4-4-4-12 hex digits)
if len(got) != 36 {
t.Errorf("expected UUID (36 chars), got %q (%d chars)", got, len(got))
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

UUID format validation is weaker than the comment implies.

The comment on line 29 states "Validate UUID format (8-4-4-4-12 hex digits)" but the check only validates the string length (36). Any 36-character string would pass — e.g., a non-UUID. Consider using uuid.Parse to assert a well-formed UUID v4.

♻️ Proposed stronger validation
+import "github.com/google/uuid"
 
-		// Validate UUID format (8-4-4-4-12 hex digits)
-		if len(got) != 36 {
-			t.Errorf("expected UUID (36 chars), got %q (%d chars)", got, len(got))
-		}
+		// Validate well-formed UUID
+		if _, err := uuid.Parse(got); err != nil {
+			t.Errorf("expected valid UUID, got %q: %v", got, err)
+		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Validate UUID format (8-4-4-4-12 hex digits)
if len(got) != 36 {
t.Errorf("expected UUID (36 chars), got %q (%d chars)", got, len(got))
}
// Validate well-formed UUID
if _, err := uuid.Parse(got); err != nil {
t.Errorf("expected valid UUID, got %q: %v", got, err)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/server/http_test.go` around lines 29 - 32, The current check only
verifies len(got)==36 which allows non-UUID strings; replace it by parsing the
value in variable got using a UUID parser (e.g., uuid.Parse from
github.com/google/uuid or uuid.Parse from github.com/gofrs/uuid) and assert the
parse returns no error (and optionally assert the parsed UUID's Version()==4 if
you want to enforce v4). Update the test around the existing validation (the
block that checks len(got) and references got) to call uuid.Parse(got), fail the
test on parse error, and remove or keep a shorter length check only as a
fallback.

@SantiagoDePolonia SantiagoDePolonia merged commit 6b41cfa into main Feb 25, 2026
16 of 18 checks passed
@SantiagoDePolonia SantiagoDePolonia deleted the cleanup/remove-redundant-request-id-logic branch March 22, 2026 14:24
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