plane icon indicating copy to clipboard operation
plane copied to clipboard

[feature]: Scoped API tokens (read-only / no delete) and a per-token rate limit

Open pitupi opened this issue 3 weeks ago • 4 comments

Is there an existing issue for this?

Searched on 2026-11-07 for api token scope / read-only token / api key permissions: no match (closest: #9155, an AI-assistant proposal that does not cover token scopes).

Summary

An API key can do everything its user can do through the API, including DELETE of work items, comments and projects. The APIToken model (apps/api/plane/db/models/api.py) has label, is_active, expired_at, user_type but no scope. The rate limit is a single global API_KEY_RATE_LIMIT (default 60/minute) applied per key, with no per-token override. Please add:

  1. Scopes on the token: at least read (GET only), write (GET/POST/PATCH) and delete as separate grants; default stays "everything" for existing tokens so nothing breaks.
  2. Optional per-token rate limit (nullable column; empty = use API_KEY_RATE_LIMIT).

Why should this be worked on?

Bots and AI agents get their own key so that people can audit what they did. Today a bot that only needs to read and comment can still wipe a project with one call. Reproduced on v1.4.3: with the same key that lists and comments, DELETE /issues/{id}/ returns 204 and DELETE /projects/{id}/ returns 204 (repro_limitacoes.py, section 4, uses a throwaway project). Operators who run several bots also cannot give a read-heavy sync job more requests/minute than a bot that writes once a day, without raising the limit for everyone.

Proposed behaviour

  • Token creation (UI and API) accepts scopes (list). Existing rows migrate to all scopes.
  • APIKeyAuthentication attaches the scopes to the request; a small permission class checks the HTTP method (GET/HEAD/OPTIONS → read; POST/PUT/PATCH → write; DELETE → delete) and answers 403 with the missing scope.
  • ApiKeyRateThrottle reads the token's own limit when set, otherwise settings.API_KEY_RATE_LIMIT.

Implementation sketch (not tested against the Plane test suite)

Pinned to 618d0eb7.

  • db/models/api.py: scopes = ArrayField(models.CharField(max_length=16), default=default_scopes) and rate_limit = models.CharField(max_length=32, null=True, blank=True) + migration with the default ["read","write","delete"].
  • api/middleware/api_authentication.py (APIKeyAuthentication.authenticate): return the token as auth, so permission classes can read request.auth.scopes.
  • api/rate_limit.py: rate = settings.API_KEY_RATE_LIMIT is a class attribute; override get_rate() to look at the token when it is available.
  • A TokenScopePermission listed in DEFAULT_PERMISSION_CLASSES for the /api/v1 views.

Tests worth adding

  1. Token with scopes=["read"]: GET 200, POST/PATCH/DELETE 403.
  2. Token with ["read","write"]: PATCH 200, DELETE 403.
  3. Legacy token (migrated): everything still works.
  4. Token with rate_limit="5/minute": the sixth call in a minute returns 429; another token is unaffected.

Workaround we use meanwhile

The CLI used by our agents does not expose delete, and the rules ask agents never to call the API directly to delete. That is a convention, not a barrier. For the rate limit, the operator raises API_KEY_RATE_LIMIT for the whole instance.

pitupi avatar Nov 07 '26 21:11 pitupi

Can I work on this?

harshdubey1234 avatar Nov 17 '26 08:11 harshdubey1234

Hi @harshdubey1234, thanks for picking this up. Yes, go ahead.

The sketch in the issue is untested, so treat it as a starting point. A few things to check before opening a PR:

  • Branch off and target preview, not main (see CONTRIBUTING.md, "Submitting a pull request").
  • APIKeyAuthentication.authenticate() currently returns the token string as auth. If you change it to the APIToken object, check every reader of request.auth first.
  • The scope permission must pass through for session-authenticated requests (the web UI uses SessionAuthentication). Only enforce scopes when request.auth is an APIToken.
  • For the migration, run makemigrations, commit apps/api/migrations_lockfile.txt, and make sure existing rows get all three scopes so nothing breaks.
  • Test layout is in apps/api/plane/tests/TESTING_GUIDE.md. The four cases in the issue map well to unit tests.
  • Consider splitting it: scopes in one PR, per-token rate limit as a follow-up.

Before writing a lot of code, please post a short plan here (scope names, default for existing tokens, how the permission class is attached) so a maintainer can confirm the direction.

pitupi avatar Nov 17 '26 11:11 pitupi

Thank you @pitupi I've traced the authentication flow with Operate and here's my plan:

Operate Investigation

I used Operate to map the authentication flow and identified:

  • APIKeyAuthentication.authenticate() currently returns token string as auth
  • ApiKeyRateThrottle uses global API_KEY_RATE_LIMIT
  • No existing permission class checks token scopes
  • Will share full investigation link in the PR

Implementation Plan

Scope names: read, write, delete

  • read → GET, HEAD, OPTIONS
  • write → POST, PUT, PATCH
  • delete → DELETE

Default for existing tokens: ["read", "write", "delete"] (backward compatible)

Permission class attachment: Add TokenScopePermission to DEFAULT_PERMISSION_CLASSES in settings/common.py so it applies globally.

Changes

  1. Database (db/models/api.py):

    • Add scopes = ArrayField(default=["read","write","delete"])
    • Add rate_limit = CharField(null=True, blank=True) for follow-up PR
    • Run makemigrations, commit migrations_lockfile.txt
    • Migration ensures existing tokens get all 3 scopes
  2. Authentication (api/middleware/api_authentication.py):

    • Change authenticate() to return (user, api_token_object) instead of (user, token_string)
    • Will audit all code reading request.auth to handle APIToken object
  3. Permission (api/permissions/token_scopes.py - new file):

    • Create TokenScopePermission
    • Only enforce when request.auth is APIToken (session auth bypasses)
    • Map HTTP method → required scope, raise 403 if missing
  4. Tests (tests/contract/app/test_api_token_scopes.py - new file):

    • Token with ["read"]: GET 200, POST/PATCH/DELETE 403
    • Token with ["read","write"]: PATCH 200, DELETE 403
    • Legacy token: all operations work
    • Session auth bypasses scope checks

Split Work

PR #1 (this PR): Scopes only PR #2 (follow-up): Per-token rate limits

Target branch: preview

Let me know if this looks good and I'll start implementation!

harshdubey1234 avatar Nov 17 '26 15:11 harshdubey1234

Thanks @harshdubey1234, the plan is close. Direction confirmed on scope names (read / write / delete), the method mapping, the all-scopes default for existing rows, and the two-PR split. Four corrections before you start:

1. DEFAULT_PERMISSION_CLASSES will not reach the /api/v1 views. BaseAPIView and BaseViewSet (apps/api/plane/api/views/base.py) set permission_classes = [IsAuthenticated], and most concrete views override it again (ProjectEntityPermission, ProjectMemberPermission, ...). A class added to the global default is never consulted for them, so the 403 would never fire. Please enforce the scope at a single choke point that every v1 view passes through, for example:

  • in initial() of both BaseAPIView and BaseViewSet (they already have an initial() that validates the body), or
  • in APIKeyAuthentication.authenticate() itself, since it has request.method.

Either way, one helper (required_scope(method)) so the mapping lives in one place. Unknown methods should be denied, not allowed.

2. Session auth. These views only use APIKeyAuthentication, so there is no session path to bypass here. Still, only enforce when request.auth is an APIToken, so nothing else that reuses these base classes is affected.

3. Keep rate_limit out of PR #1. Add the column and its migration in PR #2, together with the throttle change. PR #1 should have exactly one migration (scopes) plus the updated migrations_lockfile.txt.

4. Token creation. The plan doesn't say how scopes gets set. PR #1 should include:

  • the token create endpoint/serializer accepting scopes (list, validated against the three allowed values, non-empty, default = all three), and returning it in the response;
  • the "Create API token" form in the web UI, or at least a note if you want that as a separate PR (the API side is the part that matters for enforcement).

Also:

  • Tests go in apps/api/plane/tests/contract/api/ (next to test_authentication.py), not contract/app/.
  • Add a case where the scope is missing and the response body names the missing scope (403, as in the issue).
  • Add a case for HEAD/OPTIONS with a read-only token.
  • Changing authenticate() to return the APIToken object: please grep every reader of request.auth (including middleware such as the API token log) and list them in the PR description. ApiKeyRateThrottle reads X-Api-Key from the header, not request.auth, so it shouldn't be affected, but confirm.

With those changes, go ahead. Target preview. A maintainer will still need to confirm before merge, but nothing here needs further sign-off from my side.

pitupi avatar Nov 17 '26 18:11 pitupi