From a15cb10b928c13093dc122380e07145cca24a220 Mon Sep 17 00:00:00 2001 From: pkriko Date: Tue, 17 Nov 2026 09:25:56 +0100 Subject: [PATCH] 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