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
20 changes: 20 additions & 0 deletions docs/user/guides/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,26 @@ token = "crg_..."
Cargo sends the token automatically on state-changing operations (publish, yank, unyank).
Read-only operations (downloading crates, browsing the index) do not require a token.

### Private Registries

To make a registry private, enable `cargo_auth_required` on the distribution:

```bash
http PATCH http://<pulp-host>/pulp/api/v3/distributions/rust/rust/<uuid>/ \
-a admin:password \
cargo_auth_required:=true
```

Pulp then advertises `auth-required: true` in the index `config.json`, so Cargo sends its
credential on index and download requests, and rejects these requests unless the user has the
`rust.view_rustdistribution` permission on the distribution (for example through the
`rust.rustdistribution_viewer` role). Anonymous requests get a `401` with a
`WWW-Authenticate: Cargo` challenge, which tells Cargo to retry with its credential.

The download endpoint redirects to the content app, which this setting does not cover. To
protect the crate files there as well, also attach a content guard that accepts the credential
Cargo sends.

### Scoping a Token

A token can be restricted to a subset of what you are allowed to do, which is useful when
Expand Down
2 changes: 1 addition & 1 deletion pulp_rust/app/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ def authenticate(self, request):
return (cargo_token.user, cargo_token)

def authenticate_header(self, request):
return "CargoToken"
return "Cargo"
23 changes: 23 additions & 0 deletions pulp_rust/app/global_access_conditions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from django.conf import settings

from pulp_rust.app.models import RustCargoToken


def has_distributions_param_model_or_domain_or_obj_perms(request, view, action, permission):
"""Check the permission against every distribution in the `distributions` parameter."""
Expand All @@ -14,3 +16,24 @@ def has_distributions_param_model_or_domain_or_obj_perms(request, view, action,
request.user.has_perm(permission, distribution)
for distribution in serializer.validated_data.get("distributions", [])
)


def can_read_distribution(request, distribution):
"""Whether the request may read the index and crates of a Rust distribution."""
if not distribution.cargo_auth_required:
return True
token = request.auth
if isinstance(token, RustCargoToken):
scoped_distributions = set(token.distributions.values_list("pk", flat=True))
if scoped_distributions and distribution.pk not in scoped_distributions:
return False
permission = "rust.view_rustdistribution"
user = request.user
if user.has_perm(permission) or user.has_perm(permission, distribution):
return True
return settings.DOMAIN_ENABLED and user.has_perm(permission, obj=request.pulp_domain)


def can_read_index(request, view, action):
"""Access condition for the Cargo index views, which expose their distribution."""
return can_read_distribution(request, view.distribution)
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('rust', '0005_rustcargotoken_actions_rustcargotoken_distributions'),
]

operations = [
migrations.AddField(
model_name='rustdistribution',
name='cargo_auth_required',
field=models.BooleanField(default=False),
),
]
1 change: 1 addition & 0 deletions pulp_rust/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,7 @@ class RustDistribution(Distribution, AutoAddObjPermsMixin):
TYPE = "rust"

allow_uploads = models.BooleanField(default=False)
cargo_auth_required = models.BooleanField(default=False)

class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
Expand Down
13 changes: 12 additions & 1 deletion pulp_rust/app/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,13 @@ class Meta:
allow_uploads = serializers.BooleanField(
default=False, help_text=_("Allow packages to be uploaded to this index.")
)
cargo_auth_required = serializers.BooleanField(
default=False,
help_text=_(
"Advertise `auth-required` in the index config, so that Cargo sends its credential "
"on index and download requests, not only on publish and yank."
),
)
remote = core_serializers.DetailRelatedField(
required=False,
help_text=_("Remote that can be used to fetch content when using pull-through caching."),
Expand Down Expand Up @@ -326,7 +333,11 @@ def validate(self, data):
return data

class Meta:
fields = core_serializers.DistributionSerializer.Meta.fields + ("allow_uploads", "remote")
fields = core_serializers.DistributionSerializer.Meta.fields + (
"allow_uploads",
"cargo_auth_required",
"remote",
)
model = models.RustDistribution


Expand Down
40 changes: 30 additions & 10 deletions pulp_rust/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from django.shortcuts import get_object_or_404, redirect
from drf_spectacular.utils import extend_schema
from dynaconf import settings
from rest_framework.exceptions import Throttled
from rest_framework.exceptions import NotAuthenticated, PermissionDenied, Throttled
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import BaseRenderer, JSONRenderer
from rest_framework.views import APIView
Expand All @@ -26,7 +26,9 @@
from pulpcore.plugin.util import get_domain

from pulp_rust.app.auth import CargoTokenAuthentication
from pulp_rust.app.global_access_conditions import can_read_distribution
from pulp_rust.app.models import (
RustCargoToken,
RustContent,
RustDistribution,
RustPackageYank,
Expand Down Expand Up @@ -86,6 +88,10 @@ def token_scope_error(token, action, distro):
Scopes only narrow what a token can do, so this runs in addition to the RBAC check
rather than in place of it. An empty scope means the token is not narrowed at all.
"""
if not isinstance(token, RustCargoToken):
# Credentials other than a Cargo token carry no scopes.
return None

if token.actions and action not in token.actions:
return cargo_error(f"this token is not scoped for the {action} action", status=403)

Expand All @@ -106,6 +112,17 @@ def render(self, data, accepted_media_type=None, renderer_context=None):
return data


class CargoAuthMixin:
"""Try the Cargo token first, then the instance's default authentication classes.

This keeps `cargo login` tokens working while still accepting the other credentials
the deployment is configured for (e.g. HTTP Basic).
"""

def get_authenticators(self):
return [CargoTokenAuthentication(), *super().get_authenticators()]


class ApiMixin:
"""Mixin to get index specific info."""

Expand Down Expand Up @@ -175,7 +192,7 @@ def urlpattern(cls):
return f"pulp/cargo/{cls.endpoint_name}"


class CargoIndexApiViewSet(ApiMixin, ViewSet):
class CargoIndexApiViewSet(CargoAuthMixin, ApiMixin, ViewSet):
"""View for the Cargo JSON metadata endpoint."""

endpoint_name = "api"
Expand All @@ -185,6 +202,7 @@ class CargoIndexApiViewSet(ApiMixin, ViewSet):
"action": ["retrieve"],
"principal": "*",
"effect": "allow",
"condition": "can_read_index",
},
],
}
Expand Down Expand Up @@ -302,7 +320,7 @@ def _build_index_response(crate_versions, yanked_versions=frozenset()):
return HttpResponse("\n".join(lines), content_type="text/plain")


class IndexRoot(ApiMixin, ViewSet):
class IndexRoot(CargoAuthMixin, ApiMixin, ViewSet):
"""View for base_url of distribution."""

endpoint_name = "root"
Expand All @@ -312,6 +330,7 @@ class IndexRoot(ApiMixin, ViewSet):
"action": ["retrieve"],
"principal": "*",
"effect": "allow",
"condition": "can_read_index",
},
],
}
Expand All @@ -322,28 +341,27 @@ def retrieve(self, request, repo):
data = {
"dl": self.base_download_url,
"api": self.base_api_url,
"auth-required": False,
"auth-required": self.distribution.cargo_auth_required,
}
return HttpResponse(json.dumps(data), content_type="application/json")


class CargoMeApiView(APIView):
class CargoMeApiView(CargoAuthMixin, APIView):
"""
Auth verification endpoint for ``cargo login``.

Cargo calls GET /me after login to verify the token is valid.
See: https://doc.rust-lang.org/cargo/reference/registry-web-api.html
"""

authentication_classes = [CargoTokenAuthentication]
permission_classes = [IsAuthenticated]
renderer_classes = [JSONRenderer]

def get(self, request, **kwargs):
return HttpResponse(json.dumps({"ok": True}), content_type="application/json")


class CargoPublishApiView(APIView):
class CargoPublishApiView(CargoAuthMixin, APIView):
"""
View for Cargo's crate publish endpoint (PUT /api/v1/crates/new).

Expand All @@ -353,7 +371,6 @@ class CargoPublishApiView(APIView):
See: https://doc.rust-lang.org/cargo/reference/registry-web-api.html#publish
"""

authentication_classes = [CargoTokenAuthentication]
permission_classes = [IsAuthenticated]
renderer_classes = [JSONRenderer]

Expand Down Expand Up @@ -451,12 +468,11 @@ def put(self, request, **kwargs):
)


class CargoDownloadApiView(APIView):
class CargoDownloadApiView(CargoAuthMixin, APIView):
"""
View for Cargo's crate download, readme, yank, and unyank endpoints.
"""

authentication_classes = [CargoTokenAuthentication]
renderer_classes = [PlainTextRenderer, JSONRenderer]

def get_permissions(self):
Expand Down Expand Up @@ -489,6 +505,10 @@ def get(self, request, name, version, rest, **kwargs):
- api/v1/crates/{name}/{version}/readme - not yet implemented
"""
distro = self.get_distribution()
if not can_read_distribution(request, distro):
if request.user.is_authenticated:
raise PermissionDenied()
raise NotAuthenticated()

if rest == "download":
relative_path = f"{name}/{name}-{version}.crate"
Expand Down
Loading
Loading