From 700667a7383eebd5fd761f4abfd1ad490a090040 Mon Sep 17 00:00:00 2001 From: pkriko Date: Tue, 17 Nov 2026 09:04:08 +0100 Subject: [PATCH 1/2] Accept instance authenticators on Cargo endpoints The Cargo me, publish, yank and download views now try the Cargo token first, then the instance's default authentication classes, so clients can use the credentials the deployment is configured for (e.g. HTTP Basic) as well as `cargo login` tokens. Token scope checks only apply when the request is authenticated with a Cargo token. Add a cargo_auth_required boolean on the Rust distribution and use it for auth-required in the index config. The setting only controls whether Cargo sends its credential on index and download requests; it does not restrict access by itself. Assisted By: Claude Opus 5.5 Co-authored-by: baptiste --- docs/user/guides/authentication.md | 15 ++++ ...06_rustdistribution_cargo_auth_required.py | 16 ++++ pulp_rust/app/models.py | 1 + pulp_rust/app/serializers.py | 13 ++- pulp_rust/app/views.py | 27 ++++-- pulp_rust/tests/functional/api/test_auth.py | 82 +++++++++++++++++++ 6 files changed, 146 insertions(+), 8 deletions(-) create mode 100644 pulp_rust/app/migrations/0006_rustdistribution_cargo_auth_required.py diff --git a/docs/user/guides/authentication.md b/docs/user/guides/authentication.md index 8f8e2eb..f730827 100644 --- a/docs/user/guides/authentication.md +++ b/docs/user/guides/authentication.md @@ -37,6 +37,21 @@ 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. +### Sending Credentials on Every Request + +To make Cargo send its credential on index and download requests as well, enable +`cargo_auth_required` on the distribution. Pulp then advertises `auth-required: true` in the +index `config.json`: + +```bash +http PATCH http:///pulp/api/v3/distributions/rust/rust// \ + -a admin:password \ + cargo_auth_required:=true +``` + +This setting only controls what Cargo sends; it does not restrict access by itself. To protect +downloads, 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 diff --git a/pulp_rust/app/migrations/0006_rustdistribution_cargo_auth_required.py b/pulp_rust/app/migrations/0006_rustdistribution_cargo_auth_required.py new file mode 100644 index 0000000..6a7a6ca --- /dev/null +++ b/pulp_rust/app/migrations/0006_rustdistribution_cargo_auth_required.py @@ -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), + ), + ] diff --git a/pulp_rust/app/models.py b/pulp_rust/app/models.py index a4b00fa..ac59e63 100755 --- a/pulp_rust/app/models.py +++ b/pulp_rust/app/models.py @@ -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" diff --git a/pulp_rust/app/serializers.py b/pulp_rust/app/serializers.py index 88df2af..e9665de 100755 --- a/pulp_rust/app/serializers.py +++ b/pulp_rust/app/serializers.py @@ -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."), @@ -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 diff --git a/pulp_rust/app/views.py b/pulp_rust/app/views.py index 985b773..2f15b88 100644 --- a/pulp_rust/app/views.py +++ b/pulp_rust/app/views.py @@ -27,6 +27,7 @@ from pulp_rust.app.auth import CargoTokenAuthentication from pulp_rust.app.models import ( + RustCargoToken, RustContent, RustDistribution, RustPackageYank, @@ -86,6 +87,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) @@ -322,12 +327,23 @@ 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 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 CargoMeApiView(CargoAuthMixin, APIView): """ Auth verification endpoint for ``cargo login``. @@ -335,7 +351,6 @@ class CargoMeApiView(APIView): See: https://doc.rust-lang.org/cargo/reference/registry-web-api.html """ - authentication_classes = [CargoTokenAuthentication] permission_classes = [IsAuthenticated] renderer_classes = [JSONRenderer] @@ -343,7 +358,7 @@ 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). @@ -353,7 +368,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] @@ -451,12 +465,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): diff --git a/pulp_rust/tests/functional/api/test_auth.py b/pulp_rust/tests/functional/api/test_auth.py index b75ebdf..51d9224 100644 --- a/pulp_rust/tests/functional/api/test_auth.py +++ b/pulp_rust/tests/functional/api/test_auth.py @@ -1,5 +1,6 @@ """Tests for Cargo token authentication on Cargo API endpoints.""" +import base64 from urllib.parse import urljoin from pulp_rust.tests.functional.utils import ( @@ -267,3 +268,84 @@ def test_yank_requires_distribution_permission( # Now Alice can yank response = cargo_yank(base_url, "itoa", "1.0.0", headers=headers) assert response.status_code == 200 + + +# --- Non-Cargo-token authenticators (the instance's default auth stack) --- + + +def test_me_with_basic_auth_succeeds( + rust_repo_factory, + rust_distribution_factory, + cargo_registry_url, + gen_user, +): + """A non-Cargo credential (HTTP Basic) must authenticate too. + + The Cargo endpoints prepend the Cargo token to the instance's configured + authenticators instead of replacing them, so any deployment auth reaches them. + """ + repository = rust_repo_factory() + distribution = rust_distribution_factory(repository=repository.pulp_href) + base = cargo_registry_url(distribution.base_path) + + user = gen_user() + creds = base64.b64encode(f"{user.username}:{user.password}".encode()).decode() + + response = cargo_api_request( + "GET", urljoin(base, "me"), headers={"Authorization": f"Basic {creds}"} + ) + assert response.status_code == 200 + assert response.json()["ok"] is True + + +def test_yank_with_basic_auth_succeeds( + gen_user, + rust_distro_api_client, + populated_repo, +): + """Token scopes only apply to Cargo tokens, so a Basic-authenticated yank goes through.""" + alice = gen_user() + rust_distro_api_client.add_role( + populated_repo["distribution"].pulp_href, + {"role": "rust.rustdistribution_publisher", "users": [alice.username]}, + ) + creds = base64.b64encode(f"{alice.username}:{alice.password}".encode()).decode() + + response = cargo_yank( + populated_repo["base_url"], "itoa", "1.0.0", headers={"Authorization": f"Basic {creds}"} + ) + assert response.status_code == 200 + + +# --- config.json auth-required follows the distribution setting --- + + +def test_config_json_auth_required_false_by_default( + rust_repo_factory, + rust_distribution_factory, + cargo_registry_url, +): + """A distribution advertises auth-required: false unless configured otherwise.""" + repository = rust_repo_factory() + distribution = rust_distribution_factory(repository=repository.pulp_href) + config_url = urljoin(cargo_registry_url(distribution.base_path), "config.json") + + response = cargo_api_request("GET", config_url) + assert response.json()["auth-required"] is False + + +def test_config_json_auth_required_true_when_enabled( + rust_repo_factory, + rust_distribution_factory, + cargo_registry_url, +): + """cargo_auth_required makes cargo send its credential on index and download requests.""" + repository = rust_repo_factory() + distribution = rust_distribution_factory( + repository=repository.pulp_href, cargo_auth_required=True + ) + assert distribution.cargo_auth_required is True + config_url = urljoin(cargo_registry_url(distribution.base_path), "config.json") + + response = cargo_api_request("GET", config_url) + assert response.json()["auth-required"] is True From d9587e17ae796e9788f7aa76717372da658d70e4 Mon Sep 17 00:00:00 2001 From: pkriko Date: Tue, 17 Nov 2026 09:25:56 +0100 Subject: [PATCH 2/2] Reject anonymous reads of private Cargo registries When cargo_auth_required is set on a distribution, the index config.json, the sparse index files and the download endpoint now require the rust.view_rustdistribution permission on the distribution. Anonymous requests get a 401 with a "WWW-Authenticate: Cargo" challenge, so Cargo retries with its credential. A Cargo token scoped to other distributions cannot read this one. The index views now accept the same credentials as the other Cargo endpoints: the Cargo token first, then the instance's default authentication classes. The download endpoint redirects to the content app, which this does not cover; a content guard is still needed to protect the crate files. Assisted By: Claude Opus 5.5 --- docs/user/guides/authentication.md | 17 ++-- pulp_rust/app/auth.py | 2 +- pulp_rust/app/global_access_conditions.py | 23 +++++ pulp_rust/app/views.py | 35 ++++--- pulp_rust/tests/functional/api/test_auth.py | 100 +++++++++++++++++++- 5 files changed, 155 insertions(+), 22 deletions(-) diff --git a/docs/user/guides/authentication.md b/docs/user/guides/authentication.md index f730827..3ca3e9f 100644 --- a/docs/user/guides/authentication.md +++ b/docs/user/guides/authentication.md @@ -37,11 +37,9 @@ 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. -### Sending Credentials on Every Request +### Private Registries -To make Cargo send its credential on index and download requests as well, enable -`cargo_auth_required` on the distribution. Pulp then advertises `auth-required: true` in the -index `config.json`: +To make a registry private, enable `cargo_auth_required` on the distribution: ```bash http PATCH http:///pulp/api/v3/distributions/rust/rust// \ @@ -49,8 +47,15 @@ http PATCH http:///pulp/api/v3/distributions/rust/rust// \ cargo_auth_required:=true ``` -This setting only controls what Cargo sends; it does not restrict access by itself. To protect -downloads, also attach a content guard that accepts the credential Cargo sends. +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 diff --git a/pulp_rust/app/auth.py b/pulp_rust/app/auth.py index e00862c..0f10a37 100644 --- a/pulp_rust/app/auth.py +++ b/pulp_rust/app/auth.py @@ -26,4 +26,4 @@ def authenticate(self, request): return (cargo_token.user, cargo_token) def authenticate_header(self, request): - return "CargoToken" + return "Cargo" diff --git a/pulp_rust/app/global_access_conditions.py b/pulp_rust/app/global_access_conditions.py index 573eb11..6317f14 100644 --- a/pulp_rust/app/global_access_conditions.py +++ b/pulp_rust/app/global_access_conditions.py @@ -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.""" @@ -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) diff --git a/pulp_rust/app/views.py b/pulp_rust/app/views.py index 2f15b88..5bec56d 100644 --- a/pulp_rust/app/views.py +++ b/pulp_rust/app/views.py @@ -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 @@ -26,6 +26,7 @@ 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, @@ -111,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.""" @@ -180,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" @@ -190,6 +202,7 @@ class CargoIndexApiViewSet(ApiMixin, ViewSet): "action": ["retrieve"], "principal": "*", "effect": "allow", + "condition": "can_read_index", }, ], } @@ -307,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" @@ -317,6 +330,7 @@ class IndexRoot(ApiMixin, ViewSet): "action": ["retrieve"], "principal": "*", "effect": "allow", + "condition": "can_read_index", }, ], } @@ -332,17 +346,6 @@ def retrieve(self, request, repo): return HttpResponse(json.dumps(data), content_type="application/json") -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 CargoMeApiView(CargoAuthMixin, APIView): """ Auth verification endpoint for ``cargo login``. @@ -502,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" diff --git a/pulp_rust/tests/functional/api/test_auth.py b/pulp_rust/tests/functional/api/test_auth.py index 51d9224..d42f14b 100644 --- a/pulp_rust/tests/functional/api/test_auth.py +++ b/pulp_rust/tests/functional/api/test_auth.py @@ -3,6 +3,8 @@ import base64 from urllib.parse import urljoin +import pytest + from pulp_rust.tests.functional.utils import ( cargo_api_request, cargo_unyank, @@ -337,6 +339,8 @@ def test_config_json_auth_required_false_by_default( def test_config_json_auth_required_true_when_enabled( rust_repo_factory, rust_distribution_factory, + rust_token_factory, + pulp_admin_user, cargo_registry_url, ): """cargo_auth_required makes cargo send its credential on index and download requests.""" @@ -346,6 +350,100 @@ def test_config_json_auth_required_true_when_enabled( ) assert distribution.cargo_auth_required is True config_url = urljoin(cargo_registry_url(distribution.base_path), "config.json") + headers = {"Authorization": rust_token_factory(pulp_admin_user).token} - response = cargo_api_request("GET", config_url) + response = cargo_api_request("GET", config_url, headers=headers) assert response.json()["auth-required"] is True + + +# --- A distribution with cargo_auth_required rejects anonymous reads --- + + +@pytest.fixture +def private_repo(populated_repo, rust_distro_api_client, monitor_task): + """The populated repository, served by a distribution that requires authentication.""" + distribution = populated_repo["distribution"] + monitor_task( + rust_distro_api_client.partial_update( + distribution.pulp_href, {"cargo_auth_required": True} + ).task + ) + return populated_repo + + +PRIVATE_READ_PATHS = ["config.json", "it/oa/itoa", "api/v1/crates/itoa/1.0.0/download"] + + +@pytest.mark.parametrize("path", PRIVATE_READ_PATHS) +def test_private_distribution_rejects_anonymous_reads(private_repo, path): + """Cargo retries with its credential when it gets a 401 with a Cargo challenge.""" + response = cargo_api_request( + "GET", urljoin(private_repo["base_url"], path), allow_redirects=False + ) + assert response.status_code == 401 + assert response.headers["WWW-Authenticate"] == "Cargo" + + +@pytest.mark.parametrize("path", PRIVATE_READ_PATHS) +def test_private_distribution_requires_view_permission(private_repo, gen_user, path): + """An authenticated user without a role on the distribution cannot read it.""" + user = gen_user() + creds = base64.b64encode(f"{user.username}:{user.password}".encode()).decode() + + response = cargo_api_request( + "GET", + urljoin(private_repo["base_url"], path), + headers={"Authorization": f"Basic {creds}"}, + allow_redirects=False, + ) + assert response.status_code == 403 + + +@pytest.mark.parametrize("path", PRIVATE_READ_PATHS) +def test_private_distribution_allows_viewers( + private_repo, gen_user, rust_token_factory, rust_distro_api_client, path +): + """A Cargo token of a user with the viewer role can read the index and download crates.""" + user = gen_user() + rust_distro_api_client.add_role( + private_repo["distribution"].pulp_href, + {"role": "rust.rustdistribution_viewer", "users": [user.username]}, + ) + headers = {"Authorization": rust_token_factory(user).token} + + response = cargo_api_request( + "GET", urljoin(private_repo["base_url"], path), headers=headers, allow_redirects=False + ) + assert response.status_code in (200, 302) + + +@pytest.mark.parametrize("path", PRIVATE_READ_PATHS) +def test_private_distribution_honors_token_distribution_scope( + private_repo, + gen_user, + rust_repo_factory, + rust_distribution_factory, + rust_token_factory, + rust_distro_api_client, + path, +): + """A token scoped to another distribution cannot read this one, even for a viewer.""" + user = gen_user() + rust_distro_api_client.add_role( + private_repo["distribution"].pulp_href, + {"role": "rust.rustdistribution_viewer", "users": [user.username]}, + ) + other = rust_distribution_factory(repository=rust_repo_factory().pulp_href) + rust_distro_api_client.add_role( + other.pulp_href, + {"role": "rust.rustdistribution_viewer", "users": [user.username]}, + ) + token = rust_token_factory(user, distributions=[other.pulp_href]) + + response = cargo_api_request( + "GET", + urljoin(private_repo["base_url"], path), + headers={"Authorization": token.token}, + allow_redirects=False, + ) + assert response.status_code == 403