Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/api/migrations_lockfile.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
# A merge conflict here means another PR added a migration to the same app first:
# merge preview, delete your migration, and run makemigrations again.

db: 0125_reset_project_deploy_board_identity
db: 0126_apitoken_scopes

license: 0006_instance_is_current_version_deprecated
48 changes: 43 additions & 5 deletions apps/api/plane/api/middleware/api_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,31 @@

# Third party imports
from rest_framework import authentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.exceptions import AuthenticationFailed, PermissionDenied

# Module imports
from plane.db.models import APIToken
from plane.db.models.api import (
API_TOKEN_SCOPE_DELETE,
API_TOKEN_SCOPE_READ,
API_TOKEN_SCOPE_WRITE,
)

# The scope a token needs for each HTTP method. Methods not listed here are refused.
METHOD_SCOPES = {
"GET": API_TOKEN_SCOPE_READ,
"HEAD": API_TOKEN_SCOPE_READ,
"OPTIONS": API_TOKEN_SCOPE_READ,
"POST": API_TOKEN_SCOPE_WRITE,
"PUT": API_TOKEN_SCOPE_WRITE,
"PATCH": API_TOKEN_SCOPE_WRITE,
"DELETE": API_TOKEN_SCOPE_DELETE,
}


def required_scope(method):
"""Return the scope an API token needs for an HTTP method, or None if the method is not allowed."""
return METHOD_SCOPES.get(method.upper())


class APIKeyAuthentication(authentication.BaseAuthentication):
Expand Down Expand Up @@ -40,16 +61,33 @@ def validate_api_token(self, token):
# save api token last used
api_token.last_used = timezone.now()
api_token.save(update_fields=["last_used"])
return (api_token.user, api_token.token)
return (api_token.user, api_token)

def enforce_scope(self, request, api_token):
"""
Refuse the request unless the token holds the scope its HTTP method needs.

Enforced here rather than in a permission class because every view that
accepts API keys authenticates through this class, while views override
permission_classes.
"""
scope = required_scope(request.method)
if scope is None:
raise PermissionDenied(f"API tokens cannot be used for {request.method} requests.")
if scope not in (api_token.scopes or []):
raise PermissionDenied(f"This API token does not have the '{scope}' scope.")

def authenticate(self, request):
token = self.get_api_token(request=request)
if not token:
return None

# Validate the API token
user, token = self.validate_api_token(token)
user, api_token = self.validate_api_token(token)

# Mark the underlying Django request, which is the one APITokenLogMiddleware sees
# Mark the underlying Django request, which is the one APITokenLogMiddleware sees.
# Set before the scope check so refused requests still reach the activity log.
getattr(request, "_request", request).api_key_authenticated = True
return user, token

self.enforce_scope(request, api_token)
return user, api_token
2 changes: 1 addition & 1 deletion apps/api/plane/app/serializers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
ModuleUserPropertiesSerializer,
)

from .api import APITokenSerializer, APITokenReadSerializer
from .api import APITokenSerializer, APITokenReadSerializer, APITokenCreateSerializer

from .importer import ImporterSerializer

Expand Down
24 changes: 24 additions & 0 deletions apps/api/plane/app/serializers/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from .base import BaseSerializer
from plane.db.models import APIToken, APIActivityLog
from plane.db.models.api import API_TOKEN_SCOPES
from rest_framework import serializers
from django.utils import timezone

Expand All @@ -22,9 +23,32 @@ class Meta:
"is_active",
"last_used",
"user_type",
# Fixed at creation; widening an issued token's access needs a new token
"scopes",
]


class APITokenCreateSerializer(BaseSerializer):
"""Validates the fields a user may set when creating an API token."""

scopes = serializers.ListField(
child=serializers.ChoiceField(choices=API_TOKEN_SCOPES),
allow_empty=False,
required=False,
help_text="Any of read, write and delete. Defaults to all three.",
)

class Meta:
model = APIToken
fields = ["label", "description", "expired_at", "scopes"]
# The endpoint has always accepted an empty label
extra_kwargs = {"label": {"allow_blank": True}}

def validate_scopes(self, value):
# Drop duplicates and store in a stable order
return [scope for scope in API_TOKEN_SCOPES if scope in value]


class APITokenReadSerializer(BaseSerializer):
is_active = serializers.SerializerMethodField()

Expand Down
21 changes: 9 additions & 12 deletions apps/api/plane/app/views/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
# See the LICENSE file for details.

# Python import
from uuid import uuid4
from typing import Optional

# Third party
Expand All @@ -14,25 +13,23 @@
# Module import
from .base import BaseAPIView
from plane.db.models import APIToken
from plane.app.serializers import APITokenSerializer, APITokenReadSerializer
from plane.app.serializers import (
APITokenSerializer,
APITokenReadSerializer,
APITokenCreateSerializer,
)


class ApiTokenEndpoint(BaseAPIView):
def post(self, request: Request) -> Response:
label = request.data.get("label", str(uuid4().hex))
description = request.data.get("description", "")
expired_at = request.data.get("expired_at", None)
create_serializer = APITokenCreateSerializer(data=request.data)
if not create_serializer.is_valid():
return Response(create_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

# Check the user type
user_type = 1 if request.user.is_bot else 0

api_token = APIToken.objects.create(
label=label,
description=description,
user=request.user,
user_type=user_type,
expired_at=expired_at,
)
api_token = create_serializer.save(user=request.user, user_type=user_type)

serializer = APITokenSerializer(api_token)
# Token will be only visible while creating
Expand Down
24 changes: 24 additions & 0 deletions apps/api/plane/db/migrations/0126_apitoken_scopes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 5.2.17 on 2026-11-18 17:19

import django.contrib.postgres.fields
import plane.db.models.api
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("db", "0125_reset_project_deploy_board_identity"),
]

operations = [
migrations.AddField(
model_name="apitoken",
name="scopes",
field=django.contrib.postgres.fields.ArrayField(
base_field=models.CharField(max_length=16),
default=plane.db.models.api.default_api_token_scopes,
help_text="Scopes granted to this token: read, write and/or delete",
size=None,
),
),
]
18 changes: 18 additions & 0 deletions apps/api/plane/db/models/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,17 @@
# Django imports
from django.db import models
from django.conf import settings
from django.contrib.postgres.fields import ArrayField

from .base import BaseModel

# Scopes an API token can be granted. Each HTTP method needs exactly one of them
# (see required_scope in plane/api/middleware/api_authentication.py).
API_TOKEN_SCOPE_READ = "read"
API_TOKEN_SCOPE_WRITE = "write"
API_TOKEN_SCOPE_DELETE = "delete"
API_TOKEN_SCOPES = (API_TOKEN_SCOPE_READ, API_TOKEN_SCOPE_WRITE, API_TOKEN_SCOPE_DELETE)


def generate_label_token():
return uuid4().hex
Expand All @@ -20,6 +28,11 @@ def generate_token():
return "plane_api_" + uuid4().hex


def default_api_token_scopes():
# Every scope, so tokens created before scopes existed keep full access
return list(API_TOKEN_SCOPES)


class APIToken(BaseModel):
# Meta information
label = models.CharField(max_length=255, default=generate_label_token)
Expand All @@ -35,6 +48,11 @@ class APIToken(BaseModel):
user_type = models.PositiveSmallIntegerField(choices=((0, "Human"), (1, "Bot")), default=0)
workspace = models.ForeignKey("db.Workspace", related_name="api_tokens", on_delete=models.CASCADE, null=True)
expired_at = models.DateTimeField(blank=True, null=True)
scopes = ArrayField(
models.CharField(max_length=16),
default=default_api_token_scopes,
help_text="Scopes granted to this token: read, write and/or delete",
)

class Meta:
verbose_name = "API Token"
Expand Down
139 changes: 139 additions & 0 deletions apps/api/plane/tests/contract/api/test_api_token_scopes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# Copyright (c) 2023-present Plane Software, Inc. and contributors
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.

"""
Contract tests for scoped API tokens on the external API.

A token may only make requests whose HTTP method its scopes allow:
GET/HEAD/OPTIONS need "read", POST/PUT/PATCH need "write", DELETE needs "delete".
"""

from uuid import uuid4

import pytest
from rest_framework import status

from plane.db.models import APIToken, Project

USERS_ME_URL = "/api/v1/users/me/"


def projects_url(slug):
return f"/api/v1/workspaces/{slug}/projects/"


def project_url(slug, project_id):
return f"/api/v1/workspaces/{slug}/projects/{project_id}/"


@pytest.fixture
def scoped_client(api_client, create_user):
"""Return a factory that authenticates api_client with a new token holding the given scopes."""

def make(scopes):
token = APIToken.objects.create(user=create_user, label=f"scoped-{uuid4().hex[:8]}", scopes=scopes)
api_client.credentials(HTTP_X_API_KEY=token.token)
return api_client

return make


@pytest.fixture
def project(api_key_client, workspace):
"""A project created through the API with the default (all scopes) token."""
response = api_key_client.post(
projects_url(workspace.slug), {"name": "Scoped Token Project", "identifier": "STP"}, format="json"
)
assert response.status_code == status.HTTP_201_CREATED, response.data
return Project.objects.get(pk=response.data["id"])


@pytest.mark.contract
class TestAPITokenScopes:
@pytest.mark.django_db
def test_read_only_token_can_read(self, scoped_client, workspace, project):
client = scoped_client(["read"])

assert client.get(USERS_ME_URL).status_code == status.HTTP_200_OK
assert client.get(project_url(workspace.slug, project.id)).status_code == status.HTTP_200_OK

@pytest.mark.django_db
def test_read_only_token_cannot_write(self, scoped_client, workspace, project):
client = scoped_client(["read"])

create = client.post(projects_url(workspace.slug), {"name": "Nope", "identifier": "NOPE"}, format="json")
update = client.patch(project_url(workspace.slug, project.id), {"name": "Renamed"}, format="json")

assert create.status_code == status.HTTP_403_FORBIDDEN
assert update.status_code == status.HTTP_403_FORBIDDEN
assert not Project.objects.filter(identifier="NOPE").exists()
project.refresh_from_db()
assert project.name == "Scoped Token Project"

@pytest.mark.django_db
def test_read_only_token_cannot_delete(self, scoped_client, workspace, project):
client = scoped_client(["read"])

response = client.delete(project_url(workspace.slug, project.id))

assert response.status_code == status.HTTP_403_FORBIDDEN
assert Project.objects.filter(pk=project.id).exists()

@pytest.mark.django_db
def test_read_write_token_can_update_but_not_delete(self, scoped_client, workspace, project):
client = scoped_client(["read", "write"])

update = client.patch(project_url(workspace.slug, project.id), {"name": "Renamed"}, format="json")
delete = client.delete(project_url(workspace.slug, project.id))

assert update.status_code == status.HTTP_200_OK, update.data
assert delete.status_code == status.HTTP_403_FORBIDDEN
assert Project.objects.filter(pk=project.id).exists()

@pytest.mark.django_db
def test_read_only_token_passes_scope_check_for_head_and_options(self, scoped_client):
"""HEAD and OPTIONS need only "read".

The v1 routes list their methods explicitly and none enable HEAD or OPTIONS, so once the
scope check passes the view answers 405. The point is that the token is not refused with 403.
"""
client = scoped_client(["read"])

for response in (client.head(USERS_ME_URL), client.options(USERS_ME_URL)):
assert response.status_code in (status.HTTP_200_OK, status.HTTP_405_METHOD_NOT_ALLOWED)

@pytest.mark.django_db
def test_head_and_options_need_read_scope(self, scoped_client):
client = scoped_client(["write", "delete"])

assert client.head(USERS_ME_URL).status_code == status.HTTP_403_FORBIDDEN
assert client.options(USERS_ME_URL).status_code == status.HTTP_403_FORBIDDEN

@pytest.mark.django_db
def test_write_only_token_cannot_read(self, scoped_client):
client = scoped_client(["write"])

assert client.get(USERS_ME_URL).status_code == status.HTTP_403_FORBIDDEN

@pytest.mark.django_db
def test_token_with_all_scopes_can_delete(self, scoped_client, workspace, project):
client = scoped_client(["read", "write", "delete"])

response = client.delete(project_url(workspace.slug, project.id))

assert response.status_code == status.HTTP_204_NO_CONTENT
assert not Project.objects.filter(pk=project.id).exists()

@pytest.mark.django_db
def test_token_created_without_scopes_keeps_full_access(self, api_token):
"""Tokens issued before scopes existed get every scope from the column default."""
assert api_token.scopes == ["read", "write", "delete"]

@pytest.mark.django_db
def test_denial_names_the_missing_scope(self, scoped_client, workspace, project):
client = scoped_client(["read"])

response = client.delete(project_url(workspace.slug, project.id))

assert "delete" in str(response.data["detail"])
Loading