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: 2 additions & 0 deletions .github/workflows/docker-hub.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ on:
push:
branches:
- 'main'
- 'feat/resource-server'
tags:
- 'v*'
pull_request:
branches:
- 'main'
- 'feat/resource-server'

env:
DOCKER_USER: 1001:127
Expand Down
1 change: 1 addition & 0 deletions src/backend/core/external_api/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Drive core resource_server package."""
64 changes: 64 additions & 0 deletions src/backend/core/external_api/authentication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Authentication for external API using JWT token."""

import logging

from django.conf import settings

import jwt
from rest_framework import authentication

from core.models import User

logger = logging.getLogger(__name__)


class JWTAuthentication(authentication.BaseAuthentication):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may add a authenticate_header method to return a 401 instead of a 403 when no authentication is provided.

"""Authentication for external API using JWT token."""

def authenticate(self, request):
"""Authenticate the request using JWT token."""

auth_header = request.headers.get("Authorization")
if not auth_header:
logger.warning("No Authorization header found in request")
return None

# Check if the header starts with 'Bearer '
if not auth_header.startswith("Bearer "):
logger.warning(
"Invalid Authorization header format. Expected 'Bearer <token>'"
)
return None

# Extract the token
token = auth_header.split(" ")[1]

# Validate the token
try:
payload = jwt.decode(
token,
settings.JWT_SECRET_KEY,
options={"require": settings.JWT_REQUIRED_CLAIMS},
algorithms=[settings.JWT_ALGORITHM],
)
except jwt.InvalidTokenError as e:
logger.error("Invalid JWT token: %s", e)
return None

if not payload.get("sub") or not payload.get("email"):
logger.warning("Invalid JWT token. Missing 'sub' or 'email' in payload")
return None

user = User.objects.get_user_by_sub_or_email(
payload.get("sub"), payload.get("email")
)
if not user:
if settings.JWT_CREATE_USER:
user = User(sub=payload.get("sub"), email=payload.get("email"))
user.set_unusable_password()
user.save()
else:
logger.warning("User not found")
return None

return user, None
48 changes: 48 additions & 0 deletions src/backend/core/external_api/permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Resource Server Permissions for the Drive app."""

from django.conf import settings

from lasuite.oidc_resource_server.authentication import ResourceServerAuthentication
from rest_framework import permissions

from .authentication import JWTAuthentication


class ResourceServerClientPermission(permissions.BasePermission):
"""
Permission class for resource server views.
This provides a way to open the resource server views to a limited set of
Service Providers.
Note: we might add a more complex permission system in the future, based on
the Service Provider ID and the requested scopes.
"""

def has_permission(self, request, view):
"""
Check if the user is authenticated and the token introspection
provides an authorized Service Provider.
"""
if not isinstance(
request.successful_authenticator,
(JWTAuthentication, ResourceServerAuthentication),
):
# Not a resource server request
return False

# Check if the user is authenticated
if not request.user.is_authenticated:
return False
if (
hasattr(view, "resource_server_actions")
and view.action not in view.resource_server_actions
):
return False

# When used as a resource server, the request has a token audience
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment needs an update and so the docstring (class & method)

return (
getattr(request, "resource_server_token_audience", None)
in settings.OIDC_RS_ALLOWED_AUDIENCES
) or isinstance(
request.successful_authenticator,
JWTAuthentication, # JWT Token are forcibly allowed
)
62 changes: 62 additions & 0 deletions src/backend/core/external_api/viewsets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Resource Server Viewsets for the Drive app."""

from django.conf import settings

from lasuite.oidc_resource_server.authentication import ResourceServerAuthentication

from ..api.permissions import (
AccessPermission,
CanCreateInvitationPermission,
IsSelf,
ItemAccessPermission,
)
from ..api.viewsets import (
InvitationViewset,
ItemAccessViewSet,
ItemViewSet,
UserViewSet,
)
from .authentication import JWTAuthentication
from .permissions import ResourceServerClientPermission

# pylint: disable=too-many-ancestors


if settings.JWT_AUTH_ENABLED:
EXTERNAL_API_AUTH_CLASSES = [JWTAuthentication, ResourceServerAuthentication]
else:
EXTERNAL_API_AUTH_CLASSES = [ResourceServerAuthentication]


class ResourceServerItemViewSet(ItemViewSet):
"""Resource Server Viewset for the Drive app."""

authentication_classes = EXTERNAL_API_AUTH_CLASSES

permission_classes = [ResourceServerClientPermission & ItemAccessPermission]


class ResourceServerItemAccessViewSet(ItemAccessViewSet):
"""Resource Server Viewset for the Drive app."""

authentication_classes = EXTERNAL_API_AUTH_CLASSES

permission_classes = [ResourceServerClientPermission & AccessPermission]


class ResourceServerInvitationViewSet(InvitationViewset):
"""Resource Server Viewset for the Drive app."""

authentication_classes = EXTERNAL_API_AUTH_CLASSES

permission_classes = [
ResourceServerClientPermission & CanCreateInvitationPermission
]


class ResourceServerUserViewSet(UserViewSet):
"""Resource Server UserViewset for the Drive app."""

authentication_classes = EXTERNAL_API_AUTH_CLASSES

permission_classes = [ResourceServerClientPermission & IsSelf]
5 changes: 5 additions & 0 deletions src/backend/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,11 @@ def get_abilities(self, user, ancestors_links=None):

def send_email(self, subject, emails, context=None, language=None):
"""Generate and send email from a template."""

if not settings.EMAIL_HOST:
logger.debug("EMAIL_HOST host is not set, skipping email sending")
return

context = context or {}
domain = Site.objects.get_current().domain
language = language or get_language()
Expand Down
39 changes: 39 additions & 0 deletions src/backend/core/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from django.core.cache import cache

import pytest
import responses

USER = "user"
TEAM = "team"
Expand All @@ -25,3 +26,41 @@ def mock_user_teams():
"core.models.User.teams", new_callable=mock.PropertyMock
) as mock_teams:
yield mock_teams


@pytest.fixture
def resource_server_backend(settings):
"""
A fixture to create a user token for testing.
"""
assert (
settings.OIDC_RS_BACKEND_CLASS
== "lasuite.oidc_resource_server.backend.ResourceServerBackend"
)

settings.OIDC_RS_CLIENT_ID = "some_client_id"
settings.OIDC_RS_CLIENT_SECRET = "some_client_secret"

settings.OIDC_OP_URL = "https://oidc.example.com"
settings.OIDC_VERIFY_SSL = False
settings.OIDC_TIMEOUT = 5
settings.OIDC_PROXY = None
settings.OIDC_OP_JWKS_ENDPOINT = "https://oidc.example.com/jwks"
settings.OIDC_OP_INTROSPECTION_ENDPOINT = "https://oidc.example.com/introspect"
settings.OIDC_RS_SCOPES = ["openid", "groups"]
settings.OIDC_RS_ALLOWED_AUDIENCES = ["some_service_provider"]
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
"https://oidc.example.com/introspect",
json={
"iss": "https://oidc.example.com",
"aud": "some_client_id", # settings.OIDC_RS_CLIENT_ID
"sub": "very-specific-sub",
"client_id": "some_service_provider",
"scope": "openid groups",
"active": True,
},
)

yield rsps
Empty file.
Loading
Loading