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