Skip to content

fix(api): propagate authenticated principal through handlers - #1476

Merged
cristim merged 3 commits into
mainfrom
fix/864-auth-principal-followup
Jul 21, 2026
Merged

cristim merged 3 commits into
mainfrom
fix/864-auth-principal-followup

Conversation

@cristim

@cristim cristim commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Summary

  • propagate the authenticated principal from request validation through router dispatch
  • reuse resolved API-key and bearer identities in handlers instead of validating twice
  • preserve session-only behavior and API-key permission precedence for mixed credentials
  • extend full request-path regression coverage for admin keys, user keys, and bearer sessions

Why

Follow-up to #194 and merged PR #864. The merged refactor returned a Principal, but the production request pipeline still discarded it before handler dispatch. That caused duplicate credential validation and inconsistent mixed-credential behavior.

Refs #194

Verification

  • go test -race ./internal/api -run 'HandleRequest|RouterAuthUser|RequireAuth|ValidateSecurity' -count=1
  • go test -race ./internal/api -count=1
  • pre-commit hooks, including vet, complexity, gosec, Trivy, and secret checks

Summary by CodeRabbit

  • Security & Authentication

    • Improved handling of sessions, user API keys, and admin API keys across protected requests.
    • Prevented conflicting credentials from unintentionally bypassing access restrictions.
    • Reduced repeated credential validation while preserving authorization checks.
    • Applied CSRF protection more consistently, with appropriate exceptions for API-key requests.
  • Bug Fixes

    • Improved unauthorized and forbidden responses for invalid sessions or insufficient permissions.
    • Ensured protected requests stop processing when authentication or validation fails.

cristim added 3 commits July 20, 2026 22:54
Attach the resolved AuthUser principal to the request context before
dispatch and reuse it in the current-user permissions path. Cover admin,
user API key, and session credentials without duplicate validation.
The authentication follow-up propagates the resolved principal through the
request context. Match that enriched context in the existing end-to-end
dashboard test while preserving its business argument assertions.
HandleRequest now propagates the authenticated principal through context.
Keep end-to-end mocks strict on business arguments while accepting the
enriched request context passed to downstream services.
@cristim cristim added triaged Item has been triaged priority/p3 Polish / idea / may never ship severity/low Minor harm urgency/eventually No deadline impact/internal Team-internal only effort/s Hours type/chore Maintenance / non-user-visible labels Jul 20, 2026
@cristim

cristim commented Jul 20, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

No new commits to review since the last review.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c14db4a8-bd2b-4d0a-ac3d-9eadc5037c56

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

Authentication principals are stored in request context and reused across validation, routing, CSRF checks, permission checks, and handlers. Session and API-key authentication paths are centralized, with tests covering single validation and mixed credentials.

Changes

Principal authentication flow

Layer / File(s) Summary
Resolve and propagate principals
internal/api/middleware.go, internal/api/router.go, internal/api/router_authuser_test.go
Principals are resolved, merged for mixed credentials, stored in request context, reused by route authentication and CSRF checks, and validated through router tests.
Thread context through validation and permissions
internal/api/handler.go
Request validation returns an updated context, and permission checks reuse contextual principals with centralized session validation and authorization responses.
Adopt centralized session requirements
internal/api/handler_auth.go, internal/api/handler_purchases.go, internal/api/handler_test.go
Authentication and purchase handlers use centralized session-principal helpers, while handler expectations accept propagated contexts.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HandleRequest
  participant Middleware
  participant Router
  participant Handler
  Client->>HandleRequest: API request with credentials
  HandleRequest->>Middleware: authenticatePrincipal
  Middleware-->>HandleRequest: contextual Principal
  HandleRequest->>Router: route with updated context
  Router->>Handler: invoke authenticated handler
  Handler->>Middleware: requireSessionPrincipal or requirePermission
  Middleware-->>Handler: session or authorization result
Loading

Possibly related PRs

  • LeanerCloud/CUDly#726: Related changes move mutating-route authorization toward handler-level permission checks.
  • LeanerCloud/CUDly#864: Related authentication refactoring resolves and reuses request principals.
  • LeanerCloud/CUDly#1454: Related permission-flow changes handle API-key-specific authorization through requirePermission.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: propagating the authenticated principal through API handlers.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/864-auth-principal-followup

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

@cristim
cristim merged commit 427e81b into main Jul 21, 2026
19 checks passed
@cristim
cristim deleted the fix/864-auth-principal-followup branch July 27, 2026 11:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/s Hours impact/internal Team-internal only priority/p3 Polish / idea / may never ship severity/low Minor harm triaged Item has been triaged type/chore Maintenance / non-user-visible urgency/eventually No deadline

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant