Skip to content

Conversation

@yottahmd
Copy link
Collaborator

@yottahmd yottahmd commented Dec 15, 2025

Issue #1478

Summary by CodeRabbit

  • Bug Fixes

    • API tokens now grant admin privileges in builtin authentication mode, enabling write, execute, and delete operations.
  • Tests

    • New test coverage verifying API token authentication in builtin mode allows admin-level create, start, and delete actions.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 15, 2025

Walkthrough

Middleware now treats successful API-token authentication as an admin identity by injecting a synthetic admin user into the request context. A new test verifies that in builtin auth mode an API token permits write/execute/delete operations while unauthenticated requests remain rejected.

Changes

Cohort / File(s) Summary
API token → synthetic admin
internal/service/frontend/auth/middleware.go
On successful API token validation, middleware injects a synthetic admin user into the request context and forwards the request with that context so downstream permission checks see admin privileges.
Tests: builtin auth + API token
internal/service/frontend/api/v2/auth_test.go
Adds TestAuth_BuiltinModeWithAPIToken_WriteExecute to assert that unauthenticated write requests are rejected, and that using an API token in builtin/JWT mode can create, start, and delete a DAG (201, 200, 204 responses).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Middleware
    participant AuthStore as API Token Verifier
    participant Handler
    participant PermissionCheck

    Client->>Middleware: HTTP POST /api/v2/dags (with API token)
    Middleware->>AuthStore: validate API token
    AuthStore-->>Middleware: token valid (metadata)
    Middleware->>Middleware: inject synthetic admin user into context
    Middleware->>Handler: forward request (with admin context)
    Handler->>PermissionCheck: check permissions (reads context)
    PermissionCheck-->>Handler: allow (admin)
    Handler-->>Client: 201 Created
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Attention areas:
    • Verify context injection is thread-safe and propagated across middlewares/handlers (no context replacement bugs).
    • Confirm downstream permission checks rely on the same context keys/shape and won't be bypassed accidentally.
    • Review security implications: ensure API-token path only grants intended admin scope and logging/auditing still records the API-token origin.

Possibly related PRs

Poem

🐇 A token tumbled in on nimble feet,
I stitched an admin cloak — quiet and neat.
Create, start, and delete with a cheerful hop,
No gates denied, I never stop.
Hooray — the rabbit guards the API's heartbeat! 🥕🔑

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly describes the main change: enabling API token authentication to perform write and execute operations, which matches the core modification in middleware.go that injects admin privileges for API token access.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 1478-token-auth

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: 0

🧹 Nitpick comments (1)
internal/service/frontend/api/v2/auth_test.go (1)

187-222: Good regression test coverage for issue #1478.

The test comprehensively validates that API tokens can perform write (create), execute (start), and delete operations in builtin auth mode, which was the core issue being fixed.

Minor suggestion: Consider adding an assertion that write operations fail without authentication, similar to the pattern used in other tests (e.g., line 165 in TestAuth_BuiltinModeWithAPIToken). This would make the test self-contained as a regression test:

+	// Without auth - write should fail
+	server.Client().Post("/api/v2/dags", api.CreateNewDAGJSONRequestBody{
+		Name: "api_token_test_dag",
+		Spec: &spec,
+	}).ExpectStatus(http.StatusUnauthorized).Send(t)
+
 	// Test write operation (create DAG) with API token - this was failing before the fix
 	server.Client().Post("/api/v2/dags", api.CreateNewDAGJSONRequestBody{
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cb83c59 and 5ba69de.

📒 Files selected for processing (2)
  • internal/service/frontend/api/v2/auth_test.go (1 hunks)
  • internal/service/frontend/auth/middleware.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*.go: Backend entrypoint in cmd/ orchestrates the scheduler and CLI; runtime, persistence, and service layers sit under internal/* (for example internal/runtime, internal/persistence)
Keep Go files gofmt/goimports clean; use tabs, PascalCase for exported symbols (SchedulerClient), lowerCamelCase for locals, and Err... names for package-level errors
Repository linting relies on golangci-lint; prefer idiomatic Go patterns, minimal global state, and structured logging helpers in internal/common

Files:

  • internal/service/frontend/api/v2/auth_test.go
  • internal/service/frontend/auth/middleware.go
**/*_test.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*_test.go: Co-locate Go tests as *_test.go; favour table-driven cases and cover failure paths
Use stretchr/testify/require and shared fixtures from internal/test instead of duplicating mocks

Files:

  • internal/service/frontend/api/v2/auth_test.go
🧬 Code graph analysis (2)
internal/service/frontend/api/v2/auth_test.go (4)
internal/test/server.go (2)
  • SetupServer (26-63)
  • Server (21-23)
internal/test/helper.go (1)
  • WithConfigMutator (72-76)
internal/common/config/config.go (2)
  • Auth (144-150)
  • AuthModeBuiltin (138-138)
api/v2/api.gen.go (2)
  • CreateNewDAGJSONRequestBody (1612-1612)
  • ExecuteDAGJSONRequestBody (1627-1627)
internal/service/frontend/auth/middleware.go (4)
api/v2/api.gen.go (1)
  • User (991-1006)
internal/auth/role.go (2)
  • Role (16-16)
  • RoleAdmin (20-20)
internal/auth/context.go (1)
  • WithUser (17-19)
internal/core/execution/context.go (1)
  • WithContext (241-243)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Test on ubuntu-latest
🔇 Additional comments (1)
internal/service/frontend/auth/middleware.go (1)

89-98: LGTM - Synthetic admin user injection for API token auth.

The approach correctly injects an admin user context so that downstream permission checks (requireWrite, requireExecute, requireAdmin) function properly. The hardcoded "api-token" identifier provides clear audit trail for API token-authenticated requests.

One consideration: API tokens now unconditionally grant full admin privileges. If finer-grained API token permissions are needed in the future (e.g., read-only tokens), this design would need revisiting. For now, this aligns with the PR objective.

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: 0

🧹 Nitpick comments (1)
internal/service/frontend/api/v2/auth_test.go (1)

187-228: Excellent regression test for issue #1478.

The test properly validates that API tokens can perform write (create), execute (start), and delete operations when builtin auth mode is enabled. The setup is correct, the test flow is logical, and it aligns with existing test patterns in the file.


Optional: Consider testing unauthorized access for start/delete operations.

For consistency and completeness, you could add unauthorized checks before the start and delete operations (similar to lines 207-211 for create). While the middleware applies uniformly to all endpoints and this may seem redundant, it would make the test coverage more explicit and self-documenting.

Example:

 	}).WithBearerToken("my-api-token").ExpectStatus(http.StatusCreated).Send(t)
 
+	// Without auth - execute should fail
+	server.Client().Post("/api/v2/dags/api_token_test_dag/start", api.ExecuteDAGJSONRequestBody{}).
+		ExpectStatus(http.StatusUnauthorized).Send(t)
+
 	// Test execute operation (start DAG) with API token - this was also failing
 	server.Client().Post("/api/v2/dags/api_token_test_dag/start", api.ExecuteDAGJSONRequestBody{}).
 		WithBearerToken("my-api-token").
 		ExpectStatus(http.StatusOK).Send(t)
 
+	// Without auth - delete should fail
+	server.Client().Delete("/api/v2/dags/api_token_test_dag").
+		ExpectStatus(http.StatusUnauthorized).Send(t)
+
 	// Test delete operation with API token
 	server.Client().Delete("/api/v2/dags/api_token_test_dag").
 		WithBearerToken("my-api-token").
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5ba69de and 9c2c138.

📒 Files selected for processing (1)
  • internal/service/frontend/api/v2/auth_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*.go: Backend entrypoint in cmd/ orchestrates the scheduler and CLI; runtime, persistence, and service layers sit under internal/* (for example internal/runtime, internal/persistence)
Keep Go files gofmt/goimports clean; use tabs, PascalCase for exported symbols (SchedulerClient), lowerCamelCase for locals, and Err... names for package-level errors
Repository linting relies on golangci-lint; prefer idiomatic Go patterns, minimal global state, and structured logging helpers in internal/common

Files:

  • internal/service/frontend/api/v2/auth_test.go
**/*_test.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*_test.go: Co-locate Go tests as *_test.go; favour table-driven cases and cover failure paths
Use stretchr/testify/require and shared fixtures from internal/test instead of duplicating mocks

Files:

  • internal/service/frontend/api/v2/auth_test.go
🧬 Code graph analysis (1)
internal/service/frontend/api/v2/auth_test.go (4)
internal/test/server.go (2)
  • SetupServer (26-63)
  • Server (21-23)
internal/service/frontend/server.go (1)
  • Server (40-46)
internal/common/config/config.go (2)
  • Auth (144-150)
  • AuthModeBuiltin (138-138)
api/v2/api.gen.go (2)
  • CreateNewDAGJSONRequestBody (1612-1612)
  • ExecuteDAGJSONRequestBody (1627-1627)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Test on ubuntu-latest

@yottahmd yottahmd merged commit 5d6e50d into main Dec 15, 2025
5 checks passed
@yottahmd yottahmd deleted the 1478-token-auth branch December 15, 2025 11:11
@codecov
Copy link

codecov bot commented Dec 15, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.87%. Comparing base (be3e71b) to head (9c2c138).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1486      +/-   ##
==========================================
- Coverage   59.89%   59.87%   -0.02%     
==========================================
  Files         195      195              
  Lines       21918    21918              
==========================================
- Hits        13127    13124       -3     
- Misses       7385     7388       +3     
  Partials     1406     1406              

see 2 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 cb83c59...9c2c138. 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.

2 participants