Skip to content
Draft
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
1 change: 1 addition & 0 deletions CHANGES/kessel-content-guard.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added KesselContentGuard, which permits content access only when Kessel grants the guard's permission (e.g. `content_sources_repository_view`) to the requesting user or service account on its org's default workspace.
7 changes: 7 additions & 0 deletions deploy/clowdapp.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,8 @@ objects:
value: ${KESSEL_URL}
- name: PULP_KESSEL_TOKEN_URL
value: ${KESSEL_TOKEN_URL}
- name: PULP_KESSEL_RBAC_URL
value: ${KESSEL_RBAC_URL}
- name: PULP_KESSEL_CLIENT_ID
valueFrom:
secretKeyRef:
Expand Down Expand Up @@ -645,6 +647,8 @@ objects:
value: ${KESSEL_URL}
- name: PULP_KESSEL_TOKEN_URL
value: ${KESSEL_TOKEN_URL}
- name: PULP_KESSEL_RBAC_URL
value: ${KESSEL_RBAC_URL}
- name: PULP_KESSEL_CLIENT_ID
valueFrom:
secretKeyRef:
Expand Down Expand Up @@ -1954,6 +1958,9 @@ parameters:
- name: KESSEL_TOKEN_URL
description: Red Hat SSO token endpoint for the Kessel client_credentials grant
value: "https://sso.stage.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token"
- name: KESSEL_RBAC_URL
description: RBAC base URL for the Kessel default-workspace lookup (set per environment in app-interface deploy.yml)
value: ""
- name: PULP_TASK_PROTECTION_TIME
description: Set the time in minutes to purge tasks
value: "20160"
Expand Down
80 changes: 80 additions & 0 deletions pulp_service/pulp_service/app/kessel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""
Kessel client used by KesselContentGuard.

Mirrors content-sources-backend: look up the org's default workspace via RBAC v2, then ask
Kessel Inventory (v1beta2 ``Check``) whether ``redhat/<user_id>`` has ``permission`` on it.
"""

from functools import lru_cache

from django.conf import settings
from kessel.auth import OAuth2ClientCredentials, oauth2_auth_request
from kessel.inventory.v1beta2 import ClientBuilder
from kessel.inventory.v1beta2.allowed_pb2 import ALLOWED_TRUE
from kessel.inventory.v1beta2.check_request_pb2 import CheckRequest
from kessel.rbac.v2 import fetch_default_workspace, principal_subject, workspace_resource
from requests.adapters import HTTPAdapter

_TIMEOUT = 5 # seconds, for the token fetch, the RBAC lookup and the gRPC call


class _TimeoutAdapter(HTTPAdapter):
"""The SDK fetches tokens without a timeout; default one so a hung SSO can't block forever."""

def send(self, request, **kwargs):
kwargs["timeout"] = kwargs.get("timeout") or _TIMEOUT
return super().send(request, **kwargs)


@lru_cache(maxsize=1)
def _credentials():
"""OAuth2 client-credentials token source, or None when no credentials are configured (dev)."""
if not (settings.KESSEL_CLIENT_ID and settings.KESSEL_CLIENT_SECRET):
return None
creds = OAuth2ClientCredentials(
client_id=settings.KESSEL_CLIENT_ID,
client_secret=settings.KESSEL_CLIENT_SECRET,
token_endpoint=settings.KESSEL_TOKEN_URL,
retry={"max_retries": 1},
)
# ponytail: reaches into the SDK's private OAuth2Session; drop once kessel-sdk accepts a timeout.
creds._session.mount("https://", _TimeoutAdapter())
creds._session.mount("http://", _TimeoutAdapter())
return creds


@lru_cache(maxsize=1)
def _stub():
creds = _credentials()
builder = ClientBuilder(settings.KESSEL_URL)
builder = builder.oauth2_client_authenticated(creds) if creds else builder.insecure()
stub, _channel = builder.build()
return stub


# Workspace ids don't change, so cache per org. lru_cache does not cache exceptions.
@lru_cache(maxsize=1024)
def _default_workspace_id(org_id):
creds = _credentials()
workspace = fetch_default_workspace(
settings.KESSEL_RBAC_URL,
org_id,
auth=oauth2_auth_request(creds) if creds else None,
timeout=_TIMEOUT,
)
return workspace.id


def check_permission(org_id, user_id, permission):
"""
Return True only if Kessel answers ALLOWED_TRUE for ``permission`` on the org's default workspace.

Raises on any transport/config error; the caller decides how to fail.
"""
request = CheckRequest(
object=workspace_resource(_default_workspace_id(org_id)),
relation=permission,
subject=principal_subject(user_id, "redhat"),
)
response = _stub().Check(request, timeout=_TIMEOUT)
return response.allowed == ALLOWED_TRUE
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 5.2.16 on 2026-11-17 20:11

import django.db.models.deletion
import pulpcore.app.models.access_policy
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('core', '0160_envvarheadercontentguard'),
('service', '0026_andgatecontentguard'),
]

operations = [
migrations.CreateModel(
name='KesselContentGuard',
fields=[
('contentguard_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.contentguard')),
('permission', models.TextField()),
],
options={
'permissions': (('manage_roles_kesselcontentguard', 'Can manage role assignments on Kessel ContentGuard'),),
'default_related_name': '%(app_label)s_%(model_name)s',
},
bases=('core.contentguard', pulpcore.app.models.access_policy.AutoAddObjPermsMixin),
),
]
51 changes: 51 additions & 0 deletions pulp_service/pulp_service/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from pulp_service.app.content_view_models import ContentView, ContentViewSearchScope # noqa: F401
from pulp_service.app.features_service import check_subscription
from pulp_service.app.kessel import check_permission
from pulp_service.exceptions import AuthenticationError

_logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -136,6 +137,56 @@ class Meta:
)


def _principal_from_identity_header(request):
"""
Return ``(org_id, user_id)`` from the request's ``x-rh-identity`` header.

Raises AuthenticationError when the header is missing, PermissionError when it can't be
parsed or carries no user/service-account principal.
"""
header = request.headers.get("x-rh-identity")
if header is None:
raise AuthenticationError(_("Authentication required."))
try:
identity = json.loads(b64decode(header))["identity"]
org_id = identity.get("org_id") or identity.get("internal", {}).get("org_id")
principal_key = {"User": "user", "ServiceAccount": "service_account"}.get(identity.get("type"))
user_id = identity.get(principal_key, {}).get("user_id") if principal_key else None
except (Base64DecodeError, ValueError, KeyError, TypeError, AttributeError) as exc:
raise PermissionError(_("Access denied.")) from exc
if not (org_id and user_id):
raise PermissionError(_("Access denied."))
return str(org_id), str(user_id)


class KesselContentGuard(ContentGuard, AutoAddObjPermsMixin):
"""
Content guard that permits access only when Kessel grants ``permission`` to the requesting
principal on its org's default workspace (e.g. ``content_sources_repository_view``).

Fails closed: any error talking to RBAC/Kessel denies access.
"""

TYPE = "kessel"

permission = models.TextField()

def permit(self, request):
org_id, user_id = _principal_from_identity_header(request)
try:
allowed = check_permission(org_id, user_id, self.permission)
except Exception as exc:
# permit() must only raise PermissionError/AuthenticationError (pulpcore's handler contract).
_logger.exception("Kessel permission check failed.")
raise PermissionError(_("Access denied.")) from exc
if not allowed:
raise PermissionError(_("Access denied."))

class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
permissions = (("manage_roles_kesselcontentguard", "Can manage role assignments on Kessel ContentGuard"),)


class YankedPackageReport(BaseModel):
"""
Stores the result of a PyPI yank check for Python packages stored in Pulp.
Expand Down
18 changes: 18 additions & 0 deletions pulp_service/pulp_service/app/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
from pulp_service.app.models import (
AndGateContentGuard,
FeatureContentGuard,
KesselContentGuard,
PyPIYankMonitor,
VulnerabilityReport,
YankedPackageReport,
Expand Down Expand Up @@ -69,6 +70,23 @@ class Meta(ContentGuardSerializer.Meta):
fields = (*ContentGuardSerializer.Meta.fields, "header_name", "jq_filter", "features")


class KesselContentGuardSerializer(ContentGuardSerializer, GetOrCreateSerializerMixin):
"""
A serializer for KesselContentGuard.
"""

permission = serializers.CharField(
help_text=_(
"Kessel permission the requesting principal must have on its org's default workspace, "
"e.g. content_sources_repository_view."
),
)

class Meta(ContentGuardSerializer.Meta):
model = KesselContentGuard
fields = (*ContentGuardSerializer.Meta.fields, "permission")


class AndGateContentGuardSerializer(ContentGuardSerializer, GetOrCreateSerializerMixin):
"""
A serializer for AndGateContentGuard.
Expand Down
6 changes: 6 additions & 0 deletions pulp_service/pulp_service/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@
# malformed timeout value and raises a ValueError.
FEATURE_SERVICE_API_CONNECT_TIMEOUT = 2
FEATURE_SERVICE_API_READ_TIMEOUT = 5
# Kessel (KesselContentGuard); set via PULP_KESSEL_* env vars in deploy/clowdapp.yaml.
KESSEL_URL = "" # Kessel Inventory gRPC host:port, no scheme (TLS when client credentials are set)
KESSEL_TOKEN_URL = ""
KESSEL_CLIENT_ID = ""
KESSEL_CLIENT_SECRET = ""
KESSEL_RBAC_URL = ""
AUTHENTICATION_HEADER_DEBUG = False
INSTALLED_APPS = "@merge django.contrib.admin.apps.SimpleAdminConfig,hijack,hijack.contrib.admin"
TEST_TASK_INGESTION = False
Expand Down
80 changes: 79 additions & 1 deletion pulp_service/pulp_service/app/viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,19 @@
RpmContentViewPackageListViewSet,
RpmContentViewPackageSearchViewSet,
)
from pulp_service.app.models import AndGateContentGuard, FeatureContentGuard, PyPIYankMonitor, YankedPackageReport
from pulp_service.app.models import (
AndGateContentGuard,
FeatureContentGuard,
KesselContentGuard,
PyPIYankMonitor,
YankedPackageReport,
)
from pulp_service.app.models import VulnerabilityReport as VulnReport
from pulp_service.app.serializers import (
AndGateContentGuardSerializer,
ContentScanSerializer,
FeatureContentGuardSerializer,
KesselContentGuardSerializer,
NpmManifestBackfillSerializer,
PublicDebugAuthenticationHeadersSerializer,
PyPIYankMonitorSerializer,
Expand Down Expand Up @@ -258,6 +265,77 @@ class FeatureContentGuardViewSet(ContentGuardViewSet, RolesMixin):
}


class KesselContentGuardViewSet(ContentGuardViewSet, RolesMixin):
"""
Content guard to protect content with Kessel permission checks.
"""

endpoint_name = "kessel"
queryset = KesselContentGuard.objects.all()
serializer_class = KesselContentGuardSerializer
queryset_filtering_required_permission = "service.view_kesselcontentguard"

DEFAULT_ACCESS_POLICY = {
"statements": [
{"action": ["list", "my_permissions"], "principal": "authenticated", "effect": "allow"},
{
"action": ["create"],
"principal": "authenticated",
"effect": "allow",
"condition": "has_model_or_domain_perms:service.add_kesselcontentguard",
},
{
"action": ["retrieve"],
"principal": "authenticated",
"effect": "allow",
"condition": "has_model_or_domain_or_obj_perms:service.view_kesselcontentguard",
},
{
"action": ["update", "partial_update"],
"principal": "authenticated",
"effect": "allow",
"condition": [
"has_model_or_domain_or_obj_perms:service.change_kesselcontentguard",
"has_model_or_domain_or_obj_perms:service.view_kesselcontentguard",
],
},
{
"action": ["destroy"],
"principal": "authenticated",
"effect": "allow",
"condition": [
"has_model_or_domain_or_obj_perms:service.delete_kesselcontentguard",
"has_model_or_domain_or_obj_perms:service.view_kesselcontentguard",
],
},
{
"action": ["list_roles", "add_role", "remove_role"],
"principal": "authenticated",
"effect": "allow",
"condition": "has_model_or_domain_or_obj_perms:service.manage_roles_kesselcontentguard",
},
],
"creation_hooks": [
{
"function": "add_roles_for_object_creator",
"parameters": {"roles": "service.kesselcontentguard_owner"},
}
],
"queryset_scoping": {"function": "scope_queryset"},
}

LOCKED_ROLES = {
"service.kesselcontentguard_creator": ["service.add_kesselcontentguard"],
"service.kesselcontentguard_owner": [
"service.view_kesselcontentguard",
"service.change_kesselcontentguard",
"service.delete_kesselcontentguard",
"service.manage_roles_kesselcontentguard",
],
"service.kesselcontentguard_viewer": ["service.view_kesselcontentguard"],
}


class AndGateContentGuardViewSet(ContentGuardViewSet, RolesMixin):
"""
Content guard that permits access only when all of its sub-guards permit.
Expand Down
Loading
Loading