You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by ak...@apache.org on 2026/04/28 15:21:50 UTC
(tooling-trusted-releases) branch api-auth-decorators-1169 updated (dac78b80 -> 2b7eba03)
This is an automated email from the ASF dual-hosted git repository.
andrewmusselman pushed a change to branch api-auth-decorators-1169
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git
omit dac78b80 Validate Trusted Publisher tokens in @api.auth.body_oidc; add registry (#1169)
omit a948ff6d Consolidate Bearer JWT auth into @api.auth.bearer (#1169)
omit d31b9844 Add explicit auth level decorators for API endpoints (scaffolding, #1169)
add fe6b4ef5 Update dependencies
add 4934a5d2 Update rpgp-py to stop using a fork
add 9cc1dbbe Restore support for DSA keys
add 907c0e0a Improve the performance of the script to update all keys
new 77165e2d Add explicit auth level decorators for API endpoints (scaffolding, #1169)
new 13019d02 Consolidate Bearer JWT auth into @api.auth.bearer (#1169)
new 2b7eba03 Validate Trusted Publisher tokens in @api.auth.body_oidc; add registry (#1169)
This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version. This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:
* -- * -- B -- O -- O -- O (dac78b80)
\
N -- N -- N refs/heads/api-auth-decorators-1169 (2b7eba03)
You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.
Any revisions marked "omit" are not gone; other references still
refer to them. Any revisions marked "discard" are gone forever.
The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
atr/storage/writers/keys.py | 65 ++++++++++++++++++++++++++++--------------
pip-audit.requirements | 2 +-
pyproject.toml | 9 ------
scripts/keys_import.py | 2 +-
tests/unit/test_keys_writer.py | 47 ++++++++++++++++++++++++++++++
uv.lock | 27 ++++++++++--------
6 files changed, 107 insertions(+), 45 deletions(-)
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org
(tooling-trusted-releases) 01/03: Add explicit auth level decorators for API endpoints (scaffolding, #1169)
Posted by ak...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
andrewmusselman pushed a commit to branch api-auth-decorators-1169
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git
commit 77165e2d866f0672a385c72728c8f30f161c6f78
Author: Andrew K. Musselman <ak...@apache.org>
AuthorDate: Tue Apr 28 08:20:53 2026 -0700
Add explicit auth level decorators for API endpoints (scaffolding, #1169)
Adds a new atr.blueprints.api_auth module with four decorators that mark
the authentication level of every route:
@api.auth.public - no authentication required
@api.auth.bearer - ATR-issued Bearer JWT (Authorization header)
@api.auth.body_oidc - Trusted Publisher OIDC token in request body
@api.auth.pat - Personal Access Token in request body
In PR 1 these are pure markers: no behavioral change. Handlers that
currently use @jwtoken.require / trusted_jwt(...) / PAT exchange retain
those mechanisms unchanged.
The @api.typed decorator now requires an @api.auth.<level> decorator on
every route and raises TypeError at import time if one is missing. This
is the fail-closed property that #1169 asks for: a new route without an
explicit auth decorator cannot register.
All 46 existing API endpoints are marked with their correct level:
public 20
bearer 18
body_oidc 7
pat 1
A coverage test (tests/unit/test_api_auth_decorators.py) walks the
registered routes and asserts every one has a valid level, and that
typed() rejects routes with no marker.
PR 2 will fold @jwtoken.require and the BearerAuth security_scheme
into @api.auth.bearer. PR 3 will do the equivalent for body_oidc and
pat, and add a checked-in URL -> level registry for drift detection.
---
atr/api/__init__.py | 46 ++++++++++++
atr/blueprints/api.py | 49 +++++++++++++
atr/blueprints/api_auth.py | 120 +++++++++++++++++++++++++++++++
tests/unit/test_api_auth_decorators.py | 128 +++++++++++++++++++++++++++++++++
4 files changed, 343 insertions(+)
diff --git a/atr/api/__init__.py b/atr/api/__init__.py
index 85c0702a..53c221e7 100644
--- a/atr/api/__init__.py
+++ b/atr/api/__init__.py
@@ -62,6 +62,7 @@ ROUTES_MODULE: Final[Literal[True]] = True
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ChecksListResults, 200)
async def checks_list(
_checks_list: Literal["checks/list"],
@@ -96,6 +97,7 @@ async def checks_list(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ChecksListResults, 200)
async def checks_list_revision(
_checks_list: Literal["checks/list"],
@@ -137,6 +139,7 @@ async def checks_list_revision(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ChecksOngoingResults, 200)
async def checks_ongoing(
_checks_ongoing: Literal["checks/ongoing"],
@@ -175,6 +178,7 @@ async def checks_ongoing(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.CommitteeGetResults, 200)
async def committee_get(
_committee_get: Literal["committee/get"],
@@ -201,6 +205,7 @@ async def committee_get(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.CommitteeKeysResults, 200)
async def committee_keys(
_committee_keys: Literal["committee/keys"],
@@ -227,6 +232,7 @@ async def committee_keys(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.CommitteeProjectsResults, 200)
async def committee_projects(
_committee_projects: Literal["committee/projects"],
@@ -253,6 +259,7 @@ async def committee_projects(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.CommitteesListResults, 200)
async def committees_list(
_committees_list: Literal["committees/list"],
@@ -274,6 +281,7 @@ async def committees_list(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.body_oidc
async def distribute_ssh_register(
_distribute_ssh_register: Literal["distribute/ssh/register"],
data: models.api.DistributeSshRegisterArgs,
@@ -315,6 +323,7 @@ async def distribute_ssh_register(
@api.typed
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.DistributionRecordResults, 200)
@@ -360,6 +369,7 @@ async def distribution_record(
@api.typed
+@api.auth.body_oidc
async def distribution_record_from_workflow(
_distribute_record_from_workflow: Literal["distribute/record_from_workflow"],
data: models.api.DistributionRecordFromWorkflowArgs,
@@ -409,6 +419,7 @@ async def distribution_record_from_workflow(
@api.typed
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.IgnoreAddResults, 200)
@@ -443,6 +454,7 @@ async def ignore_add(
@api.typed
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.IgnoreDeleteResults, 200)
@@ -471,6 +483,7 @@ async def ignore_delete(
# TODO: Rename to ignores
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.IgnoreListResults, 200)
async def ignore_list(
_ignore_list: Literal["ignore/list"],
@@ -492,6 +505,7 @@ async def ignore_list(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.pat
async def jwt_create(
_jwt_create: Literal["jwt/create"],
data: models.api.JwtCreateArgs,
@@ -520,6 +534,7 @@ async def jwt_create(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.KeyAddResults, 200)
@@ -558,6 +573,7 @@ async def key_add(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.KeyDeleteResults, 200)
@@ -597,6 +613,7 @@ async def key_delete(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.public
@quart_schema.validate_response(models.api.KeyGetResults, 200)
async def key_get(
_key_get: Literal["key/get"],
@@ -621,6 +638,7 @@ async def key_get(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.KeysUploadResults, 200)
@@ -683,6 +701,7 @@ async def keys_upload(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.public
@quart_schema.validate_response(models.api.KeysUserResults, 200)
async def keys_user(
_keys_user: Literal["keys/user"],
@@ -702,6 +721,7 @@ async def keys_user(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.PolicyGetResults, 200)
async def policy_get(
_policy_get: Literal["policy/get"],
@@ -744,6 +764,7 @@ async def policy_get(
@api.typed
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.PolicyUpdateResults, 200)
@@ -771,6 +792,7 @@ async def policy_update(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ProjectGetResults, 200)
async def project_get(
_project_get: Literal["project/get"],
@@ -790,6 +812,7 @@ async def project_get(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ProjectReleasesResults, 200)
async def project_releases(
_project_releases: Literal["project/releases"],
@@ -810,6 +833,7 @@ async def project_releases(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ProjectsListResults, 200)
async def projects_list(
_projects_list: Literal["projects/list"],
@@ -829,6 +853,7 @@ async def projects_list(
@api.typed
+@api.auth.body_oidc
async def publisher_distribution_record(
_publisher_distribution_record: Literal["publisher/distribution/record"],
data: models.api.PublisherDistributionRecordArgs,
@@ -881,6 +906,7 @@ async def publisher_distribution_record(
@api.typed
+@api.auth.body_oidc
async def publisher_release_announce(
_publisher_release_announce: Literal["publisher/release/announce"],
data: models.api.PublisherReleaseAnnounceArgs,
@@ -919,6 +945,7 @@ async def publisher_release_announce(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.body_oidc
async def publisher_ssh_register(
_publisher_ssh_register: Literal["publisher/ssh/register"],
data: models.api.PublisherSshRegisterArgs,
@@ -949,6 +976,7 @@ async def publisher_ssh_register(
@api.typed
+@api.auth.body_oidc
async def publisher_vote_resolve(
_publisher_vote_resolve: Literal["publisher/vote/resolve"],
data: models.api.PublisherVoteResolveArgs,
@@ -986,6 +1014,7 @@ async def publisher_vote_resolve(
@api.typed
@rate_limiter.rate_limit(5, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.ReleaseAnnounceResults, 201)
@@ -1028,6 +1057,7 @@ async def release_announce(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.ReleaseCreateResults, 201)
@@ -1059,6 +1089,7 @@ async def release_create(
# TODO: Duplicates the below
@api.typed
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.ReleaseDeleteResults, 200)
@@ -1088,6 +1119,7 @@ async def release_delete(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ReleaseGetResults, 200)
async def release_get(
_release_get: Literal["release/get"],
@@ -1109,6 +1141,7 @@ async def release_get(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ReleasePathsResults, 200)
async def release_paths(
_release_paths: Literal["release/paths"],
@@ -1140,6 +1173,7 @@ async def release_paths(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ReleaseRevisionsResults, 200)
async def release_revisions(
_release_revisions: Literal["release/revisions"],
@@ -1164,6 +1198,7 @@ async def release_revisions(
@api.typed
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.ReleaseUploadResults, 201)
@@ -1205,6 +1240,7 @@ async def release_upload(
@api.typed
+@api.auth.public
@quart_schema.validate_response(models.api.ReleasesListResults, 200)
async def releases_list(
_releases_list: Literal["releases/list"],
@@ -1255,6 +1291,7 @@ async def releases_list(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.SignatureProvenanceResults, 200)
@@ -1329,6 +1366,7 @@ async def signature_provenance(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.SshKeyAddResults, 201)
@@ -1355,6 +1393,7 @@ async def ssh_key_add(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.SshKeyDeleteResults, 201)
@@ -1381,6 +1420,7 @@ async def ssh_key_delete(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.public
async def ssh_keys_list(
_ssh_keys_list: Literal["ssh-keys/list"],
asf_uid: unsafe.UnsafeStr,
@@ -1417,6 +1457,7 @@ async def ssh_keys_list(
@api.typed
+@api.auth.body_oidc
async def update_distribution_task_status(
_distribute_task_status: Literal["distribute/task/status"],
data: models.api.DistributeStatusUpdateArgs,
@@ -1448,6 +1489,7 @@ async def update_distribution_task_status(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.UserInfoResults, 200)
@@ -1472,6 +1514,7 @@ async def user_info(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.public
@quart_schema.validate_response(models.api.UsersListResults, 200)
async def users_list(
_users_list: Literal["users/list"],
@@ -1515,6 +1558,7 @@ async def users_list(
# TODO: Add endpoints to allow users to vote
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.VoteResolveResults, 200)
@@ -1558,6 +1602,7 @@ async def vote_resolve(
@api.typed
@rate_limiter.rate_limit(5, datetime.timedelta(hours=1))
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.VoteStartResults, 201)
@@ -1617,6 +1662,7 @@ async def vote_start(
@api.typed
+@api.auth.bearer
@jwtoken.require
@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.VoteTabulateResults, 200)
diff --git a/atr/blueprints/api.py b/atr/blueprints/api.py
index bfd129ed..06116d98 100644
--- a/atr/blueprints/api.py
+++ b/atr/blueprints/api.py
@@ -30,11 +30,16 @@ import quart_rate_limiter as rate_limiter
import quart_schema
import werkzeug.exceptions as exceptions
+import atr.blueprints.api_auth as auth
import atr.blueprints.common as common
import atr.config as config
import atr.log as log
import atr.web as web
+# Re-export so routes can write `@api.auth.public` etc. (matches #1169).
+# We also keep `auth` importable as a plain attribute for tests.
+__all__ = ["auth", "register", "typed"]
+
_BLUEPRINT_NAME: Final = "api_blueprint"
_BLUEPRINT: Final = quart.Blueprint(_BLUEPRINT_NAME, __name__, url_prefix="/api")
_routes: list[str] = []
@@ -47,6 +52,19 @@ def register(app: base.QuartApp) -> tuple[ModuleType, list[str]]:
return api, _routes
+# Registry of (function name -> auth level) captured at import time.
+# Populated by typed() and consumed by tests/unit/test_api_auth_decorators.py.
+_route_auth_levels: dict[str, auth.AuthLevel] = {}
+
+
+def route_auth_levels() -> dict[str, auth.AuthLevel]:
+ """Return a snapshot of the registered (route function name -> auth level) map.
+
+ A copy is returned so callers cannot mutate the registry.
+ """
+ return dict(_route_auth_levels)
+
+
def typed(func: Callable[..., Awaitable[Any]]) -> web.RouteFunction[Any]:
"""Decorator that derives the URL path from the function's type annotations.
@@ -57,8 +75,16 @@ def typed(func: Callable[..., Awaitable[Any]]) -> web.RouteFunction[Any]:
- str | None parameters create optional URL segments (two routes registered)
- int, float use Quart's built-in type converters
- HTTP method is POST if a body param is present, GET otherwise
+
+ Every route decorated with this function must also declare its
+ authentication level via exactly one of the decorators in
+ :mod:`atr.blueprints.api_auth` (``@api.auth.public``, ``@api.auth.bearer``,
+ ``@api.auth.body_oidc``, or ``@api.auth.pat``). This is enforced at
+ import time: forgetting the decorator raises :class:`TypeError` and
+ the server will not start.
"""
original = inspect.unwrap(func)
+ _require_auth_level(func, original)
path, validated_params, literal_params, body_param, _, query_param, optional_params = common.build_api_path(
original
)
@@ -199,6 +225,29 @@ def _json_error(
return quart.jsonify(payload), status_code or 500
+def _require_auth_level(func: Callable[..., Any], original: Callable[..., Any]) -> auth.AuthLevel:
+ """Fail import if ``original`` has no ``@api.auth.<level>`` decorator.
+
+ Returns the detected level and records it in the module-level registry.
+ Looks at both the wrapped and unwrapped callables because ``@api.auth.bearer``
+ returns a wrapper, while ``@api.auth.public`` returns the function itself.
+ """
+ level = getattr(func, auth.AUTH_LEVEL_ATTR, None) or getattr(original, auth.AUTH_LEVEL_ATTR, None)
+ if level is None:
+ raise TypeError(
+ f"API route {original.__name__!r} in {original.__module__} is missing "
+ "an auth decorator. Apply exactly one of @api.auth.public, "
+ "@api.auth.bearer, @api.auth.body_oidc, or @api.auth.pat. "
+ "See atr/blueprints/api_auth.py for details."
+ )
+ if level not in auth.VALID_LEVELS:
+ raise TypeError(
+ f"API route {original.__name__!r}: unknown auth level {level!r}. Valid levels: {sorted(auth.VALID_LEVELS)}"
+ )
+ _route_auth_levels[original.__name__] = level
+ return level
+
+
@_BLUEPRINT.record_once
def _setup(state: blueprints.BlueprintSetupState) -> None:
if isinstance(state.app, base.QuartApp):
diff --git a/atr/blueprints/api_auth.py b/atr/blueprints/api_auth.py
new file mode 100644
index 00000000..9017dec6
--- /dev/null
+++ b/atr/blueprints/api_auth.py
@@ -0,0 +1,120 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Explicit authentication level decorators for API endpoints.
+
+Every route decorated with :func:`atr.blueprints.api.typed` must also be
+decorated with exactly one of the auth level decorators in this module.
+The :func:`atr.blueprints.api.typed` decorator enforces this at import
+time; forgetting the decorator raises :class:`TypeError` and the server
+will not start.
+
+Usage::
+
+ @api.typed
+ @api.auth.bearer
+ @quart_schema.validate_response(models.api.FooResults, 200)
+ async def foo(...):
+ ...
+
+Decorator order: ``@api.typed`` on the outside, then ``@api.auth.<level>``,
+then any ``@quart_schema`` or ``@rate_limiter`` decorators closer to the
+function.
+
+The levels are:
+
+- ``public`` No authentication. Route may be called by anyone.
+- ``bearer`` ATR-issued JWT in an ``Authorization: Bearer ...`` header.
+- ``body_oidc`` Trusted Publisher OIDC token carried in the request body.
+- ``pat`` Personal Access Token in the request body, exchanged for a JWT.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Final, Literal
+
+if TYPE_CHECKING:
+ from collections.abc import Awaitable, Callable
+ from typing import Any
+
+
+AuthLevel = Literal["public", "bearer", "body_oidc", "pat"]
+
+# Public name so external tests and the typed() enforcer agree.
+AUTH_LEVEL_ATTR: Final[str] = "_api_auth_level"
+
+VALID_LEVELS: Final[frozenset[AuthLevel]] = frozenset({"public", "bearer", "body_oidc", "pat"})
+
+
+def bearer[F: Callable[..., Awaitable[Any]]](func: F) -> F:
+ """Marker for routes authenticated by an ATR-issued Bearer JWT.
+
+ PR 1: marker only. Handlers still declare ``@jwtoken.require`` and
+ ``@quart_schema.security_scheme([{"BearerAuth": []}])`` explicitly.
+ PR 2 folds both of those into this decorator and removes the duplicate
+ stack across the ~18 bearer endpoints.
+ """
+ return _mark("bearer", func)
+
+
+def body_oidc[F: Callable[..., Awaitable[Any]]](func: F) -> F:
+ """Marker for routes authenticated by a Trusted Publisher OIDC token in the body.
+
+ PR 1: marker only. The handler still calls ``interaction.trusted_jwt(...)``
+ or ``interaction.validate_trusted_jwt(...)`` itself. PR 3 moves the
+ validation into the decorator.
+ """
+ return _mark("body_oidc", func)
+
+
+def pat[F: Callable[..., Awaitable[Any]]](func: F) -> F:
+ """Marker for routes that accept a Personal Access Token in the body.
+
+ PR 1: marker only. Currently applies to ``jwt_create`` only, which
+ exchanges a PAT for an ATR-issued JWT. PR 3 may move the PAT validation
+ into the decorator once we have a second caller to design against.
+ """
+ return _mark("pat", func)
+
+
+def public[F: Callable[..., Awaitable[Any]]](func: F) -> F:
+ """Mark an API route as public (no authentication required).
+
+ This is a marker only: it has no runtime effect. Its purpose is to
+ make "this route is intentionally public" a visible, grep-able,
+ diffable statement in the source, and to let the import-time enforcer
+ in ``typed()`` tell the difference between "intentionally public" and
+ "someone forgot to add an auth decorator".
+ """
+ return _mark("public", func)
+
+
+def _mark[F: Callable[..., Any]](level: AuthLevel, func: F) -> F:
+ """Attach the auth-level sentinel to ``func``.
+
+ Raises TypeError if ``func`` has already been marked with a different
+ level (i.e. someone stacked two auth decorators).
+ """
+ existing = getattr(func, AUTH_LEVEL_ATTR, None)
+ if (existing is not None) and (existing != level):
+ raise TypeError(
+ f"{getattr(func, '__name__', func)!r}: cannot apply "
+ f"@api.auth.{level} on top of @api.auth.{existing}. "
+ "A route may declare exactly one auth level."
+ )
+ setattr(func, AUTH_LEVEL_ATTR, level)
+ return func
diff --git a/tests/unit/test_api_auth_decorators.py b/tests/unit/test_api_auth_decorators.py
new file mode 100644
index 00000000..08b234c3
--- /dev/null
+++ b/tests/unit/test_api_auth_decorators.py
@@ -0,0 +1,128 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Tests that every API route declares an explicit authentication level.
+
+See issue #1169. These tests are the enforcement mechanism for the
+"fail-closed" property: a new route that forgets an auth decorator
+either fails to import (the ``typed()`` enforcer) or fails this test
+(the coverage assertion).
+"""
+
+from typing import Literal
+
+import pytest
+
+import atr.blueprints.api as api_blueprint
+import atr.blueprints.api_auth as api_auth
+
+
+def test_every_api_route_has_an_auth_level() -> None:
+ """Every function registered via @api.typed must carry an auth level.
+
+ This is the coverage test. If it fails, some route somewhere in
+ ``atr/api/__init__.py`` is missing an ``@api.auth.<level>`` decorator.
+ (The ``typed()`` decorator also catches this at import time, so a
+ failure here usually means a bug in the enforcer itself or in the
+ ordering of decorators.)
+ """
+ # Importing atr.api triggers registration of every route.
+ import atr.api # noqa: F401
+
+ levels = api_blueprint.route_auth_levels()
+ assert levels, "no API routes were registered; did atr.api fail to import?"
+
+ invalid = {name: lvl for name, lvl in levels.items() if lvl not in api_auth.VALID_LEVELS}
+ assert not invalid, f"routes with invalid auth level: {invalid}"
+
+
+def test_typed_rejects_route_without_auth_decorator() -> None:
+ """A route missing any ``@api.auth.*`` decorator must fail at import time.
+
+ This is the fail-closed guarantee. A developer adding a new endpoint
+ and forgetting the auth decorator gets a TypeError from ``typed()``
+ before the server can even start.
+ """
+
+ # Minimal stand-in for a real route. No auth decorator applied.
+ async def fake_route(_fake: Literal["fake"]) -> tuple[dict, int]:
+ return {}, 200
+
+ with pytest.raises(TypeError, match="missing an auth decorator"):
+ api_blueprint.typed(fake_route)
+
+
+def test_typed_accepts_route_with_each_auth_level() -> None:
+ """Each of the four auth levels must satisfy ``typed()``'s check."""
+ for level in ("public", "bearer", "body_oidc", "pat"):
+
+ async def fake_route(_fake: Literal["fake"]) -> tuple[dict, int]:
+ return {}, 200
+
+ decorator = getattr(api_auth, level)
+ marked = decorator(fake_route)
+ # typed() does more than just the auth check (URL rule registration,
+ # etc.), so we can't call it here without a full Quart app context.
+ # But we can confirm the marker attribute made it through, which is
+ # what typed() keys off.
+ assert getattr(marked, api_auth.AUTH_LEVEL_ATTR, None) == level, (
+ f"@api.auth.{level} did not set {api_auth.AUTH_LEVEL_ATTR!r}"
+ )
+
+
+def test_auth_levels_cannot_be_stacked() -> None:
+ """Applying two different auth decorators to the same route must fail."""
+
+ async def fake_route(_fake: Literal["fake"]) -> tuple[dict, int]:
+ return {}, 200
+
+ marked = api_auth.public(fake_route)
+ with pytest.raises(TypeError, match=r"cannot apply @api\.auth"):
+ api_auth.bearer(marked)
+
+
+def test_applying_same_auth_level_twice_is_idempotent() -> None:
+ """Re-applying the same level must not raise; it's a harmless no-op."""
+
+ async def fake_route(_fake: Literal["fake"]) -> tuple[dict, int]:
+ return {}, 200
+
+ first = api_auth.public(fake_route)
+ second = api_auth.public(first)
+ assert getattr(second, api_auth.AUTH_LEVEL_ATTR) == "public"
+
+
+def test_expected_level_distribution() -> None:
+ """Sanity check: the headline counts from the #1169 audit hold.
+
+ 18 bearer, 7 body_oidc, 1 pat, 20 public = 46 total.
+
+ Not meant as a rigid drift check (that's PR 3's registry file), but a
+ heads-up that catches obvious regressions like "the PAT endpoint
+ accidentally got marked public".
+ """
+ import atr.api # noqa: F401
+
+ levels = api_blueprint.route_auth_levels()
+ counts = {lvl: 0 for lvl in api_auth.VALID_LEVELS}
+ for lvl in levels.values():
+ counts[lvl] += 1
+
+ assert counts["pat"] == 1, f"expected exactly one @api.auth.pat route, got {counts['pat']}"
+ assert counts["bearer"] >= 15, f"bearer count dropped unexpectedly: {counts['bearer']}"
+ assert counts["body_oidc"] >= 5, f"body_oidc count dropped unexpectedly: {counts['body_oidc']}"
+ assert sum(counts.values()) >= 40, f"total route count dropped unexpectedly: {counts}"
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org
(tooling-trusted-releases) 02/03: Consolidate Bearer JWT auth into @api.auth.bearer (#1169)
Posted by ak...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
andrewmusselman pushed a commit to branch api-auth-decorators-1169
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git
commit 13019d0214a6a58167bae9a66f877704c1e364a5
Author: Andrew K. Musselman <ak...@apache.org>
AuthorDate: Tue Apr 28 08:20:54 2026 -0700
Consolidate Bearer JWT auth into @api.auth.bearer (#1169)
Builds on the scaffolding in the previous commit: @api.auth.bearer now
applies both jwtoken.require and the BearerAuth OpenAPI security scheme
itself, so every bearer endpoint can drop two redundant decorators.
Across 18 endpoints:
@jwtoken.require -> removed
@quart_schema.security_scheme([{'BearerAuth': []}]) -> removed
Also drops the now-unused 'import atr.jwtoken' at the top of
atr/api/__init__.py (the _jwt_asf_uid helper reads claims from
quart.g.jwt_claims, which is populated by jwtoken.require itself).
No behavioral change: every bearer endpoint still requires a valid
Authorization: Bearer <jwt> header, and the generated OpenAPI document
still advertises the scheme. The difference is that both facts are now
declared by a single decorator per route.
---
atr/api/__init__.py | 37 -------------------------------------
atr/blueprints/api_auth.py | 32 ++++++++++++++++++++++++--------
2 files changed, 24 insertions(+), 45 deletions(-)
diff --git a/atr/api/__init__.py b/atr/api/__init__.py
index 53c221e7..210f623e 100644
--- a/atr/api/__init__.py
+++ b/atr/api/__init__.py
@@ -33,7 +33,6 @@ import atr.config as config
import atr.db as db
import atr.db.interaction as interaction
import atr.hashes as hashes
-import atr.jwtoken as jwtoken
import atr.log as log
import atr.models as models
import atr.models.safe as safe
@@ -324,8 +323,6 @@ async def distribute_ssh_register(
@api.typed
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.DistributionRecordResults, 200)
async def distribution_record(
_distribution_record: Literal["distribution/record"],
@@ -420,8 +417,6 @@ async def distribution_record_from_workflow(
@api.typed
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.IgnoreAddResults, 200)
async def ignore_add(
_ignore_add: Literal["ignore/add"],
@@ -455,8 +450,6 @@ async def ignore_add(
@api.typed
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.IgnoreDeleteResults, 200)
async def ignore_delete(
_ignore_delete: Literal["ignore/delete"],
@@ -535,8 +528,6 @@ async def jwt_create(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.KeyAddResults, 200)
async def key_add(
_key_add: Literal["key/add"],
@@ -574,8 +565,6 @@ async def key_add(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.KeyDeleteResults, 200)
async def key_delete(
_key_delete: Literal["key/delete"],
@@ -639,8 +628,6 @@ async def key_get(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.KeysUploadResults, 200)
async def keys_upload(
_keys_upload: Literal["keys/upload"],
@@ -765,8 +752,6 @@ async def policy_get(
@api.typed
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.PolicyUpdateResults, 200)
async def policy_update(
_policy_update: Literal["policy/update"],
@@ -1015,8 +1000,6 @@ async def publisher_vote_resolve(
@api.typed
@rate_limiter.rate_limit(5, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.ReleaseAnnounceResults, 201)
async def release_announce(
_release_announce: Literal["release/announce"],
@@ -1058,8 +1041,6 @@ async def release_announce(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.ReleaseCreateResults, 201)
async def release_create(
_release_create: Literal["release/create"],
@@ -1090,8 +1071,6 @@ async def release_create(
# TODO: Duplicates the below
@api.typed
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.ReleaseDeleteResults, 200)
async def release_delete(
_release_delete: Literal["release/delete"],
@@ -1199,8 +1178,6 @@ async def release_revisions(
@api.typed
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.ReleaseUploadResults, 201)
async def release_upload(
_release_upload: Literal["release/upload"],
@@ -1292,8 +1269,6 @@ async def releases_list(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.SignatureProvenanceResults, 200)
async def signature_provenance(
_signature_provenance: Literal["signature/provenance"],
@@ -1367,8 +1342,6 @@ async def signature_provenance(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.SshKeyAddResults, 201)
async def ssh_key_add(
_ssh_key_add: Literal["ssh-key/add"],
@@ -1394,8 +1367,6 @@ async def ssh_key_add(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.SshKeyDeleteResults, 201)
async def ssh_key_delete(
_ssh_key_delete: Literal["ssh-key/delete"],
@@ -1490,8 +1461,6 @@ async def update_distribution_task_status(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.UserInfoResults, 200)
async def user_info(
_user_info: Literal["user/info"],
@@ -1559,8 +1528,6 @@ async def users_list(
@api.typed
@rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.VoteResolveResults, 200)
async def vote_resolve(
_vote_resolve: Literal["vote/resolve"],
@@ -1603,8 +1570,6 @@ async def vote_resolve(
@api.typed
@rate_limiter.rate_limit(5, datetime.timedelta(hours=1))
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.VoteStartResults, 201)
async def vote_start(
_vote_start: Literal["vote/start"],
@@ -1663,8 +1628,6 @@ async def vote_start(
@api.typed
@api.auth.bearer
-@jwtoken.require
-@quart_schema.security_scheme([{"BearerAuth": []}])
@quart_schema.validate_response(models.api.VoteTabulateResults, 200)
async def vote_tabulate(
_vote_tabulate: Literal["vote/tabulate"],
diff --git a/atr/blueprints/api_auth.py b/atr/blueprints/api_auth.py
index 9017dec6..7d4a746a 100644
--- a/atr/blueprints/api_auth.py
+++ b/atr/blueprints/api_auth.py
@@ -47,8 +47,12 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Final, Literal
+import quart_schema
+
+import atr.jwtoken as jwtoken
+
if TYPE_CHECKING:
- from collections.abc import Awaitable, Callable
+ from collections.abc import Awaitable, Callable, Coroutine
from typing import Any
@@ -60,15 +64,27 @@ AUTH_LEVEL_ATTR: Final[str] = "_api_auth_level"
VALID_LEVELS: Final[frozenset[AuthLevel]] = frozenset({"public", "bearer", "body_oidc", "pat"})
-def bearer[F: Callable[..., Awaitable[Any]]](func: F) -> F:
- """Marker for routes authenticated by an ATR-issued Bearer JWT.
+def bearer[**P, R](
+ func: Callable[P, Coroutine[Any, Any, R]],
+) -> Callable[P, Awaitable[R]]:
+ """Require an ATR-issued Bearer JWT in the ``Authorization`` header.
+
+ Folds in two concerns that previously had to be declared separately
+ on every bearer endpoint:
+
+ 1. ``@jwtoken.require`` — validates the JWT and populates
+ ``quart.g.jwt_claims`` so handlers can read the caller's identity
+ via ``_jwt_asf_uid()``.
+ 2. ``@quart_schema.security_scheme([{"BearerAuth": []}])`` — advertises
+ the scheme in the generated OpenAPI document.
- PR 1: marker only. Handlers still declare ``@jwtoken.require`` and
- ``@quart_schema.security_scheme([{"BearerAuth": []}])`` explicitly.
- PR 2 folds both of those into this decorator and removes the duplicate
- stack across the ~18 bearer endpoints.
+ The auth-level marker is applied to the outermost wrapper so
+ :func:`atr.blueprints.api.typed` can read it back.
"""
- return _mark("bearer", func)
+ wrapped = jwtoken.require(func)
+ wrapped = quart_schema.security_scheme([{"BearerAuth": []}])(wrapped)
+ _mark("bearer", wrapped)
+ return wrapped
def body_oidc[F: Callable[..., Awaitable[Any]]](func: F) -> F:
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org
(tooling-trusted-releases) 03/03: Validate Trusted Publisher tokens in @api.auth.body_oidc; add registry (#1169)
Posted by ak...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
andrewmusselman pushed a commit to branch api-auth-decorators-1169
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git
commit 2b7eba03e72404ba03ee597e8986c516d52f1a7f
Author: Andrew K. Musselman <ak...@apache.org>
AuthorDate: Tue Apr 28 08:20:54 2026 -0700
Validate Trusted Publisher tokens in @api.auth.body_oidc; add registry (#1169)
Third and final commit for #1169. The @api.auth.body_oidc decorator now
validates the Trusted Publisher OIDC token from the request body before
the handler runs, and exposes the verified state via a frozen
TrustedPublisherContext dataclass at api.auth.trusted_publisher_context().
Changes:
1. atr/blueprints/api_auth.py
- body_oidc pre-validates via interaction.validate_trusted_jwt().
- TrustedPublisherContext carries the verified payload and the resolved
asf_uid (None when the token is for the trusted role, not a user).
- Advertises a TrustedPublisherJwt security scheme in the OpenAPI doc.
- pat is documented as an intentional marker: the only consumer,
jwt_create, is the PAT exchange endpoint itself, so moving the check
into a decorator would duplicate storage-layer logic.
2. atr/db/interaction.py
- New trusted_project_for_payload() and trusted_release_for_payload()
helpers that take an already-verified payload and do only the phase
and project lookup. The existing trusted_jwt() and trusted_jwt_for_dist()
are preserved and now delegate to the shared _trusted_dist_lookup().
3. atr/api/__init__.py
- All 7 body_oidc handlers migrated off direct JWT re-verification.
Zero calls to interaction.trusted_jwt* remain in the API module.
- publisher_ssh_register, publisher_vote_resolve,
publisher_release_announce, publisher_distribution_record now use
trusted_project_for_payload.
- distribute_ssh_register, distribution_record_from_workflow use
trusted_release_for_payload.
- update_distribution_task_status reads ctx.asf_uid directly.
4. tests/unit/api_auth_registry.yaml
- Canonical URL -> auth level registry for all 46 API endpoints.
Changes to this file are security-relevant and require review.
5. tests/unit/test_api_auth_decorators.py (18 tests total)
- test_api_auth_registry_matches_live_routes: drift test; the live
Quart url map must equal the registry.
- Behavioral tests: 200 for public, 401 for bearer, 400/401 for
body_oidc with a bogus token.
- Context handoff tests: body_oidc populates quart.g.tp_context on
success; trusted_publisher_context() raises when called outside a
decorated handler; body_oidc refuses a handler with no 'data' kwarg
or a body lacking 'publisher'/'jwt' fields.
- interaction helper tests: trusted_project_for_payload refuses a
payload with no ASF UID; trusted_release_for_payload refuses a
per-user token; both happy paths delegate correctly to the lower-
level lookups (stubbed, so no DB needed).
6. docs/authentication-security.html
- Updated the Token handling section to describe the four auth
decorator levels and the registry drift test.
---
atr/api/__init__.py | 53 ++--
atr/blueprints/api_auth.py | 112 +++++++-
atr/db/interaction.py | 77 ++++--
tests/unit/api_auth_registry.yaml | 70 +++++
tests/unit/test_api_auth_decorators.py | 454 ++++++++++++++++++++++++++++++++-
5 files changed, 720 insertions(+), 46 deletions(-)
diff --git a/atr/api/__init__.py b/atr/api/__init__.py
index 210f623e..da0f67a8 100644
--- a/atr/api/__init__.py
+++ b/atr/api/__init__.py
@@ -291,14 +291,16 @@ async def distribute_ssh_register(
Register an SSH key sent with a corroborating Trusted Publisher JWT,
validating the requested release is in the correct phase.
"""
- payload, asf_uid, project, release = await interaction.trusted_jwt_for_dist(
- data.publisher,
- data.jwt,
+ ctx = api.auth.trusted_publisher_context()
+ project, release = await interaction.trusted_release_for_payload(
+ ctx.asf_uid,
data.asf_uid,
interaction.TrustedProjectPhase(data.phase),
data.project_key,
data.version,
)
+ asf_uid = data.asf_uid
+ payload = ctx.payload
# Validate that the task ID passed exists and was started by the UID asserted
async with db.session() as _data:
await _data.task(id=int(data.task_id), asf_uid=data.asf_uid).demand(
@@ -378,9 +380,9 @@ async def distribution_record_from_workflow(
Validates the caller is a Github workflow, triggered by ATR itself
"""
- _payload, _asf_uid, _project, release = await interaction.trusted_jwt_for_dist(
- data.publisher,
- data.jwt,
+ ctx = api.auth.trusted_publisher_context()
+ _project, release = await interaction.trusted_release_for_payload(
+ ctx.asf_uid,
data.asf_uid,
interaction.TrustedProjectPhase(data.phase),
data.project,
@@ -848,17 +850,18 @@ async def publisher_distribution_record(
Record a distribution with a corroborating Trusted Publisher JWT.
"""
+ ctx = api.auth.trusted_publisher_context()
try:
- _payload, asf_uid, project = await interaction.trusted_jwt(
- data.publisher,
- data.jwt,
+ asf_uid, project = await interaction.trusted_project_for_payload(
+ ctx.payload,
+ ctx.asf_uid,
interaction.TrustedProjectPhase.FINISH,
)
except interaction.ReleasePolicyNotFoundError:
# TODO: We could perform a more advanced query with multiple in_ statements
- _payload, asf_uid, project = await interaction.trusted_jwt(
- data.publisher,
- data.jwt,
+ asf_uid, project = await interaction.trusted_project_for_payload(
+ ctx.payload,
+ ctx.asf_uid,
interaction.TrustedProjectPhase.COMPOSE,
)
util.validate_distribution_owner_namespace(data.platform, data.distribution_owner_namespace)
@@ -901,9 +904,10 @@ async def publisher_release_announce(
Announce a release with a corroborating Trusted Publisher JWT.
"""
- _payload, asf_uid, project = await interaction.trusted_jwt(
- data.publisher,
- data.jwt,
+ ctx = api.auth.trusted_publisher_context()
+ asf_uid, project = await interaction.trusted_project_for_payload(
+ ctx.payload,
+ ctx.asf_uid,
interaction.TrustedProjectPhase.FINISH,
)
try:
@@ -940,9 +944,13 @@ async def publisher_ssh_register(
Register an SSH key sent with a corroborating Trusted Publisher JWT.
"""
- payload, asf_uid, project = await interaction.trusted_jwt(
- data.publisher, data.jwt, interaction.TrustedProjectPhase.COMPOSE
+ ctx = api.auth.trusted_publisher_context()
+ asf_uid, project = await interaction.trusted_project_for_payload(
+ ctx.payload,
+ ctx.asf_uid,
+ interaction.TrustedProjectPhase.COMPOSE,
)
+ payload = ctx.payload
async with storage.write_as_committee_member(util.unwrap(project.committee).key, asf_uid) as wacm:
fingerprint, expires = await wacm.ssh.add_workflow_key(
payload.actor,
@@ -972,9 +980,10 @@ async def publisher_vote_resolve(
Resolve a vote with a corroborating Trusted Publisher JWT.
"""
# TODO: Need to be able to resolve and make the release immutable
- _payload, asf_uid, project = await interaction.trusted_jwt(
- data.publisher,
- data.jwt,
+ ctx = api.auth.trusted_publisher_context()
+ asf_uid, project = await interaction.trusted_project_for_payload(
+ ctx.payload,
+ ctx.asf_uid,
interaction.TrustedProjectPhase.VOTE,
)
try:
@@ -1439,9 +1448,9 @@ async def update_distribution_task_status(
Update the status of a distribution task
Validates the caller is a Github workflow, triggered by ATR itself
"""
- _payload, asf_uid = await interaction.validate_trusted_jwt(data.publisher, data.jwt)
+ ctx = api.auth.trusted_publisher_context()
# If UID is not none, this is a non-ATR workflow, which is unsupported.
- if asf_uid is not None:
+ if ctx.asf_uid is not None:
raise exceptions.Forbidden("This endpoint may only be called by ATR")
async with db.session() as db_data:
status = await db_data.workflow_status(
diff --git a/atr/blueprints/api_auth.py b/atr/blueprints/api_auth.py
index 7d4a746a..55c1c73f 100644
--- a/atr/blueprints/api_auth.py
+++ b/atr/blueprints/api_auth.py
@@ -41,13 +41,21 @@ The levels are:
- ``bearer`` ATR-issued JWT in an ``Authorization: Bearer ...`` header.
- ``body_oidc`` Trusted Publisher OIDC token carried in the request body.
- ``pat`` Personal Access Token in the request body, exchanged for a JWT.
+
+For ``body_oidc`` routes, the verified OIDC payload and the resolved
+ASF UID (if any) are exposed via :func:`trusted_publisher_context` /
+``quart.g.tp_payload`` / ``quart.g.tp_asf_uid`` after the decorator runs.
"""
from __future__ import annotations
+import dataclasses
+import functools
from typing import TYPE_CHECKING, Final, Literal
+import quart
import quart_schema
+import werkzeug.exceptions as exceptions
import atr.jwtoken as jwtoken
@@ -55,6 +63,8 @@ if TYPE_CHECKING:
from collections.abc import Awaitable, Callable, Coroutine
from typing import Any
+ import atr.models.github as github
+
AuthLevel = Literal["public", "bearer", "body_oidc", "pat"]
@@ -87,22 +97,93 @@ def bearer[**P, R](
return wrapped
+@dataclasses.dataclass(frozen=True)
+class TrustedPublisherContext:
+ """Verified state exposed to ``body_oidc`` handlers after the decorator runs.
+
+ Handlers retrieve this via :func:`trusted_publisher_context`, or equivalently
+ via ``quart.g.tp_context``. The fields are:
+
+ - ``payload`` The verified :class:`github.TrustedPublisherPayload`.
+ - ``asf_uid`` The ASF user the GitHub actor maps to, or ``None`` when the
+ token was issued to the trusted role (i.e. an ATR-driven
+ workflow, not a project's TP workflow).
+ - ``publisher`` The publisher string from the body (currently only
+ ``"github"`` is supported).
+ """
+
+ payload: github.TrustedPublisherPayload
+ asf_uid: str | None
+ publisher: str
+
+
+_TP_CONTEXT_ATTR: Final[str] = "tp_context"
+
+
def body_oidc[F: Callable[..., Awaitable[Any]]](func: F) -> F:
- """Marker for routes authenticated by a Trusted Publisher OIDC token in the body.
+ """Validate a Trusted Publisher OIDC token carried in the request body.
+
+ The handler must accept a ``data`` keyword argument whose value is a
+ pydantic model with ``publisher: str`` and ``jwt: str`` fields. This
+ decorator runs *after* ``@quart_schema.validate_request``, so ``data``
+ is already a validated model by the time this wrapper executes.
- PR 1: marker only. The handler still calls ``interaction.trusted_jwt(...)``
- or ``interaction.validate_trusted_jwt(...)`` itself. PR 3 moves the
- validation into the decorator.
+ On success, a :class:`TrustedPublisherContext` is placed on
+ ``quart.g.tp_context`` and the handler runs normally. Handlers read
+ the context via :func:`trusted_publisher_context`.
+
+ On failure (bad signature, wrong audience, unsupported publisher,
+ unknown actor) a 401 ``ASFQuartException`` is raised before the
+ handler body executes, so handlers never see unauthenticated calls.
+
+ Phase-specific checks (e.g. "this release is in the COMPOSE phase")
+ remain the handler's responsibility — the decorator is deliberately
+ narrow.
"""
- return _mark("body_oidc", func)
+
+ @functools.wraps(func)
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
+ data = kwargs.get("data")
+ if data is None:
+ # If @quart_schema.validate_request wasn't applied the handler
+ # is misconfigured; we can't authenticate a body we don't have.
+ raise exceptions.BadRequest("Trusted Publisher auth requires a validated request body")
+ publisher = getattr(data, "publisher", None)
+ jwt = getattr(data, "jwt", None)
+ if (not isinstance(publisher, str)) or (not isinstance(jwt, str)):
+ raise exceptions.BadRequest(
+ "Trusted Publisher auth requires 'publisher' and 'jwt' string fields in the request body"
+ )
+
+ # Import lazily to avoid a top-level cycle: atr.db.interaction
+ # depends on a lot of things, some of which depend on the blueprints.
+ import atr.db.interaction as interaction
+
+ payload, asf_uid = await interaction.validate_trusted_jwt(publisher, jwt)
+ quart.g.tp_context = TrustedPublisherContext(
+ payload=payload,
+ asf_uid=asf_uid,
+ publisher=publisher,
+ )
+ return await func(*args, **kwargs)
+
+ wrapped = quart_schema.security_scheme([{"TrustedPublisherJwt": []}])(wrapper)
+ return _mark("body_oidc", wrapped) # type: ignore[return-value]
def pat[F: Callable[..., Awaitable[Any]]](func: F) -> F:
"""Marker for routes that accept a Personal Access Token in the body.
- PR 1: marker only. Currently applies to ``jwt_create`` only, which
- exchanges a PAT for an ATR-issued JWT. PR 3 may move the PAT validation
- into the decorator once we have a second caller to design against.
+ This is intentionally a pure marker, not a validating decorator. The
+ only current user is ``jwt_create``, which *exchanges* a PAT for an
+ ATR-issued JWT — the PAT check is intrinsic to what the endpoint
+ does, and wrapping it in a decorator would duplicate the storage
+ layer's token-issuance logic rather than clean it up.
+
+ The marker still serves its purpose: it declares "this route accepts
+ a PAT" loudly enough that a security reviewer can spot it in a diff.
+ If a second PAT-consuming endpoint ever appears, revisit whether a
+ shared decorator is worthwhile.
"""
return _mark("pat", func)
@@ -119,6 +200,21 @@ def public[F: Callable[..., Awaitable[Any]]](func: F) -> F:
return _mark("public", func)
+def trusted_publisher_context() -> TrustedPublisherContext:
+ """Return the :class:`TrustedPublisherContext` stashed by ``@body_oidc``.
+
+ Must only be called from inside a handler decorated with
+ ``@api.auth.body_oidc``. Raises :class:`RuntimeError` otherwise, which
+ makes misuse loud rather than silently returning ``None``.
+ """
+ ctx = getattr(quart.g, _TP_CONTEXT_ATTR, None)
+ if ctx is None:
+ raise RuntimeError(
+ "trusted_publisher_context() called outside a @api.auth.body_oidc handler (or before the decorator ran)."
+ )
+ return ctx
+
+
def _mark[F: Callable[..., Any]](level: AuthLevel, func: F) -> F:
"""Attach the auth-level sentinel to ``func``.
diff --git a/atr/db/interaction.py b/atr/db/interaction.py
index f3062c70..d3903034 100644
--- a/atr/db/interaction.py
+++ b/atr/db/interaction.py
@@ -457,24 +457,48 @@ async def trusted_jwt_for_dist(
payload, asf_uid_from_jwt = await validate_trusted_jwt(publisher, jwt)
if asf_uid_from_jwt is not None:
raise InteractionError("Must use Trusted Publishing when specifying ASF UID")
- # payload, asf_uid, project = await trusted_jwt(publisher, jwt, phase)
- async with db.session() as db_data:
- project = await db_data.project(key=str(project_key), _committee=True).demand(
- InteractionError(f"Project {project_key} does not exist")
- )
- release = await db_data.release(project_key=str(project_key), version=str(version_key)).get()
- if not release:
- raise InteractionError(f"Release {version_key} does not exist in project {project_key}")
- if (phase == TrustedProjectPhase.COMPOSE) and (release.phase != sql.ReleasePhase.RELEASE_CANDIDATE_DRAFT):
- raise InteractionError(f"Release {version_key} is not in compose phase")
- if (phase == TrustedProjectPhase.VOTE) and (release.phase != sql.ReleasePhase.RELEASE_CANDIDATE):
- raise InteractionError(f"Release {version_key} is not in vote phase")
- if (phase == TrustedProjectPhase.FINISH) and (release.phase != sql.ReleasePhase.RELEASE_PREVIEW):
- raise InteractionError(f"Release {version_key} is not in finish phase")
-
+ project, release = await _trusted_dist_lookup(asf_uid, phase, project_key, version_key)
return payload, asf_uid, project, release
+async def trusted_project_for_payload(
+ payload: github.TrustedPublisherPayload,
+ asf_uid: str | None,
+ phase: TrustedProjectPhase,
+) -> tuple[str, sql.Project]:
+ """Look up the project for an already-verified Trusted Publisher payload.
+
+ Companion to :func:`trusted_jwt`, but takes a verified payload rather
+ than a raw JWT. This is what ``@api.auth.body_oidc`` handlers should
+ call after the decorator has already checked the token signature.
+ Keeps the phase/project lookup in handler code where it belongs.
+ """
+ if asf_uid is None:
+ raise InteractionError("ASF user not found")
+ project = await _trusted_project(payload.repository, payload.workflow_ref, phase)
+ return asf_uid, project
+
+
+async def trusted_release_for_payload(
+ payload_asf_uid: str | None,
+ asserted_asf_uid: str,
+ phase: TrustedProjectPhase,
+ project_key: safe.ProjectKey,
+ version_key: safe.VersionKey,
+) -> tuple[sql.Project, sql.Release]:
+ """Look up project+release for a body_oidc workflow token.
+
+ Companion to :func:`trusted_jwt_for_dist` that takes the already-verified
+ ``payload_asf_uid`` (from ``@api.auth.body_oidc``) and the ``asf_uid``
+ asserted by the caller in the request body. Enforces the same rule
+ as the original helper: the JWT must not carry an ASF UID of its own
+ (i.e. it must be a trusted-role token, not a per-user token).
+ """
+ if payload_asf_uid is not None:
+ raise InteractionError("Must use Trusted Publishing when specifying ASF UID")
+ return await _trusted_dist_lookup(asserted_asf_uid, phase, project_key, version_key)
+
+
async def unfinished_releases(asfuid: str) -> list[tuple[str, str, list[sql.Release]]]:
releases: list[tuple[str, str, list[sql.Release]]] = []
async with db.session() as data:
@@ -594,6 +618,29 @@ async def wait_for_task(
return False
+async def _trusted_dist_lookup(
+ asf_uid: str,
+ phase: TrustedProjectPhase,
+ project_key: safe.ProjectKey,
+ version_key: safe.VersionKey,
+) -> tuple[sql.Project, sql.Release]:
+ """Shared project + release + phase lookup for dist-style trusted calls."""
+ async with db.session() as db_data:
+ project = await db_data.project(key=str(project_key), _committee=True).demand(
+ InteractionError(f"Project {project_key} does not exist")
+ )
+ release = await db_data.release(project_key=str(project_key), version=str(version_key)).get()
+ if not release:
+ raise InteractionError(f"Release {version_key} does not exist in project {project_key}")
+ if (phase == TrustedProjectPhase.COMPOSE) and (release.phase != sql.ReleasePhase.RELEASE_CANDIDATE_DRAFT):
+ raise InteractionError(f"Release {version_key} is not in compose phase")
+ if (phase == TrustedProjectPhase.VOTE) and (release.phase != sql.ReleasePhase.RELEASE_CANDIDATE):
+ raise InteractionError(f"Release {version_key} is not in vote phase")
+ if (phase == TrustedProjectPhase.FINISH) and (release.phase != sql.ReleasePhase.RELEASE_PREVIEW):
+ raise InteractionError(f"Release {version_key} is not in finish phase")
+ return project, release
+
+
async def _trusted_project(repository: str, workflow_ref: str, phase: TrustedProjectPhase) -> sql.Project:
# Debugging
log.info(f"GitHub OIDC JWT payload: {repository} {workflow_ref}")
diff --git a/tests/unit/api_auth_registry.yaml b/tests/unit/api_auth_registry.yaml
new file mode 100644
index 00000000..faf85c87
--- /dev/null
+++ b/tests/unit/api_auth_registry.yaml
@@ -0,0 +1,70 @@
+# tests/unit/api_auth_registry.yaml
+# Registry of API endpoints -> authentication level.
+# See issue #1169. Changing a level here is a security-relevant change
+# and requires explicit review. Adding a new route without an entry
+# fails test_api_auth_registry_matches_live_routes.
+#
+# Levels:
+# public - no authentication
+# bearer - ATR-issued JWT in Authorization header
+# body_oidc - Trusted Publisher OIDC token in body
+# pat - Personal Access Token in body (exchange endpoint only)
+#
+# URL templates follow the form used by the Quart blueprint:
+# <param_name> validated path segment
+# [/<param_name>] optional trailing segment (renders as two
+# Quart routes, short and full)
+
+# --- public (20) ---
+"/api/checks/list/<project_key>/<version_key>": public # checks_list
+"/api/checks/list/<project_key>/<version_key>/<revision>": public # checks_list_revision
+"/api/checks/ongoing/<project_key>/<version_key>[/<revision>]": public # checks_ongoing
+"/api/committee/get/<name>": public # committee_get
+"/api/committee/keys/<name>": public # committee_keys
+"/api/committee/projects/<name>": public # committee_projects
+"/api/committees/list": public # committees_list
+"/api/ignore/list/<project_key>": public # ignore_list
+"/api/key/get/<fingerprint>": public # key_get
+"/api/keys/user/<asf_uid>": public # keys_user
+"/api/policy/get/<project_key>": public # policy_get
+"/api/project/get/<project_key>": public # project_get
+"/api/project/releases/<project_key>": public # project_releases
+"/api/projects/list": public # projects_list
+"/api/release/get/<project_key>/<version_key>": public # release_get
+"/api/release/paths/<project_key>/<version_key>[/<revision>]": public # release_paths
+"/api/release/revisions/<project_key>/<version_key>": public # release_revisions
+"/api/releases/list": public # releases_list
+"/api/ssh-keys/list/<asf_uid>": public # ssh_keys_list
+"/api/users/list": public # users_list
+
+# --- bearer (18) ---
+"/api/distribution/record": bearer # distribution_record
+"/api/ignore/add": bearer # ignore_add
+"/api/ignore/delete": bearer # ignore_delete
+"/api/key/add": bearer # key_add
+"/api/key/delete": bearer # key_delete
+"/api/keys/upload": bearer # keys_upload
+"/api/policy/update": bearer # policy_update
+"/api/release/announce": bearer # release_announce
+"/api/release/create": bearer # release_create
+"/api/release/delete": bearer # release_delete
+"/api/release/upload": bearer # release_upload
+"/api/signature/provenance": bearer # signature_provenance
+"/api/ssh-key/add": bearer # ssh_key_add
+"/api/ssh-key/delete": bearer # ssh_key_delete
+"/api/user/info": bearer # user_info
+"/api/vote/resolve": bearer # vote_resolve
+"/api/vote/start": bearer # vote_start
+"/api/vote/tabulate": bearer # vote_tabulate
+
+# --- body_oidc (7) ---
+"/api/distribute/record_from_workflow": body_oidc # distribution_record_from_workflow
+"/api/distribute/ssh/register": body_oidc # distribute_ssh_register
+"/api/distribute/task/status": body_oidc # update_distribution_task_status
+"/api/publisher/distribution/record": body_oidc # publisher_distribution_record
+"/api/publisher/release/announce": body_oidc # publisher_release_announce
+"/api/publisher/ssh/register": body_oidc # publisher_ssh_register
+"/api/publisher/vote/resolve": body_oidc # publisher_vote_resolve
+
+# --- pat (1) ---
+"/api/jwt/create": pat # jwt_create
diff --git a/tests/unit/test_api_auth_decorators.py b/tests/unit/test_api_auth_decorators.py
index 08b234c3..fbf28054 100644
--- a/tests/unit/test_api_auth_decorators.py
+++ b/tests/unit/test_api_auth_decorators.py
@@ -111,7 +111,7 @@ def test_expected_level_distribution() -> None:
18 bearer, 7 body_oidc, 1 pat, 20 public = 46 total.
- Not meant as a rigid drift check (that's PR 3's registry file), but a
+ Not meant as a rigid drift check (that's the registry test below), but a
heads-up that catches obvious regressions like "the PAT endpoint
accidentally got marked public".
"""
@@ -126,3 +126,455 @@ def test_expected_level_distribution() -> None:
assert counts["bearer"] >= 15, f"bearer count dropped unexpectedly: {counts['bearer']}"
assert counts["body_oidc"] >= 5, f"body_oidc count dropped unexpectedly: {counts['body_oidc']}"
assert sum(counts.values()) >= 40, f"total route count dropped unexpectedly: {counts}"
+
+
+def test_api_auth_registry_matches_live_routes(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every registered API route must match the checked-in registry.
+
+ The registry file ``tests/unit/api_auth_registry.yaml`` is the canonical
+ record of which URL gets which auth level. This test asserts that a live
+ Quart app, built from the same source, registers exactly the same
+ (URL -> level) mapping. A diff means either:
+
+ - a new route was added (add it to the registry), or
+ - a route's auth level changed (that's a security-relevant change that
+ must be reviewed explicitly), or
+ - a route's URL template changed (update the registry).
+
+ This is the drift-detection test #1169 asks for.
+ """
+ import pathlib
+
+ import asfquart
+ import yaml
+
+ import atr.blueprints as blueprints
+
+ # Mirror the protections used by test_all_routes_support_url_construction
+ # so we don't accidentally write routes.json or leak a live app handle.
+ monkeypatch.setattr("atr.blueprints._export_routes", lambda _: None)
+ monkeypatch.setattr("asfquart.APP", None)
+
+ registry_path = pathlib.Path(__file__).parent / "api_auth_registry.yaml"
+ registry = yaml.safe_load(registry_path.read_text())
+ assert isinstance(registry, dict) and registry, f"registry file {registry_path} is empty or malformed"
+
+ app = asfquart.construct("test")
+ blueprints.register(app)
+
+ # Build live (URL template -> auth level) from the Quart url map.
+ live: dict[str, str] = {}
+ by_endpoint = api_blueprint.route_auth_levels()
+ for rule in app.url_map.iter_rules():
+ if not rule.rule.startswith("/api/"):
+ continue
+ # Quart endpoint string is "<blueprint>.<setup_wrapper_endpoint>".
+ # setup_wrapper composes endpoint names as "<module>_<func>" with
+ # dots replaced by underscores (see common.setup_wrapper), so for
+ # routes in atr.api the segment after the blueprint name looks
+ # like "atr_api_committees_list". The auth registry is keyed by
+ # the original function name only, so strip the module prefix and
+ # any "_full" suffix (added by add_url_rule for the long form of
+ # routes with optional params).
+ endpoint = rule.endpoint.rsplit(".", 1)[-1]
+ endpoint = endpoint.removeprefix("atr_api_")
+ base = endpoint.removesuffix("_full")
+ level = by_endpoint.get(base)
+ if level is None:
+ continue
+
+ # Collapse the two Quart routes for an optional param into the single
+ # "[/<optional>]" template used by the registry. Detect the pair by
+ # looking at whether this rule's `defaults` set the optional arg.
+ if rule.defaults:
+ opt_name = next(iter(rule.defaults))
+ template = f"{rule.rule}[/<{opt_name}>]"
+ elif endpoint.endswith("_full"):
+ # The full form of an optional-param route is already covered by
+ # the short form's bracketed template; skip it to avoid
+ # double-counting.
+ continue
+ else:
+ template = rule.rule
+ live[template] = level
+
+ missing_from_registry = set(live) - set(registry)
+ missing_from_live = set(registry) - set(live)
+ level_mismatches = {
+ url: (registry[url], live[url]) for url in set(registry) & set(live) if registry[url] != live[url]
+ }
+
+ failures = []
+ if missing_from_registry:
+ failures.append(
+ "routes live but missing from registry (add these):\n " + "\n ".join(sorted(missing_from_registry))
+ )
+ if missing_from_live:
+ failures.append(
+ "routes in registry but not live (remove these, or rename):\n " + "\n ".join(sorted(missing_from_live))
+ )
+ if level_mismatches:
+ lines = [f" {url}: registry={reg!r}, live={lv!r}" for url, (reg, lv) in sorted(level_mismatches.items())]
+ failures.append("auth level drift (security review required):\n" + "\n".join(lines))
+
+ assert not failures, "\n\n".join(failures)
+
+
+@pytest.mark.asyncio
+async def test_public_endpoint_accepts_unauthenticated_request(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A @api.auth.public route must respond without any credentials.
+
+ Uses ``/api/committees/list`` as the representative public endpoint
+ because it takes no path parameters and no body.
+ """
+ import asfquart
+
+ import atr.blueprints as blueprints
+
+ monkeypatch.setattr("atr.blueprints._export_routes", lambda _: None)
+ monkeypatch.setattr("asfquart.APP", None)
+
+ app = asfquart.construct("test")
+ blueprints.register(app)
+
+ client = app.test_client()
+ response = await client.get("/api/committees/list")
+ # 200 on success, 500 if DB isn't reachable in the test env - either way
+ # we know we passed authentication, which is what we're testing.
+ assert response.status_code != 401, (
+ f"public endpoint returned 401, which means @api.auth.public is "
+ f"enforcing auth it shouldn't: body={await response.get_data()!r}"
+ )
+
+
+@pytest.mark.asyncio
+async def test_bearer_endpoint_rejects_unauthenticated_request(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A @api.auth.bearer route must return 401 without a Bearer token.
+
+ Uses ``/api/user/info`` as the representative bearer endpoint: simple
+ GET, no path or body params to fabricate.
+ """
+ import asfquart
+
+ import atr.blueprints as blueprints
+
+ monkeypatch.setattr("atr.blueprints._export_routes", lambda _: None)
+ monkeypatch.setattr("asfquart.APP", None)
+
+ app = asfquart.construct("test")
+ blueprints.register(app)
+
+ client = app.test_client()
+ response = await client.get("/api/user/info")
+ assert response.status_code == 401, (
+ f"bearer endpoint did not return 401 without credentials: status={response.status_code}"
+ )
+
+
+# Note: there is no HTTP-level negative test for @api.auth.body_oidc here.
+# Driving a body_oidc endpoint through the test client requires the full
+# QuartSchema(app, security_schemes=...) initialization that server.py does
+# (it populates QUART_SCHEMA_CONVERT_CASING etc.), which the asfquart test
+# fixture doesn't replicate. The decorator's auth behavior is already
+# covered at the unit level by:
+# - test_body_oidc_populates_quart_g_with_context (happy path)
+# - test_body_oidc_missing_body_raises_bad_request
+# - test_body_oidc_rejects_body_without_jwt_fields
+# A proper HTTP-level test belongs in the e2e suite where the real app
+# initialization runs.
+
+
+# ---------------------------------------------------------------------------
+# TrustedPublisherContext handoff from decorator to handler.
+#
+# The body_oidc decorator's contract has two halves: reject invalid tokens
+# (covered above), and make the verified payload available to the handler.
+# The tests below cover the second half.
+# ---------------------------------------------------------------------------
+
+
+def _fake_trusted_payload(**overrides: object) -> object:
+ """Build a minimally-valid TrustedPublisherPayload for tests.
+
+ The model has many required fields but none that the context-handoff
+ tests care about beyond the few we reference directly.
+ """
+ import atr.models.github as github
+
+ defaults = {
+ "actor": "test-user",
+ "actor_id": 12345,
+ "aud": "https://atr.example/",
+ "base_ref": "",
+ "check_run_id": "1",
+ "enterprise": "the-asf",
+ "enterprise_id": "212555",
+ "event_name": "workflow_dispatch",
+ "head_ref": "",
+ "iat": 0,
+ "iss": "https://token.actions.githubusercontent.com",
+ "job_workflow_ref": "apache/test/.github/workflows/x.yml@refs/heads/main",
+ "job_workflow_sha": "0" * 40,
+ "jti": "test-jti",
+ "ref": "refs/heads/main",
+ "ref_protected": "false",
+ "ref_type": "branch",
+ "repository": "apache/test",
+ "repository_owner": "apache",
+ "repository_visibility": "public",
+ "run_attempt": "1",
+ "run_number": "1",
+ "runner_environment": "github-hosted",
+ "sha": "0" * 40,
+ "sub": "repo:apache/test:ref:refs/heads/main",
+ "workflow": "test",
+ "workflow_ref": "apache/test/.github/workflows/x.yml@refs/heads/main",
+ "workflow_sha": "0" * 40,
+ }
+ defaults.update(overrides)
+ return github.TrustedPublisherPayload.model_validate(defaults)
+
+
+def test_trusted_publisher_context_raises_when_unset(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """trusted_publisher_context() must raise if called outside a body_oidc handler.
+
+ Silently returning ``None`` would let a handler misattribute actions
+ to "no one" when the decorator hadn't run. Making misuse loud is the
+ safer default.
+ """
+ import asfquart
+
+ monkeypatch.setattr("asfquart.APP", None)
+
+ app = asfquart.construct("test")
+
+ async def _assert_raises() -> None:
+ async with app.test_request_context("/"):
+ with pytest.raises(RuntimeError, match=r"outside a @api\.auth\.body_oidc"):
+ api_auth.trusted_publisher_context()
+
+ import asyncio
+
+ asyncio.run(_assert_raises())
+
+
+@pytest.mark.asyncio
+async def test_body_oidc_populates_quart_g_with_context(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """On successful validation, @api.auth.body_oidc stashes the verified
+ context on ``quart.g.tp_context`` and the handler reads it via
+ ``trusted_publisher_context()``.
+
+ We stub ``interaction.validate_trusted_jwt`` so the test doesn't hit
+ the network or need a real OIDC token. That's the right seam: the
+ decorator's job is the handoff, not the crypto. Crypto is covered by
+ ``jwtoken.verify_github_oidc``'s own tests.
+ """
+ import asfquart
+ import pydantic
+
+ import atr.db.interaction as interaction
+
+ monkeypatch.setattr("asfquart.APP", None)
+
+ fake_payload = _fake_trusted_payload()
+
+ async def fake_validate(publisher: str, jwt: str) -> tuple[object, str | None]:
+ assert publisher == "github"
+ assert jwt == "fake.jwt.token"
+ return fake_payload, "alice"
+
+ monkeypatch.setattr(interaction, "validate_trusted_jwt", fake_validate)
+
+ class FakeBody(pydantic.BaseModel):
+ publisher: str
+ jwt: str
+
+ captured: dict[str, object] = {}
+
+ @api_auth.body_oidc
+ async def handler(data: FakeBody) -> tuple[dict, int]:
+ ctx = api_auth.trusted_publisher_context()
+ captured["payload"] = ctx.payload
+ captured["asf_uid"] = ctx.asf_uid
+ captured["publisher"] = ctx.publisher
+ return {}, 200
+
+ app = asfquart.construct("test")
+ async with app.test_request_context("/"):
+ await handler(data=FakeBody(publisher="github", jwt="fake.jwt.token"))
+
+ assert captured["payload"] is fake_payload
+ assert captured["asf_uid"] == "alice"
+ assert captured["publisher"] == "github"
+
+
+@pytest.mark.asyncio
+async def test_body_oidc_missing_body_raises_bad_request(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """If the decorated handler has no ``data`` kwarg (i.e. the request
+ body never got validated into a model), the decorator refuses rather
+ than silently skipping the auth check.
+ """
+ import asfquart
+ import werkzeug.exceptions as exceptions
+
+ monkeypatch.setattr("asfquart.APP", None)
+
+ @api_auth.body_oidc
+ async def handler() -> tuple[dict, int]:
+ return {}, 200
+
+ app = asfquart.construct("test")
+ async with app.test_request_context("/"):
+ with pytest.raises(exceptions.BadRequest):
+ await handler()
+
+
+@pytest.mark.asyncio
+async def test_body_oidc_rejects_body_without_jwt_fields(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A body without `publisher` + `jwt` string fields is rejected before
+ the handler runs. Guards against swapping a body model and accidentally
+ losing the auth envelope."""
+ import asfquart
+ import pydantic
+ import werkzeug.exceptions as exceptions
+
+ monkeypatch.setattr("asfquart.APP", None)
+
+ class BodyWithoutJwt(pydantic.BaseModel):
+ name: str
+
+ @api_auth.body_oidc
+ async def handler(data: BodyWithoutJwt) -> tuple[dict, int]:
+ return {}, 200
+
+ app = asfquart.construct("test")
+ async with app.test_request_context("/"):
+ with pytest.raises(exceptions.BadRequest):
+ await handler(data=BodyWithoutJwt(name="hi"))
+
+
+# ---------------------------------------------------------------------------
+# interaction.trusted_project_for_payload / trusted_release_for_payload
+#
+# These helpers sit on the security-relevant path for every body_oidc
+# endpoint: they take an already-verified OIDC payload and do the
+# project/release/phase lookup. The decorator-level tests above cover
+# the auth edge; these cover the post-auth lookup edge.
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.asyncio
+async def test_trusted_project_for_payload_rejects_missing_user(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """When the OIDC token carries no ASF UID (i.e. it's a trusted-role
+ token, not a per-user token), ``trusted_project_for_payload`` must
+ refuse. That refusal is what keeps the publisher/* endpoints from
+ being callable by ATR's own workflow tokens."""
+ import atr.db.interaction as interaction
+
+ payload = _fake_trusted_payload()
+ with pytest.raises(interaction.InteractionError, match="ASF user not found"):
+ await interaction.trusted_project_for_payload(
+ payload,
+ None,
+ interaction.TrustedProjectPhase.COMPOSE,
+ )
+
+
+@pytest.mark.asyncio
+async def test_trusted_release_for_payload_rejects_user_token(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The distribute/* endpoints require a trusted-role token (asf_uid
+ in the payload is None); a per-user token must be refused. Mirrors
+ the check that ``trusted_jwt_for_dist`` performs on live tokens."""
+ import atr.db.interaction as interaction
+ import atr.models.safe as safe
+
+ with pytest.raises(interaction.InteractionError, match="Must use Trusted Publishing"):
+ await interaction.trusted_release_for_payload(
+ payload_asf_uid="bob", # non-None => user token => reject
+ asserted_asf_uid="alice",
+ phase=interaction.TrustedProjectPhase.COMPOSE,
+ project_key=safe.ProjectKey("example"),
+ version_key=safe.VersionKey("1.0.0"),
+ )
+
+
+@pytest.mark.asyncio
+async def test_trusted_project_for_payload_delegates_to_project_lookup(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Happy path: with an ASF UID and a verified payload, the helper
+ calls through to ``_trusted_project`` and returns its result.
+
+ Stubs ``_trusted_project`` so the test doesn't need a database. What
+ we're asserting is that the helper does the null check and then
+ delegates — not the project resolution itself, which has its own
+ tests in interaction.py's existing suite.
+ """
+ import atr.db.interaction as interaction
+
+ payload = _fake_trusted_payload(repository="apache/myproj")
+ sentinel = object()
+
+ async def fake_trusted_project(repository, workflow_ref, phase): # type: ignore[no-untyped-def]
+ assert repository == "apache/myproj"
+ assert phase is interaction.TrustedProjectPhase.VOTE
+ return sentinel
+
+ monkeypatch.setattr(interaction, "_trusted_project", fake_trusted_project)
+
+ asf_uid, project = await interaction.trusted_project_for_payload(
+ payload,
+ "alice",
+ interaction.TrustedProjectPhase.VOTE,
+ )
+ assert asf_uid == "alice"
+ assert project is sentinel
+
+
+@pytest.mark.asyncio
+async def test_trusted_release_for_payload_delegates_to_dist_lookup(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Happy path for the dist variant: with no ASF UID in the payload
+ (i.e. a trusted-role token), the helper delegates the phase/project/
+ release lookup to ``_trusted_dist_lookup`` using the caller-asserted
+ ASF UID from the body.
+ """
+ import atr.db.interaction as interaction
+ import atr.models.safe as safe
+
+ project_sentinel = object()
+ release_sentinel = object()
+
+ async def fake_lookup(asf_uid, phase, project_key, version_key): # type: ignore[no-untyped-def]
+ assert asf_uid == "alice"
+ assert phase is interaction.TrustedProjectPhase.COMPOSE
+ return project_sentinel, release_sentinel
+
+ monkeypatch.setattr(interaction, "_trusted_dist_lookup", fake_lookup)
+
+ project, release = await interaction.trusted_release_for_payload(
+ payload_asf_uid=None, # trusted-role token
+ asserted_asf_uid="alice",
+ phase=interaction.TrustedProjectPhase.COMPOSE,
+ project_key=safe.ProjectKey("example"),
+ version_key=safe.VersionKey("1.0.0"),
+ )
+ assert project is project_sentinel
+ assert release is release_sentinel
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org