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
17 changes: 11 additions & 6 deletions docs/user/guides/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,25 @@ 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-host>/pulp/api/v3/distributions/rust/rust/<uuid>/ \
-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.
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

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)
35 changes: 21 additions & 14 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,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,
Expand Down Expand Up @@ -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."""

Expand Down Expand Up @@ -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"
Expand All @@ -190,6 +202,7 @@ class CargoIndexApiViewSet(ApiMixin, ViewSet):
"action": ["retrieve"],
"principal": "*",
"effect": "allow",
"condition": "can_read_index",
},
],
}
Expand Down Expand Up @@ -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"
Expand All @@ -317,6 +330,7 @@ class IndexRoot(ApiMixin, ViewSet):
"action": ["retrieve"],
"principal": "*",
"effect": "allow",
"condition": "can_read_index",
},
],
}
Expand All @@ -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``.
Expand Down Expand Up @@ -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"
Expand Down
100 changes: 99 additions & 1 deletion pulp_rust/tests/functional/api/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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."""
Expand All @@ -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
Loading