Skip to content

UN-3638 [TEST] Cover the Platform API key branch of CustomAuthMiddleware - #2223

Merged
chandrasekharan-zipstack merged 1 commit into
mainfrom
test/platform-key-middleware
Jul 31, 2026
Merged

UN-3638 [TEST] Cover the Platform API key branch of CustomAuthMiddleware#2223
chandrasekharan-zipstack merged 1 commit into
mainfrom
test/platform-key-middleware

Conversation

@chandrasekharan-zipstack

Copy link
Copy Markdown
Contributor

What

Adds request-level tests for the Platform API key (Bearer) branch of CustomAuthMiddlewarebackend/account_v2/custom_auth_middleware.py:70-146.

Why

This branch is the only way a caller authenticates without a session, and it carries authorization decisions that the views behind it do not repeat:

  • the key must belong to the organization named in the URL (403 otherwise)
  • the key's permission tier must allow the HTTP method (403 otherwise)
  • Bearer requests are opted out of CSRF (request.csrf_processing_done = True)

Both 403s are tenant/privilege boundaries, and neither had a single test — platform_api/ had no tests/ directory at all. The tier logic (UN-3405, full_access for DELETE) and the rotation permission gate (UN-3586) both landed untested.

Note api-deployment-auth does not cover this despite the name: it tests api_v2.APIKey via the validate_api_key decorator with APIRequestFactory (no middleware), and /deployment/ is whitelisted so the middleware returns before reaching the Bearer branch.

How

Real middleware chain (trimmed from production, relative order preserved) plus a throwaway DRF view, so OrganizationMiddleware populates request.organization_id from the URL exactly as it does in production. MIDDLEWARE is pinned explicitly rather than inherited, because the cloud test settings drop CustomAuthMiddleware.

12 tests: malformed/unknown/inactive key, cross-org key, missing service account, each permission tier against an allowed and a disallowed method, request binding, and the CSRF opt-out (via APIClient(enforce_csrf_checks=True)).

Incidental finding

The "unrecognized permission tier" guard in the middleware is unreachable: a platform_api_key_permission_valid CHECK constraint rejects the write first. The test asserts the constraint instead of the dead branch.

🤖 Generated with Claude Code

https://claude.ai/code/session_01TgRHmXGEFLbPZTG7ewyvhM

The Bearer branch decides organization scoping and permission tier vs HTTP
method before any view runs, and had no test in either tree. Drives a real
middleware chain so those decisions are exercised where they are made.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TgRHmXGEFLbPZTG7ewyvhM
@sonarqubecloud

Copy link
Copy Markdown

@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds request-level coverage for Platform API key authentication through the production-ordered middleware path.

  • Covers malformed, unknown, inactive, cross-organization, and service-account-less keys.
  • Exercises permission tiers against allowed and denied HTTP methods.
  • Verifies service-account/key request binding, the database permission constraint, and Bearer-request CSRF opt-out.

Confidence Score: 5/5

The PR appears safe to merge, with the new tests covering the intended Platform API key middleware behavior without changing production code.

The added middleware test configuration preserves the relevant production ordering, exercises concrete authentication and authorization outcomes, and safely contains the expected database constraint error within a nested transaction.

Important Files Changed

Filename Overview
backend/platform_api/tests/test_platform_key_middleware.py Adds focused request-level tests for Platform API key validation, tenant and permission boundaries, request binding, and CSRF handling; no actionable defect was identified.
backend/platform_api/tests/init.py Marks the new platform_api test directory as a Python package without introducing runtime behavior.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
    Request[Bearer request with organization URL] --> Org[OrganizationMiddleware resolves organization]
    Org --> Auth[CustomAuthMiddleware validates Platform API key]
    Auth --> KeyChecks{Key valid and active?}
    KeyChecks -->|No| Unauthorized[401 response]
    KeyChecks -->|Yes| OrgCheck{Key belongs to organization?}
    OrgCheck -->|No| ForbiddenOrg[403 response]
    OrgCheck -->|Yes| TierCheck{Permission allows HTTP method?}
    TierCheck -->|No| ForbiddenMethod[403 response]
    TierCheck -->|Yes| Bind[Bind service-account user and key; opt out of CSRF]
    Bind --> View[Test echo view]
Loading

Reviews (1): Last reviewed commit: "[TEST] Cover the Platform API key branch..." | Re-trigger Greptile

@chandrasekharan-zipstack chandrasekharan-zipstack changed the title [TEST] Cover the Platform API key branch of CustomAuthMiddleware UN-3638 [TEST] Cover the Platform API key branch of CustomAuthMiddleware Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Tests
    • Added comprehensive coverage for platform API-key authentication.
    • Verified rejection of malformed, unknown, inactive, cross-organization, and improperly configured keys.
    • Confirmed permission-based method restrictions and successful request authentication.
    • Verified that authenticated bearer requests bypass CSRF checks.

Walkthrough

Added request-level tests for CustomAuthMiddleware. The tests cover API-key rejection, permission-tier method restrictions, successful request binding, unsupported permission persistence, and CSRF bypass.

Changes

Platform API-key authentication

Layer / File(s) Summary
Request test harness
backend/platform_api/tests/test_platform_key_middleware.py
Adds the endpoint, URL configuration, middleware configuration, fixtures, and request helpers used by the middleware tests.
Authentication rejection cases
backend/platform_api/tests/test_platform_key_middleware.py
Tests malformed, unknown, inactive, cross-organization, and service-account-less keys. It also checks that unsupported permission tiers cannot be persisted.
Permission and success paths
backend/platform_api/tests/test_platform_key_middleware.py
Tests method restrictions by permission tier, successful service-account and API-key binding, and CSRF bypass for accepted bearer credentials.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change, motivation, implementation, and testing scope, but omits several required template sections. Add the break-risk, database migrations, environment configuration, relevant docs, related issues, dependency versions, testing notes, screenshots, and checklist sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title clearly identifies the issue, test scope, and CustomAuthMiddleware Platform API key branch covered by the changes.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test/platform-key-middleware

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.

@github-actions

Copy link
Copy Markdown
Contributor

Unstract test results

Per-group results

Status Group Tier Passed Failed Errors Skipped Duration (s)
e2e-api-deployment e2e 3 0 0 0 20.7
e2e-coowners e2e 1 0 0 0 1.7
e2e-etl e2e 1 0 0 0 4.2
e2e-login e2e 2 0 0 0 1.2
e2e-prompt-studio e2e 1 0 0 0 4.4
e2e-smoke e2e 2 0 0 0 1.0
e2e-workflow e2e 1 0 0 0 16.6
integration-backend integration 205 0 0 26 40.6
integration-connectors integration 1 0 0 7 8.0
integration-workers integration 140 0 0 1 48.7
unit-backend unit 277 0 0 1 36.9
unit-connectors unit 63 0 0 0 10.1
unit-core unit 33 0 0 0 1.4
unit-platform-service unit 15 0 0 0 2.7
unit-rig unit 109 0 0 0 5.5
unit-sdk1 unit 480 0 0 0 23.8
unit-workers unit 1312 0 0 0 96.6
TOTAL 2646 0 0 35 324.1

Critical paths

⚠️ Critical paths not yet covered

  • workflow-execution-fan-out — Multi-file workflow execution fans out to file-processing workers and rejoins. (declared coverage: no groups declared)
✅ Covered critical paths
  • auth-login — covered by e2e-login
  • adapter-register-llm — covered by integration-backend
  • workflow-author — covered by integration-backend
  • co-owner-manage — covered by integration-backend, e2e-coowners
  • workflow-create-execute — covered by e2e-workflow
  • api-deployment-provision — covered by integration-backend
  • api-deployment-auth — covered by integration-backend
  • api-deployment-run — covered by e2e-api-deployment
  • prompt-studio-author — covered by integration-backend
  • prompt-studio-fetch-response — covered by e2e-prompt-studio
  • connector-register-test — covered by integration-backend
  • pipeline-etl-execute — covered by e2e-etl
  • usage-aggregate-read — covered by integration-backend
  • usage-token-tracking — covered by e2e-api-deployment
  • callback-result-delivery — covered by e2e-api-deployment

@chandrasekharan-zipstack
chandrasekharan-zipstack merged commit 1c737df into main Jul 31, 2026
14 of 16 checks passed
@chandrasekharan-zipstack
chandrasekharan-zipstack deleted the test/platform-key-middleware branch July 31, 2026 07:54
Deepak-Kesavan added a commit that referenced this pull request Aug 3, 2026
Picks up ResourceTable (frontend/src/components/widgets/resource-table/),
which cloud main's agentic-prompt-studio plugin imports — without it the
Cloud Frontend image fails to build:

  Could not resolve "../../../components/widgets/resource-table/ResourceTable"
  from "src/plugins/agentic-prompt-studio/pages/Projects.jsx"

Also brings in #2223, which covers the Platform API key branch of
CustomAuthMiddleware — the auth path the platform MCP server relies on.
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