You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by ar...@apache.org on 2026/05/25 13:44:38 UTC

(tooling-trusted-releases) branch arm updated (a51cd184 -> 514b62a7)

This is an automated email from the ASF dual-hosted git repository.

alitheg pushed a change to branch arm
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git


 discard a51cd184 Add system PATs and enable optional IP limiting for PATs. Limit asfyaml endpoint to system PAT
     add 11fc77e7 Set rdf and charter optional since they're missing for some committees
     new 514b62a7 Add system PATs and enable optional IP limiting for PATs. Limit asfyaml endpoint to system PAT

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   (a51cd184)
            \
             N -- N -- N   refs/heads/arm (514b62a7)

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 1 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/datasources/apache.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org


(tooling-trusted-releases) 01/01: Add system PATs and enable optional IP limiting for PATs. Limit asfyaml endpoint to system PAT

Posted by ar...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

alitheg pushed a commit to branch arm
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git

commit 514b62a7c08620f1e0481cb86710de59177a28d2
Author: Alastair McFarlane <ar...@apache.org>
AuthorDate: Mon May 25 10:13:58 2026 +0100

    Add system PATs and enable optional IP limiting for PATs. Limit asfyaml endpoint to system PAT
---
 atr/admin/__init__.py                           | 132 +++++++++++++++
 atr/admin/templates/system-tokens.html          |  66 ++++++++
 atr/api/__init__.py                             |  25 +--
 atr/blueprints/api.py                           |   2 +-
 atr/blueprints/api_auth.py                      |  26 ++-
 atr/db/__init__.py                              |  17 +-
 atr/docs/authentication-security.md             |  10 ++
 atr/docs/authorization-security.md              |   5 +
 atr/jwtoken.py                                  |  60 +++++--
 atr/ldap.py                                     |   7 +-
 atr/models/sql.py                               |  22 +++
 atr/post/tokens.py                              |  12 +-
 atr/shared/tokens.py                            |   5 +-
 atr/storage/__init__.py                         |  31 ++++
 atr/storage/readers/tokens.py                   |   7 +-
 atr/storage/types.py                            |   2 +
 atr/storage/writers/policy.py                   | 145 ++++++++++-------
 atr/storage/writers/project.py                  | 141 ++++++++--------
 atr/storage/writers/tokens.py                   | 135 +++++++++++++---
 atr/templates/includes/topnav.html              |   5 +
 migrations/versions/0086_2026.05.22_383a2b3d.py |  34 ++++
 tests/unit/test_ldap.py                         |   9 +-
 tests/unit/test_tokens_safe.py                  | 205 +++++++++++++++++++++++-
 23 files changed, 904 insertions(+), 199 deletions(-)

diff --git a/atr/admin/__init__.py b/atr/admin/__init__.py
index 3dcb03a1..a111a505 100644
--- a/atr/admin/__init__.py
+++ b/atr/admin/__init__.py
@@ -18,6 +18,8 @@
 import asyncio
 import collections
 import datetime
+import hashlib
+import ipaddress
 import json
 import os
 import pathlib
@@ -55,8 +57,10 @@ import atr.models.safe as safe
 import atr.models.sql as sql
 import atr.models.unsafe as unsafe
 import atr.models.validation as validation
+import atr.noisy as noisy
 import atr.paths as paths
 import atr.principal as principal
+import atr.shared as shared
 import atr.storage as storage
 import atr.storage.outcome as outcome
 import atr.tasks as tasks
@@ -132,6 +136,41 @@ class ValidateJwtForm(form.Form):
         return token
 
 
+class CreateSystemTokenForm(form.Form):
+    label: str = form.label("Label", "A name to identify this system token.")
+    allowed_ip: str = form.label(
+        "Allowed IP",
+        "Optional single IP or CIDR the token may be exchanged from. Leave blank for no restriction.",
+        default="",
+    )
+
+    @pydantic.field_validator("label", mode="after")
+    @classmethod
+    def validate_label(cls, value: str) -> str:
+        value = value.strip()
+        if not value:
+            raise ValueError("Label is required")
+        if len(value) > 100:
+            raise ValueError("Label must be 100 characters or less")
+        return value
+
+    @pydantic.field_validator("allowed_ip", mode="after")
+    @classmethod
+    def validate_allowed_ip(cls, value: str) -> str:
+        value = value.strip()
+        if not value:
+            return ""
+        try:
+            ipaddress.ip_network(value, strict=False)
+        except ValueError as e:
+            raise ValueError("Allowed IP must be a valid IP address or CIDR") from e
+        return value
+
+
+class RevokeSystemTokenForm(form.Form):
+    token_id: form.Int = form.label("Token ID", widget=form.Widget.HIDDEN)
+
+
 class SessionDataCommon(NamedTuple):
     uid: str
     fullname: str
@@ -981,6 +1020,99 @@ async def revoke_user_tokens_post(
     return await session.redirect(revoke_user_tokens_get)
 
 
+@admin.typed
+async def system_tokens_get(session: web.Committer, _system_tokens: Literal["system-tokens"]) -> str:
+    """
+    URL: GET /system-tokens
+
+    Mint and manage system tokens.
+    """
+    async with storage.write(session) as write:
+        wafa = write.as_foundation_admin()
+        tokens = await wafa.tokens.list_system_tokens()
+
+    create_form = await form.render(
+        model_cls=CreateSystemTokenForm,
+        action=util.as_url(system_tokens_create_post),
+        submit_label="Create system token",
+    )
+    rows = []
+    for token in tokens:
+        revoke_form = await form.render(
+            model_cls=RevokeSystemTokenForm,
+            action=util.as_url(system_tokens_revoke_post),
+            form_classes=".mb-0",
+            submit_classes="btn-sm btn-danger",
+            submit_label="Revoke",
+            confirm="Revoke this system token? Any JWTs issued from it stop working immediately.",
+            defaults={"token_id": token.id},
+            empty=True,
+        )
+        rows.append((token, revoke_form))
+    return await template.render(
+        "system-tokens.html",
+        create_form=create_form,
+        rows=rows,
+        format_datetime=util.format_datetime,
+    )
+
+
+@admin.typed
+async def system_tokens_create_post(
+    session: web.Committer,
+    _system_tokens_create: Literal["system-tokens/create"],
+    create_form: CreateSystemTokenForm,
+) -> web.WerkzeugResponse:
+    """
+    URL: POST /system-tokens/create
+
+    Mint a system token and show its secret once.
+    """
+    plaintext = noisy.create(shared.tokens.PAT_NOISY_SECRET_DOMAIN).decode("ascii")
+    token_hash = hashlib.sha3_256(plaintext.encode()).hexdigest()
+    created = datetime.datetime.now(datetime.UTC)
+    expires = created + datetime.timedelta(days=shared.tokens.PAT_EXPIRY_DAYS)
+    allowed_ip = create_form.allowed_ip.strip() or None
+
+    async with storage.write(session) as write:
+        wafa = write.as_foundation_admin()
+        await wafa.tokens.add_system_token(token_hash, created, expires, create_form.label, allowed_ip)
+
+    await web.flash_success(
+        htm.p[
+            htm.strong["New system token"],
+            " (",
+            htm.code[create_form.label],
+            "): ",
+            htm.code(".bg-light.border.rounded.px-1.text-break")[plaintext],
+        ],
+        htm.p(".mb-0")["Copy it now - it will not be shown again."],
+    )
+    return await session.redirect(system_tokens_get)
+
+
+@admin.typed
+async def system_tokens_revoke_post(
+    session: web.Committer,
+    _system_tokens_revoke: Literal["system-tokens/revoke"],
+    revoke_form: RevokeSystemTokenForm,
+) -> web.WerkzeugResponse:
+    """
+    URL: POST /system-tokens/revoke
+
+    Revoke a single system token.
+    """
+    async with storage.write(session) as write:
+        wafa = write.as_foundation_admin()
+        revoked = await wafa.tokens.revoke_system_token(revoke_form.token_id)
+
+    if revoked:
+        await quart.flash("System token revoked.", "success")
+    else:
+        await quart.flash("System token not found.", "info")
+    return await session.redirect(system_tokens_get)
+
+
 @admin.typed
 async def rotate_jwt_key_get(_session: web.Committer, _rotate_jwt_key: Literal["rotate-jwt-key"]) -> str:
     """
diff --git a/atr/admin/templates/system-tokens.html b/atr/admin/templates/system-tokens.html
new file mode 100644
index 00000000..6f6b27ae
--- /dev/null
+++ b/atr/admin/templates/system-tokens.html
@@ -0,0 +1,66 @@
+{% extends "layouts/base-admin.html" %}
+
+{%- block title -%}System tokens ~ ATR{%- endblock title -%}
+
+{%- block description -%}Mint and manage system tokens for trusted service callers.{%- endblock description -%}
+
+{% block content %}
+  <h1>System tokens</h1>
+  <p>System tokens are admin-issued Personal Access Tokens for trusted service callers, such as the
+    <code>.asf.yaml</code> processor.</p>
+
+  <div class="card mb-4">
+    <div class="card-header">
+      <h5 class="mb-0">Create system token</h5>
+    </div>
+    <div class="card-body">
+      {{ create_form }}
+    </div>
+  </div>
+
+  {% if rows %}
+    <div class="card">
+      <div class="card-header">
+        <h5 class="mb-0">Active system tokens</h5>
+      </div>
+      <div class="card-body">
+        <table class="table table-sm table-striped table-bordered align-middle">
+          <thead>
+            <tr>
+              <th>Label</th>
+              <th>Created by</th>
+              <th>Allowed IP</th>
+              <th>Created</th>
+              <th>Expires</th>
+              <th>Last used</th>
+              <th></th>
+            </tr>
+          </thead>
+          <tbody>
+            {% for token, revoke_form in rows %}
+              <tr>
+                <td>{{ token.label or "" }}</td>
+                <td><code>{{ token.asfuid }}</code></td>
+                <td>
+                  {% if token.allowed_ip %}
+                    <code>{{ token.allowed_ip }}</code>
+                  {% else %}
+                    <span class="text-muted">Any</span>
+                  {% endif %}
+                </td>
+                <td>{{ format_datetime(token.created) }}</td>
+                <td>{{ format_datetime(token.expires) }}</td>
+                <td>
+                  {% if token.last_used %}{{ format_datetime(token.last_used) }}{% else %}Never{% endif %}
+                </td>
+                <td>{{ revoke_form }}</td>
+              </tr>
+            {% endfor %}
+          </tbody>
+        </table>
+      </div>
+    </div>
+  {% else %}
+    <div class="alert alert-info" role="alert">No system tokens have been created.</div>
+  {% endif %}
+{% endblock content %}
diff --git a/atr/api/__init__.py b/atr/api/__init__.py
index 92aabb25..a7a74836 100644
--- a/atr/api/__init__.py
+++ b/atr/api/__init__.py
@@ -594,9 +594,15 @@ async def jwt_create(
     # Returns {"asfuid": "uid", "jwt": "jwt-token"}
     asf_uid = data.asfuid
     log.set_asf_uid(asf_uid)
-    async with storage.write(asf_uid) as write:
-        wafc = write.as_foundation_committer()
-        jwt = await wafc.tokens.issue_jwt(data.pat)
+    client_ip = quart.request.remote_addr
+    # System tokens take a service-identity context, not the LDAP-backed write().
+    if await storage.pat_is_system(data.pat):
+        async with storage.write_as_system_service(asf_uid) as wss:
+            jwt = await wss.tokens.issue_jwt(data.pat, client_ip)
+    else:
+        async with storage.write(asf_uid) as write:
+            wafc = write.as_foundation_committer()
+            jwt = await wafc.tokens.issue_jwt(data.pat, client_ip)
 
     return models.api.JwtCreateResults(
         endpoint="/jwt/create",
@@ -872,7 +878,7 @@ async def policy_update(
 
 
 @api.typed
-@api.auth.bearer
+@api.auth.system_bearer
 @quart_schema.validate_response(models.api.ProjectConfigResults, 200)
 async def project_config_upsert(
     _project_config: Literal["project/config"],
@@ -883,16 +889,17 @@ async def project_config_upsert(
 
     Upsert a project's full configuration.
 
-    Creates a project if it on by the specified key does not yet exist.
+    Creates a project under the specified key if it does not yet exist.
     Otherwise, updates all specified fields for an existing project.
 
-    The caller must be a committee member of the specified committee,
-    and for an existing project committee_key must match the current value.
+    Requires a system token. This endpoint backs the .asf.yaml processor, which
+    establishes upstream that the caller may act for the named committee. For an
+    existing project, committee_key must match the current value.
     """
     asf_uid = _jwt_asf_uid()
     try:
-        async with storage.write_as_committee_member(str(data.committee_key), asf_uid) as wacm:
-            created = await wacm.project.upsert_config(data)
+        async with storage.write_as_system_service(asf_uid) as wss:
+            created = await wss.project.upsert_config(data)
     except storage.AccessError as e:
         raise _http_exception_from_storage_access_error(e) from e
     except ValueError as e:
diff --git a/atr/blueprints/api.py b/atr/blueprints/api.py
index fa0075ca..7471b91d 100644
--- a/atr/blueprints/api.py
+++ b/atr/blueprints/api.py
@@ -228,7 +228,7 @@ def _require_auth_level(func: Callable[..., Any], original: Callable[..., Any])
         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. "
+            "@api.auth.bearer, @api.auth.system_bearer, @api.auth.body_oidc, or @api.auth.pat. "
             "See atr/blueprints/api_auth.py for details."
         )
     if level not in auth.VALID_LEVELS:
diff --git a/atr/blueprints/api_auth.py b/atr/blueprints/api_auth.py
index 4df8dea0..9745ba1e 100644
--- a/atr/blueprints/api_auth.py
+++ b/atr/blueprints/api_auth.py
@@ -38,11 +38,11 @@ if TYPE_CHECKING:
     import atr.models.github as github
 
 
-AuthLevel = Literal["public", "bearer", "body_oidc", "pat"]
+AuthLevel = Literal["public", "bearer", "system_bearer", "body_oidc", "pat"]
 
 AUTH_LEVEL_ATTR: Final[str] = "_api_auth_level"
 
-VALID_LEVELS: Final[frozenset[AuthLevel]] = frozenset({"public", "bearer", "body_oidc", "pat"})
+VALID_LEVELS: Final[frozenset[AuthLevel]] = frozenset({"public", "bearer", "system_bearer", "body_oidc", "pat"})
 
 _TP_CONTEXT_ATTR: Final[str] = "tp_context"
 
@@ -125,6 +125,28 @@ def public[F: Callable[..., Awaitable[Any]]](func: F) -> F:
     return _mark("public", func)
 
 
+def system_bearer[**P, R](
+    func: Callable[P, Coroutine[Any, Any, R]],
+) -> Callable[P, Awaitable[R]]:
+    """Require an ATR-issued Bearer JWT with system privileges (from a system PAT).
+
+    Ordinary user JWTs are rejected.
+    """
+
+    @functools.wraps(func)
+    async def checked(*args: P.args, **kwargs: P.kwargs) -> R:
+        claims = getattr(quart.g, "jwt_claims", None)
+        if not (isinstance(claims, dict) and claims.get("atr_sys")):
+            raise base.ASFQuartException("System privileges required", errorcode=403)
+        return await func(*args, **kwargs)
+
+    # require() verifies the JWT and sets quart.g.jwt_claims before checked runs.
+    wrapped = jwtoken.require(checked)
+    wrapped = quart_schema.security_scheme([{"BearerAuth": []}])(wrapped)
+    _mark("system_bearer", wrapped)
+    return wrapped
+
+
 def trusted_publisher_context() -> TrustedPublisherContext:
     """Return the TrustedPublisherContext placed by @body_oidc on quart.g."""
     ctx = getattr(quart.g, _TP_CONTEXT_ATTR, None)
diff --git a/atr/db/__init__.py b/atr/db/__init__.py
index 2f4b801e..8ef24a56 100644
--- a/atr/db/__init__.py
+++ b/atr/db/__init__.py
@@ -417,9 +417,22 @@ class Session(sqlalchemy.ext.asyncio.AsyncSession):
         if commit is True:
             await self.commit()
 
-    def personal_access_token(self, token_hash: str) -> Query[sql.PersonalAccessToken]:
+    def personal_access_token(
+        self,
+        token_hash: Opt[str] = NOT_SET,
+        id: Opt[int] = NOT_SET,
+        asfuid: Opt[str] = NOT_SET,
+        is_system: Opt[bool] = NOT_SET,
+    ) -> Query[sql.PersonalAccessToken]:
         query = sqlmodel.select(sql.PersonalAccessToken)
-        query = query.where(sql.PersonalAccessToken.token_hash == token_hash)
+        if is_defined(token_hash):
+            query = query.where(sql.PersonalAccessToken.token_hash == token_hash)
+        if is_defined(id):
+            query = query.where(sql.PersonalAccessToken.id == id)
+        if is_defined(asfuid):
+            query = query.where(sql.PersonalAccessToken.asfuid == asfuid)
+        if is_defined(is_system):
+            query = query.where(sql.PersonalAccessToken.is_system == is_system)
         return Query(self, query)
 
     def project(
diff --git a/atr/docs/authentication-security.md b/atr/docs/authentication-security.md
index faf47635..1853241d 100644
--- a/atr/docs/authentication-security.md
+++ b/atr/docs/authentication-security.md
@@ -107,6 +107,7 @@ Committers can obtain PATs from the `/tokens` page on the ATR website. PATs have
 * **Format**: New PATs are Noisy Secrets using the `tooling.apache.org` namespace
 * **Storage**: ATR stores only SHA3-256 hashes, never the plaintext PAT
 * **Revocation**: Users can revoke their own PATs at any time; admins can revoke all PATs for any user via the admin "Revoke user tokens" page
+* **IP restriction**: A PAT may optionally be bound to a single IP or CIDR. When set, JWT issuance is refused from any other address
 * **Purpose**: PATs are used solely to obtain JWTs; they cannot be used directly for API access
 
 Only authenticated committers (signed in via ASF OAuth) can create PATs. Each user can have multiple active PATs.
@@ -147,6 +148,14 @@ Authorization: Bearer jwt_token_value
 
 The [`jwtoken`](/ref/atr/jwtoken.py) module handles JWT creation and verification. Protected API endpoints use the `@jwtoken.require` decorator, which extracts the JWT from the `Authorization` header, verifies its signature and required claims, and makes the user's ASF UID available to the handler. Verification applies a deliberate two minute leeway to the time based JWT checks to tolerate small clock skew between ATR and API clients.
 
+### System tokens
+
+Most PATs belong to a committer and are tied to their LDAP account. ATR also supports *system tokens*: PATs minted for a trusted service caller rather than a person, flagged with `is_system` in the database. The PAT's `asfuid` records the administrator who created it; the JWT it mints carries a fixed service identity, `atr-system`, which has no LDAP account. System tokens are restricted to foundation administrators; committers cannot create them from the `/tokens` page.
+
+A system token is exchanged for a JWT at `/api/jwt`, requesting the `atr-system` identity. The resulting JWT carries an additional `atr_sys` claim and `atr-system` as its subject. Because that identity has no LDAP account, verification skips the LDAP active check for these JWTs. It still re-validates the backing PAT on every request, so revoking the PAT immediately invalidates every JWT issued from it. Two further checks apply: a system JWT must be backed by a system PAT, and its subject [...]
+
+Endpoints that should accept only system tokens are decorated with `@api.auth.system_bearer`, which rejects ordinary user JWTs. The committee membership check that gates committer-driven writes does not apply, so any committee authorisation for these endpoints must be established by the calling service before it reaches ATR. The only such endpoint at present is `/project/config`, which the `.asf.yaml` processor uses to create and update projects.
+
 ## GitHub Actions OIDC (Trusted Publishing)
 
 GitHub Actions workflows authenticate to ATR using OIDC tokens issued by GitHub (`token.actions.githubusercontent.com`). ATR uses this mechanism in two distinct contexts with different authorization requirements, described below.
@@ -302,6 +311,7 @@ Tokens must be protected by the user at all times:
 * [`blueprints/api.py`](/ref/atr/blueprints/api.py) - API wide rate limiting
 * [`api/__init__.py`](/ref/atr/api/__init__.py) - Tighter API limits for JWT creation
 * [`jwtoken.py`](/ref/atr/jwtoken.py) - JWT creation, verification, and decorators; `verify_github_oidc` implements the OIDC validation chain
+* [`blueprints/api_auth.py`](/ref/atr/blueprints/api_auth.py) - per-endpoint auth level decorators, including `system_bearer`
 * [`db/interaction.py`](/ref/atr/db/interaction.py) - `validate_trusted_jwt` implements the service account authorisation, `trusted_jwt_for_dist` implements gating based on the service account
 * [`ldap.py`](/ref/atr/ldap.py) - Account deactivation handling and credential revocation
 * [`storage/writers/tokens.py`](/ref/atr/storage/writers/tokens.py) - Token creation, deletion, and admin revocation
diff --git a/atr/docs/authorization-security.md b/atr/docs/authorization-security.md
index cf384516..76fca759 100644
--- a/atr/docs/authorization-security.md
+++ b/atr/docs/authorization-security.md
@@ -146,6 +146,11 @@ Token operations apply to the authenticated user:
 * Allowed for: Anyone with a valid PAT
 * Note: This is an unauthenticated endpoint; the PAT serves as the credential
 
+**System tokens**:
+
+* Allowed for: Foundation administrators only (not committer self-service)
+* Note: System tokens are PATs for a service identity rather than a person. Endpoints that accept them (via `@api.auth.system_bearer`) apply no committee membership check, so the calling service must establish any committee authorisation upstream. See [System tokens](authentication-security#system-tokens) in the authentication guide for the mechanism.
+
 ## Implementation patterns
 
 Authorization checks in ATR follow consistent patterns.
diff --git a/atr/jwtoken.py b/atr/jwtoken.py
index 751a9e01..3344b4c9 100644
--- a/atr/jwtoken.py
+++ b/atr/jwtoken.py
@@ -39,6 +39,10 @@ import atr.models.github as github
 import atr.util as util
 
 _ALGORITHM: Final[str] = "HS256"
+# Fixed identity carried by JWTs minted from system PATs (the sub claim, and the
+# UID logged for their actions). The PAT row itself records the admin who created
+# it in its asfuid.
+SYSTEM_SERVICE_UID: Final[str] = "atr-system"
 _ATR_JWT_AUDIENCE: Final[str] = f"https://{config.get().APP_HOST}/"
 _ATR_JWT_ISSUER: Final[str] = f"https://{config.get().APP_HOST}/"
 _ATR_JWT_LEEWAY_SECONDS: Final[int] = 2 * 60
@@ -68,7 +72,7 @@ def activate_signing_key(key: str) -> None:
     app.extensions[_JWT_KEY_APP_EXTENSION] = key
 
 
-def issue(uid: str, *, ttl: int = _ATR_JWT_TTL, pat_hash: str | None = None) -> str:
+def issue(uid: str, *, ttl: int = _ATR_JWT_TTL, pat_hash: str | None = None, system: bool = False) -> str:
     # audit_guidance no explicit typ header or token_type claim is added: the aud claim (_ATR_JWT_AUDIENCE)
     # already acts as an explicit token type discriminator, and ATR issues only one JWT type verified
     # by a single internal verifier — the RFC 9068 typ header is relevant to multi-issuer OAuth2 RS
@@ -85,6 +89,8 @@ def issue(uid: str, *, ttl: int = _ATR_JWT_TTL, pat_hash: str | None = None) ->
     }
     if pat_hash:
         payload["atr_th"] = pat_hash
+    if system:
+        payload["atr_sys"] = True
     log.auth_event("jwt_issuance", uid, pat_hash=pat_hash if pat_hash else None)
     return jwt.encode(payload, _signing_key(), algorithm=_ALGORITHM)
 
@@ -143,25 +149,15 @@ async def verify(token: str) -> dict[str, Any]:
     if not isinstance(asf_uid, str):
         log.auth_failure("jwt_token", "jwt_subject_invalid")
         raise jwt.InvalidTokenError("Invalid Bearer JWT subject")
-    if not await ldap.is_active(asf_uid):
+    # System tokens have no LDAP account to check; the PAT recheck below still
+    # gates them, so revocation stays immediate.
+    is_system = bool(claims.get("atr_sys"))
+    if (not is_system) and (not await ldap.is_active(asf_uid)):
         log.auth_failure("jwt_token", "account_deleted_or_banned")
         raise base.ASFQuartException("Account is disabled", errorcode=401)
 
     # audit_guidance Revalidating PAT on each request ensures PAT deletion immediately revokes all JWTs issued therefrom
-    pat_hash = claims.get("atr_th")
-    # Not all JWTs come from PATs, so don't fail on missing atr_th
-    if pat_hash:
-        async with db.session() as data:
-            pat = await data.personal_access_token(pat_hash).get()
-            if not pat:
-                log.auth_failure("jwt_token", "pat_hash_invalid")
-                raise base.ASFQuartException("Personal Access Token invalid", errorcode=401)
-            if pat.asfuid != claims.get("sub"):
-                log.auth_failure("jwt_token", "pat_user_mismatch")
-                raise base.ASFQuartException("Personal Access Token invalid", errorcode=401)
-            if pat.expires < datetime.datetime.now(datetime.UTC):
-                log.auth_failure("jwt_token", "pat_expired")
-                raise base.ASFQuartException("Personal Access Token expired", errorcode=401)
+    await _revalidate_pat(claims, is_system)
     return claims
 
 
@@ -260,6 +256,38 @@ def _read_signing_key() -> str | None:
     return key
 
 
+async def _revalidate_pat(claims: dict[str, Any], is_system: bool) -> None:
+    pat_hash = claims.get("atr_th")
+    # A system claim with no PAT hash skipped the LDAP check and has nothing left
+    # to validate it, so reject it.
+    if is_system and (not pat_hash):
+        log.auth_failure("jwt_token", "system_without_pat")
+        raise base.ASFQuartException("Personal Access Token invalid", errorcode=401)
+    # Not all JWTs come from PATs, so don't fail on missing atr_th
+    if not pat_hash:
+        return
+    async with db.session() as data:
+        pat = await data.personal_access_token(pat_hash).get()
+    if not pat:
+        log.auth_failure("jwt_token", "pat_hash_invalid")
+        raise base.ASFQuartException("Personal Access Token invalid", errorcode=401)
+    # A system JWT must come from a system PAT, and vice versa.
+    if pat.is_system != is_system:
+        log.auth_failure("jwt_token", "pat_system_mismatch")
+        raise base.ASFQuartException("Personal Access Token invalid", errorcode=401)
+    # A user JWT's sub is the PAT owner; a system JWT's sub is the fixed service
+    # identity, not the admin who created the PAT.
+    if is_system and (claims.get("sub") != SYSTEM_SERVICE_UID):
+        log.auth_failure("jwt_token", "system_subject_invalid")
+        raise base.ASFQuartException("Personal Access Token invalid", errorcode=401)
+    if (not is_system) and (pat.asfuid != claims.get("sub")):
+        log.auth_failure("jwt_token", "pat_user_mismatch")
+        raise base.ASFQuartException("Personal Access Token invalid", errorcode=401)
+    if pat.is_expired:
+        log.auth_failure("jwt_token", "pat_expired")
+        raise base.ASFQuartException("Personal Access Token expired", errorcode=401)
+
+
 def _signing_key() -> str:
     app = asfquart.APP
     if app is not None:
diff --git a/atr/ldap.py b/atr/ldap.py
index 71790124..3208dd78 100644
--- a/atr/ldap.py
+++ b/atr/ldap.py
@@ -309,7 +309,7 @@ async def is_active(asf_uid: str) -> bool:
             return True
         if asf_uid == "test-banned":
             return False
-    if get_bind_credentials() is None:
+    if get_bind_credentials() is None and not config.is_production_mode():
         return True
     account = await account_lookup(asf_uid)
     if account is None:
@@ -384,10 +384,7 @@ async def _revoke_all_credentials(uid: str, log) -> None:
         log.auth_event("sessions_revoked", uid)
 
     async with db.session() as data:
-        token_result = await data.execute(
-            sqlmodel.select(sql.PersonalAccessToken).where(sql.PersonalAccessToken.asfuid == uid)
-        )
-        tokens = list(token_result.scalars().all())
+        tokens = await data.personal_access_token(asfuid=uid).all()
         for token in tokens:
             await data.delete(token)
 
diff --git a/atr/models/sql.py b/atr/models/sql.py
index 5e4e4d92..1d747b51 100644
--- a/atr/models/sql.py
+++ b/atr/models/sql.py
@@ -24,6 +24,7 @@
 import dataclasses
 import datetime
 import enum
+import ipaddress
 from typing import TYPE_CHECKING, Any, Final, Literal, Optional, TypeVar, assert_never, overload
 
 import pydantic
@@ -563,6 +564,27 @@ class PersonalAccessToken(sqlmodel.SQLModel, table=True):
     expires: datetime.datetime = sqlmodel.Field(sa_column=sqlalchemy.Column(UTCDateTime, nullable=False))
     last_used: datetime.datetime | None = sqlmodel.Field(default=None, sa_column=sqlalchemy.Column(UTCDateTime))
     label: str | None = None
+    # System tokens are admin-minted for service callers (e.g. the .asf.yaml
+    # processor); asfuid records the creating admin. The JWTs they mint carry
+    # the fixed atr-system identity, skip the LDAP check, and gain system privileges.
+    is_system: bool = sqlmodel.Field(default=False)
+    # Optional single IP or CIDR the token may be exchanged from. Null means no
+    # restriction.
+    allowed_ip: str | None = None
+
+    @property
+    def is_expired(self) -> bool:
+        return self.expires < datetime.datetime.now(datetime.UTC)
+
+    def allows_ip(self, client_ip: str | None) -> bool:
+        if self.allowed_ip is None:
+            return True
+        if client_ip is None:
+            return False
+        try:
+            return ipaddress.ip_address(client_ip) in ipaddress.ip_network(self.allowed_ip, strict=False)
+        except ValueError:
+            return False
 
 
 # RevisionCounter:
diff --git a/atr/post/tokens.py b/atr/post/tokens.py
index e478c8c3..1d54cff0 100644
--- a/atr/post/tokens.py
+++ b/atr/post/tokens.py
@@ -17,8 +17,9 @@
 
 import datetime
 import hashlib
-from typing import Final, Literal
+from typing import Literal
 
+import quart
 import quart_rate_limiter as rate_limiter
 
 import atr.blueprints.post as post
@@ -30,9 +31,6 @@ import atr.shared as shared
 import atr.storage as storage
 import atr.web as web
 
-_EXPIRY_DAYS: Final[int] = 180
-_PAT_NOISY_SECRET_DOMAIN: Final[bytes] = b"tooling.apache.org"
-
 
 @post.typed
 @rate_limiter.rate_limit(10, datetime.timedelta(hours=1))
@@ -44,7 +42,7 @@ async def jwt_post(
     """
     async with storage.write(session) as write:
         wafc = write.as_foundation_committer()
-        jwt_token = await wafc.tokens.issue_jwt(form.pat)
+        jwt_token = await wafc.tokens.issue_jwt(form.pat, quart.request.remote_addr)
     response = web.TextResponse(jwt_token)
     response.headers["Cache-Control"] = "no-store"
     return response
@@ -67,10 +65,10 @@ async def tokens(
 
 
 async def _add_token(session: web.Committer, add_form: shared.tokens.AddTokenForm) -> web.WerkzeugResponse:
-    plaintext = noisy.create(_PAT_NOISY_SECRET_DOMAIN).decode("ascii")
+    plaintext = noisy.create(shared.tokens.PAT_NOISY_SECRET_DOMAIN).decode("ascii")
     token_hash = hashlib.sha3_256(plaintext.encode()).hexdigest()
     created = datetime.datetime.now(datetime.UTC)
-    expires = created + datetime.timedelta(days=_EXPIRY_DAYS)
+    expires = created + datetime.timedelta(days=shared.tokens.PAT_EXPIRY_DAYS)
 
     async with storage.write() as write:
         wafc = write.as_foundation_committer()
diff --git a/atr/shared/tokens.py b/atr/shared/tokens.py
index 3928c148..41293288 100644
--- a/atr/shared/tokens.py
+++ b/atr/shared/tokens.py
@@ -15,12 +15,15 @@
 # specific language governing permissions and limitations
 # under the License.
 
-from typing import Annotated, Literal
+from typing import Annotated, Final, Literal
 
 import pydantic
 
 import atr.form as form
 
+PAT_EXPIRY_DAYS: Final[int] = 180
+PAT_NOISY_SECRET_DOMAIN: Final[bytes] = b"tooling.apache.org"
+
 type ADD_TOKEN = Literal["add_token"]
 type DELETE_TOKEN = Literal["delete_token"]
 
diff --git a/atr/storage/__init__.py b/atr/storage/__init__.py
index 3e856670..9108545c 100644
--- a/atr/storage/__init__.py
+++ b/atr/storage/__init__.py
@@ -269,6 +269,23 @@ class WriteAsUserService(WriteAs):
         return self.__asf_uid
 
 
+class WriteAsSystemService(WriteAs):
+    # Built directly from the service identity rather than via Authorisation,
+    # which would reject an identity with no LDAP account.
+    def __init__(self, data: db.Session, asf_uid: str):
+        asf_uid = asf_uid.strip()
+        if not asf_uid:
+            raise AccessError("System service writes require a service identity", status=500)
+        self.__asf_uid = asf_uid
+        self.policy = writers.policy.SystemService(self, data)
+        self.project = writers.project.SystemService(self, data)
+        self.tokens = writers.tokens.SystemService(self, data)
+
+    @property
+    def asf_uid(self) -> str:
+        return self.__asf_uid
+
+
 # TODO: Could name this WriteDispatcher
 class Write:
     # Read and Write have authenticator methods which return access outcomes
@@ -507,6 +524,13 @@ def ensure_project_active(project: sql.Project) -> None:
     raise AccessError(f"Project '{project.key}' is archived; release actions are disabled.")
 
 
+async def pat_is_system(pat_text: str) -> bool:
+    token_hash = writers.tokens.hash_pat(pat_text)
+    async with db.session() as data:
+        pat = await data.personal_access_token(token_hash).get()
+    return bool(pat and pat.is_system)
+
+
 @contextlib.asynccontextmanager
 async def read(asf_uid: principal.UID = principal.ArgumentNone) -> AsyncGenerator[Read]:
     if asf_uid is principal.ArgumentNone:
@@ -594,6 +618,13 @@ async def write_as_project_release_manager(
         yield await w.as_project_release_manager(project_key)
 
 
+@contextlib.asynccontextmanager
+async def write_as_system_service(asf_uid: str) -> AsyncGenerator[WriteAsSystemService]:
+    async with db.session() as data:
+        wss = WriteAsSystemService(data, asf_uid)
+        yield wss
+
+
 @contextlib.asynccontextmanager
 async def write_as_user_service(asf_uid: str) -> AsyncGenerator[WriteAsUserService]:
     async with db.session() as data:
diff --git a/atr/storage/readers/tokens.py b/atr/storage/readers/tokens.py
index 02436346..2f6ee247 100644
--- a/atr/storage/readers/tokens.py
+++ b/atr/storage/readers/tokens.py
@@ -46,12 +46,9 @@ class FoundationCommitter(GeneralPublic):
         if asf_uid is None:
             raise ValueError("Not authorized")
         via = sql.validate_instrumented_attribute
-        stmt = (
-            sqlmodel.select(sql.PersonalAccessToken)
-            .where(sql.PersonalAccessToken.asfuid == asf_uid)
-            .order_by(via(sql.PersonalAccessToken.created))
+        tokens = await (
+            self.__data.personal_access_token(asfuid=asf_uid).order_by(via(sql.PersonalAccessToken.created)).all()
         )
-        tokens = await self.__data.query_all(stmt)
         return [types.PersonalAccessTokenSafe.from_sql(token) for token in tokens]
 
     async def most_recent_jwt_pat(self) -> types.PersonalAccessTokenSafe | None:
diff --git a/atr/storage/types.py b/atr/storage/types.py
index 8d005530..463d0eef 100644
--- a/atr/storage/types.py
+++ b/atr/storage/types.py
@@ -81,6 +81,7 @@ class PathInfo(schema.Strict):
 
 
 class PersonalAccessTokenSafe(schema.Strict):
+    allowed_ip: str | None
     asfuid: str
     created: datetime.datetime
     expires: datetime.datetime
@@ -94,6 +95,7 @@ class PersonalAccessTokenSafe(schema.Strict):
             raise ValueError("PAT must have an ID before being returned")
         return cls(
             id=token.id,
+            allowed_ip=token.allowed_ip,
             asfuid=token.asfuid,
             created=token.created,
             expires=token.expires,
diff --git a/atr/storage/writers/policy.py b/atr/storage/writers/policy.py
index 088b1f37..d693ac71 100644
--- a/atr/storage/writers/policy.py
+++ b/atr/storage/writers/policy.py
@@ -230,30 +230,7 @@ class CommitteeMember(CommitteeParticipant):
         project_key: models.safe.ProjectKey,
         update: models.api.PolicyUpdateArgs,
     ) -> None:
-        # TODO: Ideally we would centralise the validation in this method
-        project, release_policy = await self.__get_or_create_policy(project_key)
-        fields_to_update = update.model_fields_set - {"manual_vote", "project", "vote_mode"}
-        normalised_values: dict[str, Any] = {}
-
-        self.__set_policy_vote_mode_from_api(project, release_policy, update)
-
-        for field in fields_to_update:
-            value = getattr(update, field)
-            if (value is None) and (field not in _NULLABLE_POLICY_FIELDS):
-                raise ValueError(f"Field '{field}' does not accept null")
-            normalised_values[field] = value
-
-        if ("file_tag_mappings" in fields_to_update) and (update.file_tag_mappings is not None):
-            _validate_file_tag_mappings(update.file_tag_mappings)
-
-        if ("min_hours" in fields_to_update) and (update.min_hours is not None):
-            models.validation.validate_policy_min_hours(update.min_hours)
-
-        if fields_to_update & _TRUSTED_PUBLISHING_FIELDS:
-            normalised_values.update(_normalise_trusted_publishing_update(release_policy, normalised_values))
-
-        for field in fields_to_update:
-            setattr(release_policy, field, normalised_values[field])
+        await _apply_policy_update_no_commit(self.__data, project_key, update)
 
     async def edit_finish(self, form: shared.projects.FinishPolicyForm) -> None:
         project_key = form.project_key
@@ -349,17 +326,7 @@ class CommitteeMember(CommitteeParticipant):
     async def __get_or_create_policy(
         self, project_key: models.safe.ProjectKey
     ) -> tuple[models.sql.Project, models.sql.ReleasePolicy]:
-        project = await self.__data.project(
-            key=str(project_key), status=models.sql.ProjectStatus.ACTIVE, _release_policy=True, _committee=True
-        ).demand(storage.AccessError(f"Project {project_key} not found", status=404))
-
-        release_policy = project.release_policy
-        if release_policy is None:
-            release_policy = models.sql.ReleasePolicy(project=project)
-            project.release_policy = release_policy
-            self.__data.add(release_policy)
-
-        return project, release_policy
+        return await _get_or_create_policy(self.__data, project_key)
 
     def __set_announce_release_subject(
         self,
@@ -406,30 +373,6 @@ class CommitteeMember(CommitteeParticipant):
         else:
             release_policy.min_hours = submitted_min_hours
 
-    def __set_policy_vote_mode_from_api(
-        self,
-        project: models.sql.Project,
-        release_policy: models.sql.ReleasePolicy,
-        update: models.api.PolicyUpdateArgs,
-    ) -> None:
-        if "vote_mode" in update.model_fields_set:
-            if update.vote_mode is None:
-                raise ValueError("Field 'vote_mode' does not accept null")
-            if (update.vote_mode == models.sql.VoteMode.MANUAL) and project.committee and project.committee.is_podling:
-                raise storage.AccessError("Manual voting is not allowed for podlings.", status=400)
-            release_policy.vote_mode = update.vote_mode
-            return
-        if "manual_vote" not in update.model_fields_set:
-            return
-        if update.manual_vote is None:
-            raise ValueError("Field 'manual_vote' does not accept null")
-        if update.manual_vote:
-            if project.committee and project.committee.is_podling:
-                raise storage.AccessError("Manual voting is not allowed for podlings.", status=400)
-            release_policy.vote_mode = models.sql.VoteMode.MANUAL
-        else:
-            release_policy.vote_mode = models.sql.VoteMode.EMAIL
-
     def __set_start_vote_subject(
         self,
         submitted_subject: str,
@@ -463,6 +406,66 @@ class CommitteeMember(CommitteeParticipant):
             release_policy.start_vote_template = submitted_template
 
 
+class SystemService:
+    def __init__(self, write_as: storage.WriteAsSystemService, data: db.Session):
+        self.__data = data
+
+    async def _edit_policy_no_commit(
+        self,
+        project_key: models.safe.ProjectKey,
+        update: models.api.PolicyUpdateArgs,
+    ) -> None:
+        await _apply_policy_update_no_commit(self.__data, project_key, update)
+
+
+async def _apply_policy_update_no_commit(
+    data: db.Session,
+    project_key: models.safe.ProjectKey,
+    update: models.api.PolicyUpdateArgs,
+) -> None:
+    # TODO: Ideally we would centralise the validation in this function
+    project, release_policy = await _get_or_create_policy(data, project_key)
+    fields_to_update = update.model_fields_set - {"manual_vote", "project", "vote_mode"}
+    normalised_values: dict[str, Any] = {}
+
+    _set_policy_vote_mode_from_api(project, release_policy, update)
+
+    for field in fields_to_update:
+        value = getattr(update, field)
+        if (value is None) and (field not in _NULLABLE_POLICY_FIELDS):
+            raise ValueError(f"Field '{field}' does not accept null")
+        normalised_values[field] = value
+
+    if ("file_tag_mappings" in fields_to_update) and (update.file_tag_mappings is not None):
+        _validate_file_tag_mappings(update.file_tag_mappings)
+
+    if ("min_hours" in fields_to_update) and (update.min_hours is not None):
+        models.validation.validate_policy_min_hours(update.min_hours)
+
+    if fields_to_update & _TRUSTED_PUBLISHING_FIELDS:
+        normalised_values.update(_normalise_trusted_publishing_update(release_policy, normalised_values))
+
+    for field in fields_to_update:
+        setattr(release_policy, field, normalised_values[field])
+
+
+async def _get_or_create_policy(
+    data: db.Session,
+    project_key: models.safe.ProjectKey,
+) -> tuple[models.sql.Project, models.sql.ReleasePolicy]:
+    project = await data.project(
+        key=str(project_key), status=models.sql.ProjectStatus.ACTIVE, _release_policy=True, _committee=True
+    ).demand(storage.AccessError(f"Project {project_key} not found", status=404))
+
+    release_policy = project.release_policy
+    if release_policy is None:
+        release_policy = models.sql.ReleasePolicy(project=project)
+        project.release_policy = release_policy
+        data.add(release_policy)
+
+    return project, release_policy
+
+
 def _normalise_text_list(values: list[str]) -> list[str]:
     return [value.strip() for value in values if value.strip()]
 
@@ -500,6 +503,30 @@ def _normalise_trusted_publishing_update(
     return normalised_values
 
 
+def _set_policy_vote_mode_from_api(
+    project: models.sql.Project,
+    release_policy: models.sql.ReleasePolicy,
+    update: models.api.PolicyUpdateArgs,
+) -> None:
+    if "vote_mode" in update.model_fields_set:
+        if update.vote_mode is None:
+            raise ValueError("Field 'vote_mode' does not accept null")
+        if (update.vote_mode == models.sql.VoteMode.MANUAL) and project.committee and project.committee.is_podling:
+            raise storage.AccessError("Manual voting is not allowed for podlings.", status=400)
+        release_policy.vote_mode = update.vote_mode
+        return
+    if "manual_vote" not in update.model_fields_set:
+        return
+    if update.manual_vote is None:
+        raise ValueError("Field 'manual_vote' does not accept null")
+    if update.manual_vote:
+        if project.committee and project.committee.is_podling:
+            raise storage.AccessError("Manual voting is not allowed for podlings.", status=400)
+        release_policy.vote_mode = models.sql.VoteMode.MANUAL
+    else:
+        release_policy.vote_mode = models.sql.VoteMode.EMAIL
+
+
 def _split_lines(text: str) -> list[str]:
     return [line.strip() for line in text.split("\n") if line.strip()]
 
diff --git a/atr/storage/writers/project.py b/atr/storage/writers/project.py
index 9e1e5be6..5ff4a019 100644
--- a/atr/storage/writers/project.py
+++ b/atr/storage/writers/project.py
@@ -152,7 +152,7 @@ class CommitteeMember(CommitteeParticipant):
 
     async def create(self, committee_key: safe.CommitteeKey, display_name: str, project_key: safe.ProjectKey) -> None:
         try:
-            await self._build_and_add_project_no_commit(committee_key, display_name, project_key)
+            await _build_and_add_project(self.__data, self.__asf_uid, committee_key, display_name, project_key)
             await self.__data.commit()
         except sqlalchemy.exc.IntegrityError as e:
             if (
@@ -168,53 +168,6 @@ class CommitteeMember(CommitteeParticipant):
             project_key=str(project_key),
         )
 
-    async def _build_and_add_project_no_commit(
-        self,
-        committee_key: safe.CommitteeKey,
-        display_name: str,
-        project_key: safe.ProjectKey,
-    ) -> sql.Project:
-        super_project = None
-        key = str(project_key)
-        # Get the base project to derive from
-        # We're allowing derivation from a retired project here
-        # TODO: Should we disallow this instead?
-        committee_projects = await self.__data.project(
-            committee_key=str(committee_key), _committee=True, _release_policy=True
-        ).all()
-        for committee_project in committee_projects:
-            if key.startswith(str(committee_project.key) + "-"):
-                if (super_project is None) or (len(str(super_project.key)) < len(str(committee_project.key))):
-                    super_project = committee_project
-
-        # Check whether the project already exists
-        if await self.__data.project(key=key).get():
-            raise storage.AccessError(f"Project {key} already exists", status=409)
-
-        now = datetime.datetime.now(datetime.UTC)
-        project = sql.Project(
-            key=key,
-            name=display_name,
-            status=sql.ProjectStatus.ACTIVE,
-            super_project_key=super_project.key if super_project else None,
-            description=super_project.description if super_project else None,
-            category=super_project.category if super_project else None,
-            programming_languages=super_project.programming_languages if super_project else None,
-            version_method=super_project.version_method if super_project else sql.VersionMethod.SIMPLE,
-            version_pattern=super_project.version_pattern if super_project else None,
-            cycle_match=super_project.cycle_match if super_project else None,
-            branch_template=super_project.branch_template if super_project else None,
-            committee_key=str(committee_key),
-            created=now,
-            created_by=self.__asf_uid,
-            updated=now,
-            updated_by=self.__asf_uid,
-        )
-        if super_project and super_project.release_policy:
-            project.release_policy = super_project.release_policy.duplicate()
-        self.__data.add(project)
-        return project
-
     async def archive(self, project_key: safe.ProjectKey) -> None:
         project = await self.__data.project(key=str(project_key), status=sql.ProjectStatus.ACTIVE, _releases=True).get()
 
@@ -350,6 +303,29 @@ class CommitteeMember(CommitteeParticipant):
             return True
         return False
 
+    def __current_categories(self, project: sql.Project) -> list[str]:
+        return (
+            [category.strip() for category in (project.category or "").split(",") if category.strip()]
+            if project.category
+            else []
+        )
+
+    def __current_languages(self, project: sql.Project) -> list[str]:
+        return (
+            [language.strip() for language in (project.programming_languages or "").split(",") if language.strip()]
+            if project.programming_languages
+            else []
+        )
+
+
+# No committee gate - the caller's right to act for the committee must be
+# established upstream, in the .asf.yaml feature.
+class SystemService:
+    def __init__(self, write_as: storage.WriteAsSystemService, data: db.Session):
+        self.__write_as = write_as
+        self.__data = data
+        self.__asf_uid = write_as.asf_uid
+
     async def upsert_config(
         self,
         args: api.ProjectConfigArgs,
@@ -368,7 +344,7 @@ class CommitteeMember(CommitteeParticipant):
                 )
                 await self.__write_as.policy._edit_policy_no_commit(args.project_key, policy_update)
             project.updated = datetime.datetime.now(datetime.UTC)
-            project.updated_by = "API"
+            project.updated_by = self.__asf_uid
             await self.__data.commit()
         except sqlalchemy.exc.IntegrityError as e:
             await self.__data.rollback()
@@ -406,8 +382,12 @@ class CommitteeMember(CommitteeParticipant):
             return existing, False
         if (args.project is None) or (args.project.name is None) or (not args.project.name.strip()):
             raise ValueError(f"Project '{args.project_key}' does not exist; project.name is required to create it")
-        project = await self._build_and_add_project_no_commit(
-            args.committee_key, display_name=args.project.name, project_key=args.project_key
+        project = await _build_and_add_project(
+            self.__data,
+            self.__asf_uid,
+            args.committee_key,
+            display_name=args.project.name,
+            project_key=args.project_key,
         )
         return project, True
 
@@ -446,16 +426,51 @@ class CommitteeMember(CommitteeParticipant):
         if version_scheme_fields & provided:
             await cycles.reassign_release_cycles(self.__data, project)
 
-    def __current_categories(self, project: sql.Project) -> list[str]:
-        return (
-            [category.strip() for category in (project.category or "").split(",") if category.strip()]
-            if project.category
-            else []
-        )
 
-    def __current_languages(self, project: sql.Project) -> list[str]:
-        return (
-            [language.strip() for language in (project.programming_languages or "").split(",") if language.strip()]
-            if project.programming_languages
-            else []
-        )
+async def _build_and_add_project(
+    data: db.Session,
+    asf_uid: str,
+    committee_key: safe.CommitteeKey,
+    display_name: str,
+    project_key: safe.ProjectKey,
+) -> sql.Project:
+    super_project = None
+    key = str(project_key)
+    # Get the base project to derive from
+    # We're allowing derivation from a retired project here
+    # TODO: Should we disallow this instead?
+    committee_projects = await data.project(
+        committee_key=str(committee_key), _committee=True, _release_policy=True
+    ).all()
+    for committee_project in committee_projects:
+        if key.startswith(str(committee_project.key) + "-"):
+            if (super_project is None) or (len(str(super_project.key)) < len(str(committee_project.key))):
+                super_project = committee_project
+
+    # Check whether the project already exists
+    if await data.project(key=key).get():
+        raise storage.AccessError(f"Project {key} already exists", status=409)
+
+    now = datetime.datetime.now(datetime.UTC)
+    project = sql.Project(
+        key=key,
+        name=display_name,
+        status=sql.ProjectStatus.ACTIVE,
+        super_project_key=super_project.key if super_project else None,
+        description=super_project.description if super_project else None,
+        category=super_project.category if super_project else None,
+        programming_languages=super_project.programming_languages if super_project else None,
+        version_method=super_project.version_method if super_project else sql.VersionMethod.SIMPLE,
+        version_pattern=super_project.version_pattern if super_project else None,
+        cycle_match=super_project.cycle_match if super_project else None,
+        branch_template=super_project.branch_template if super_project else None,
+        committee_key=str(committee_key),
+        created=now,
+        created_by=asf_uid,
+        updated=now,
+        updated_by=asf_uid,
+    )
+    if super_project and super_project.release_policy:
+        project.release_policy = super_project.release_policy.duplicate()
+    data.add(project)
+    return project
diff --git a/atr/storage/writers/tokens.py b/atr/storage/writers/tokens.py
index 06f07cdd..d121791e 100644
--- a/atr/storage/writers/tokens.py
+++ b/atr/storage/writers/tokens.py
@@ -22,8 +22,6 @@ import asyncio
 import datetime
 import hashlib
 
-import sqlmodel
-
 import atr.db as db
 import atr.jwtoken as jwtoken
 import atr.ldap as ldap
@@ -86,12 +84,7 @@ class FoundationCommitter(GeneralPublic):
     # audit_guidance PAT deletion revokes associated JWTs
     # audit_guidance JWT verification rechecks PAT existence on every API request
     async def delete_token(self, token_id: int) -> None:
-        pat: sql.PersonalAccessToken | None = await self.__data.query_one_or_none(
-            sqlmodel.select(sql.PersonalAccessToken).where(
-                sql.PersonalAccessToken.id == token_id,
-                sql.PersonalAccessToken.asfuid == self.__asf_uid,
-            )
-        )
+        pat = await self.__data.personal_access_token(id=token_id, asfuid=self.__asf_uid).get()
         if pat is not None:
             await self.__data.delete(pat)
             await self.__data.commit()
@@ -110,15 +103,10 @@ class FoundationCommitter(GeneralPublic):
             )
             await self.__write_as.mail.send(message, mail.MailFooterCategory.AUTO)
 
-    async def issue_jwt(self, pat_text: str) -> str:
-        pat_hash = hashlib.sha3_256(pat_text.encode()).hexdigest()
-        pat = await self.__data.query_one_or_none(
-            sqlmodel.select(sql.PersonalAccessToken).where(
-                sql.PersonalAccessToken.asfuid == self.__asf_uid,
-                sql.PersonalAccessToken.token_hash == pat_hash,
-            )
-        )
-        if (pat is None) or (pat.expires < datetime.datetime.now(datetime.UTC)):
+    async def issue_jwt(self, pat_text: str, client_ip: str | None) -> str:
+        pat_hash = hash_pat(pat_text)
+        pat = await self.__data.personal_access_token(pat_hash, asfuid=self.__asf_uid).get()
+        if (pat is None) or pat.is_expired or (not pat.allows_ip(client_ip)):
             log.warning(
                 "Authentication failed",
                 extra={
@@ -127,9 +115,8 @@ class FoundationCommitter(GeneralPublic):
             )
             raise storage.AccessError("Authentication failed", status=401)
 
-        # Verify account still exists in LDAP
-        account_details = await ldap.account_lookup(self.__asf_uid)
-        if (account_details is None) or ldap.is_banned(account_details):
+        # Verify account still exists in LDAP and is not banned
+        if not await ldap.is_active(self.__asf_uid):
             log.auth_failure("jwt_issuance", "account_deleted_or_banned", self.__asf_uid)
             raise storage.AccessError("Authentication failed", status=401)
 
@@ -198,11 +185,49 @@ class FoundationAdmin(FoundationCommitter):
             raise storage.AccessError("Not authorized", status=403)
         self.__asf_uid = asf_uid
 
+    async def add_system_token(
+        self,
+        token_hash: str,
+        created: datetime.datetime,
+        expires: datetime.datetime,
+        label: str,
+        allowed_ip: str | None,
+    ) -> types.PersonalAccessTokenSafe:
+        if not label:
+            raise ValueError("Label is required")
+        # asfuid records the creating admin, not a token owner. No notification
+        # email - this is not a user's token.
+        pat = sql.PersonalAccessToken(
+            asfuid=self.__asf_uid,
+            token_hash=token_hash,
+            created=created,
+            expires=expires,
+            label=label,
+            is_system=True,
+            allowed_ip=allowed_ip,
+        )
+        self.__data.add(pat)
+        await self.__data.commit()
+        self.__write_as.append_to_audit_log(
+            asf_uid=self.__asf_uid,
+            pat_hash=token_hash,
+            is_system=True,
+            allowed_ip=allowed_ip,
+        )
+        log.auth_event("system_pat_issuance", self.__asf_uid, pat_hash=token_hash, name=label)
+        return types.PersonalAccessTokenSafe.from_sql(pat)
+
+    async def list_system_tokens(self) -> list[types.PersonalAccessTokenSafe]:
+        tokens = await (
+            self.__data.personal_access_token(is_system=True)
+            .order_by(sql.validate_instrumented_attribute(sql.PersonalAccessToken.created))
+            .all()
+        )
+        return [types.PersonalAccessTokenSafe.from_sql(token) for token in tokens]
+
     async def revoke_all_user_tokens(self, target_asf_uid: str) -> int:
         """Revoke all PATs for a specified user. Returns count of revoked tokens."""
-        tokens = await self.__data.query_all(
-            sqlmodel.select(sql.PersonalAccessToken).where(sql.PersonalAccessToken.asfuid == target_asf_uid)
-        )
+        tokens = await self.__data.personal_access_token(asfuid=target_asf_uid).all()
         count = len(tokens)
         for token in tokens:
             await self.__data.delete(token)
@@ -224,6 +249,21 @@ class FoundationAdmin(FoundationCommitter):
             await self.__write_as.mail.send(message, mail.MailFooterCategory.AUTO)
         return count
 
+    async def revoke_system_token(self, token_id: int) -> bool:
+        pat = await self.__data.personal_access_token(id=token_id, is_system=True).get()
+        if pat is None:
+            return False
+        await self.__data.delete(pat)
+        await self.__data.commit()
+        self.__write_as.append_to_audit_log(
+            asf_uid=self.__asf_uid,
+            pat_hash=pat.token_hash,
+            token_id=token_id,
+            is_system=True,
+        )
+        log.auth_event("system_pat_revoke", self.__asf_uid, pat_hash=pat.token_hash, name=pat.label)
+        return True
+
     async def rotate_jwt_signing_key(self) -> None:
         key = await asyncio.to_thread(jwtoken.write_new_signing_key)
         log.auth_event("jwt_key_rotation", self.__asf_uid)
@@ -232,3 +272,52 @@ class FoundationAdmin(FoundationCommitter):
             asf_uid=self.__asf_uid,
             action="rotate_jwt_signing_key",
         )
+
+
+class SystemService:
+    def __init__(self, write_as: storage.WriteAsSystemService, data: db.Session):
+        self.__write_as = write_as
+        self.__data = data
+        self.__asf_uid = write_as.asf_uid
+
+    async def issue_jwt(self, pat_text: str, client_ip: str | None) -> str:
+        # Look up by hash alone - a system PAT's asfuid is its creator, not the
+        # requesting identity, so we can't filter on it here.
+        pat_hash = hash_pat(pat_text)
+        pat = await self.__data.personal_access_token(pat_hash).get()
+        # No LDAP check, unlike the user path - the is_system flag and the fixed
+        # service identity the caller asked for are the gate.
+        if (
+            (pat is None)
+            or (not pat.is_system)
+            or (self.__asf_uid != jwtoken.SYSTEM_SERVICE_UID)
+            or pat.is_expired
+            or (not pat.allows_ip(client_ip))
+        ):
+            log.warning(
+                "Authentication failed",
+                extra={
+                    "reason": "invalid_or_expired_system_pat",
+                },
+            )
+            raise storage.AccessError("Authentication failed", status=401)
+
+        # The JWT carries the fixed service identity; the PAT's creator and name
+        # go to the audit log.
+        issued_jwt = jwtoken.issue(jwtoken.SYSTEM_SERVICE_UID, pat_hash=pat_hash, system=True)
+        log.auth_event(
+            "jwt_issued", jwtoken.SYSTEM_SERVICE_UID, pat_hash=pat_hash, created_by=pat.asfuid, name=pat.label
+        )
+        pat.last_used = datetime.datetime.now(datetime.UTC)
+        await self.__data.commit()
+        self.__write_as.append_to_audit_log(
+            asf_uid=jwtoken.SYSTEM_SERVICE_UID,
+            pat_hash=pat_hash,
+            created_by=pat.asfuid,
+            name=pat.label,
+        )
+        return issued_jwt
+
+
+def hash_pat(pat_text: str) -> str:
+    return hashlib.sha3_256(pat_text.encode()).hexdigest()
diff --git a/atr/templates/includes/topnav.html b/atr/templates/includes/topnav.html
index d782a0a1..ed46b321 100644
--- a/atr/templates/includes/topnav.html
+++ b/atr/templates/includes/topnav.html
@@ -226,6 +226,11 @@
                    href="{{ as_url(admin.revoke_user_tokens_get) }}"
                    {% if request.endpoint == 'atr_admin_revoke_user_tokens_get' %}class="active"{% endif %}><i class="bi bi-shield-x"></i> Revoke user tokens</a>
               </li>
+              <li>
+                <a class="dropdown-item"
+                   href="{{ as_url(admin.system_tokens_get) }}"
+                   {% if request.endpoint == 'atr_admin_system_tokens_get' %}class="active"{% endif %}><i class="bi bi-key"></i> System tokens</a>
+              </li>
               <li>
                 <a class="dropdown-item"
                    href="{{ as_url(admin.revoke_user_ssh_keys_get) }}"
diff --git a/migrations/versions/0086_2026.05.22_383a2b3d.py b/migrations/versions/0086_2026.05.22_383a2b3d.py
new file mode 100644
index 00000000..780e0643
--- /dev/null
+++ b/migrations/versions/0086_2026.05.22_383a2b3d.py
@@ -0,0 +1,34 @@
+"""Add is_system flag and allowed_ip to personal access tokens
+
+Revision ID: 0086_2026.05.22_383a2b3d
+Revises: 0085_2025.05.19_9d086f7e
+Create Date: 2026-05-25 08:56:58.627368+00:00
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# Revision identifiers, used by Alembic
+revision: str = "0086_2026.05.22_383a2b3d"
+down_revision: str | None = "0085_2025.05.19_9d086f7e"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+    with op.batch_alter_table("personalaccesstoken", schema=None) as batch_op:
+        # Existing tokens predate the flag, so default them to non-system.
+        batch_op.add_column(
+            sa.Column("is_system", sa.Boolean(), nullable=False, server_default=sa.false()),
+        )
+        batch_op.add_column(
+            sa.Column("allowed_ip", sa.String(), nullable=True),
+        )
+
+
+def downgrade() -> None:
+    with op.batch_alter_table("personalaccesstoken", schema=None) as batch_op:
+        batch_op.drop_column("allowed_ip")
+        batch_op.drop_column("is_system")
diff --git a/tests/unit/test_ldap.py b/tests/unit/test_ldap.py
index cde86e5d..8645f858 100644
--- a/tests/unit/test_ldap.py
+++ b/tests/unit/test_ldap.py
@@ -282,11 +282,14 @@ def _mock_db_session(token_items: list | None = None, ssh_key_items: list | None
 
     # execute() is called twice: first for tokens, then for SSH keys
     # Each result needs .scalars().all() to return the items
-    token_result = mock.MagicMock()
-    token_result.scalars.return_value.all.return_value = token_items or []
+    pat_query = mock.MagicMock()
+    pat_query.all = mock.AsyncMock(return_value=token_items or [])
+    mock_data.personal_access_token = mock.MagicMock(return_value=pat_query)
+
+    # execute() is now called only for SSH keys.
     ssh_result = mock.MagicMock()
     ssh_result.scalars.return_value.all.return_value = ssh_key_items or []
-    mock_data.execute = mock.AsyncMock(side_effect=[token_result, ssh_result])
+    mock_data.execute = mock.AsyncMock(return_value=ssh_result)
 
     mock_session_ctx = mock.AsyncMock()
     mock_session_ctx.__aenter__ = mock.AsyncMock(return_value=mock_data)
diff --git a/tests/unit/test_tokens_safe.py b/tests/unit/test_tokens_safe.py
index 8d4eaa65..c6381249 100644
--- a/tests/unit/test_tokens_safe.py
+++ b/tests/unit/test_tokens_safe.py
@@ -18,6 +18,7 @@
 import datetime
 import unittest.mock as mock
 
+import asfquart.base as base
 import jwt
 import pytest
 
@@ -38,13 +39,29 @@ class FakeRead:
         self.authorisation = FakeAuthorisation(asf_uid)
 
 
+class FakeQuery:
+    """Mimics db.Query: sync order_by chains, async all/get terminate."""
+
+    def __init__(self, tokens: list[sql.PersonalAccessToken]):
+        self._tokens = tokens
+
+    def order_by(self, *_args: object) -> "FakeQuery":
+        return self
+
+    async def all(self) -> list[sql.PersonalAccessToken]:
+        return self._tokens
+
+    async def get(self) -> sql.PersonalAccessToken | None:
+        return self._tokens[0] if self._tokens else None
+
+
 class FakeReadData:
     def __init__(self, tokens: list[sql.PersonalAccessToken], most_recent: sql.PersonalAccessToken | None):
         self._tokens = tokens
         self._most_recent = most_recent
 
-    async def query_all(self, _stmt):
-        return self._tokens
+    def personal_access_token(self, *_args: object, **_kwargs: object) -> FakeQuery:
+        return FakeQuery(self._tokens)
 
     async def query_one_or_none(self, _stmt):
         return self._most_recent
@@ -59,20 +76,46 @@ class FakeWriteAs:
     def __init__(self):
         self.mail = mock.MagicMock()
         self.mail.send = mock.AsyncMock(return_value=("mid", []))
+        self.append_to_audit_log = mock.MagicMock()
 
 
 class FakeWriteData:
-    def __init__(self):
+    def __init__(self, tokens: list[sql.PersonalAccessToken] | None = None):
         self._added: sql.PersonalAccessToken | None = None
+        self._tokens = tokens if tokens is not None else []
+        self.deleted: list[sql.PersonalAccessToken] = []
 
     def add(self, pat: sql.PersonalAccessToken) -> None:
         self._added = pat
 
+    async def delete(self, pat: sql.PersonalAccessToken) -> None:
+        self.deleted.append(pat)
+
     async def commit(self) -> None:
         if self._added is None:
             return
         self._added.id = 101
 
+    def personal_access_token(self, *_args: object, **_kwargs: object) -> FakeQuery:
+        return FakeQuery(self._tokens)
+
+
+def _make_pat(
+    *,
+    expires: datetime.datetime | None = None,
+    allowed_ip: str | None = None,
+    is_system: bool = False,
+) -> sql.PersonalAccessToken:
+    now = datetime.datetime.now(tz=datetime.UTC)
+    return sql.PersonalAccessToken(
+        asfuid="test",
+        token_hash="0" * 64,
+        created=now,
+        expires=expires if expires is not None else now + datetime.timedelta(days=1),
+        allowed_ip=allowed_ip,
+        is_system=is_system,
+    )
+
 
 def test_personal_access_token_safe_excludes_token_hash() -> None:
     token = sql.PersonalAccessToken(
@@ -161,3 +204,159 @@ async def test_writer_add_token_returns_safe_token() -> None:
     assert isinstance(safe, types.PersonalAccessTokenSafe)
     assert safe.id == 101
     assert "token_hash" not in safe.model_dump()
+
+
+def test_is_expired() -> None:
+    now = datetime.datetime.now(tz=datetime.UTC)
+    assert _make_pat(expires=now + datetime.timedelta(days=1)).is_expired is False
+    assert _make_pat(expires=now - datetime.timedelta(days=1)).is_expired is True
+
+
+def test_allows_ip() -> None:
+    unrestricted = _make_pat(allowed_ip=None)
+    assert unrestricted.allows_ip("1.2.3.4") is True
+    assert unrestricted.allows_ip(None) is True
+
+    single = _make_pat(allowed_ip="1.2.3.4")
+    assert single.allows_ip("1.2.3.4") is True
+    assert single.allows_ip("1.2.3.5") is False
+    assert single.allows_ip(None) is False
+    assert single.allows_ip("not-an-ip") is False
+
+    cidr = _make_pat(allowed_ip="10.0.0.0/8")
+    assert cidr.allows_ip("10.1.2.3") is True
+    assert cidr.allows_ip("11.0.0.1") is False
+
+
+@pytest.mark.asyncio
+async def test_writer_add_system_token() -> None:
+    created = datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)
+    write = FakeWrite("admin")
+    write_as = FakeWriteAs()
+    data = FakeWriteData()
+    writer = atr.storage.writers.tokens.FoundationAdmin(write, write_as, data)
+
+    safe = await writer.add_system_token(
+        token_hash="0" * 64,
+        created=created,
+        expires=created + datetime.timedelta(days=180),
+        label="asfyaml",
+        allowed_ip="10.0.0.0/8",
+    )
+
+    assert isinstance(safe, types.PersonalAccessTokenSafe)
+    assert safe.id == 101
+    # asfuid is the creating admin, not the runtime service identity
+    assert safe.asfuid == "admin"
+    assert safe.allowed_ip == "10.0.0.0/8"
+    write_as.append_to_audit_log.assert_called_once()
+    audit_kwargs = write_as.append_to_audit_log.call_args.kwargs
+    assert audit_kwargs["is_system"] is True
+    assert audit_kwargs["allowed_ip"] == "10.0.0.0/8"
+
+
+@pytest.mark.asyncio
+async def test_writer_revoke_system_token() -> None:
+    token = _make_pat(is_system=True)
+    token.id = 5
+    write = FakeWrite("admin")
+    data = FakeWriteData(tokens=[token])
+    writer = atr.storage.writers.tokens.FoundationAdmin(write, FakeWriteAs(), data)
+
+    assert await writer.revoke_system_token(5) is True
+    assert data.deleted == [token]
+
+    empty = FakeWriteData(tokens=[])
+    writer_empty = atr.storage.writers.tokens.FoundationAdmin(write, FakeWriteAs(), empty)
+    assert await writer_empty.revoke_system_token(999) is False
+
+
+def _signed_jwt(
+    secret: str,
+    *,
+    sub: str = jwtoken.SYSTEM_SERVICE_UID,
+    atr_sys: bool = True,
+    atr_th: str | None = "0" * 64,
+) -> str:
+    now = datetime.datetime.now(tz=datetime.UTC)
+    payload: dict[str, object] = {
+        "sub": sub,
+        "iss": jwtoken._ATR_JWT_ISSUER,
+        "aud": jwtoken._ATR_JWT_AUDIENCE,
+        "iat": now,
+        "nbf": now,
+        "exp": now + datetime.timedelta(minutes=30),
+        "jti": "test-jti",
+    }
+    if atr_sys:
+        payload["atr_sys"] = True
+    if atr_th is not None:
+        payload["atr_th"] = atr_th
+    return jwt.encode(payload, secret, algorithm=jwtoken._ALGORITHM)
+
+
+def _fake_db_session(pat: sql.PersonalAccessToken | None) -> mock.MagicMock:
+    pat_query = mock.MagicMock()
+    pat_query.get = mock.AsyncMock(return_value=pat)
+    fake_data = mock.MagicMock()
+    fake_data.personal_access_token = mock.MagicMock(return_value=pat_query)
+    ctx = mock.AsyncMock()
+    ctx.__aenter__ = mock.AsyncMock(return_value=fake_data)
+    ctx.__aexit__ = mock.AsyncMock(return_value=False)
+    return mock.MagicMock(return_value=ctx)
+
+
+@pytest.mark.asyncio
+async def test_verify_system_token_skips_ldap(monkeypatch: pytest.MonkeyPatch) -> None:
+    secret = "a" * 64
+    monkeypatch.setattr("atr.jwtoken._signing_key", lambda: secret)
+    monkeypatch.setattr("atr.ldap.is_active", mock.AsyncMock(side_effect=AssertionError("LDAP consulted")))
+    monkeypatch.setattr("atr.db.session", _fake_db_session(_make_pat(is_system=True)))
+
+    claims = await jwtoken.verify(_signed_jwt(secret))
+
+    assert claims["sub"] == jwtoken.SYSTEM_SERVICE_UID
+    assert claims["atr_sys"] is True
+
+
+@pytest.mark.asyncio
+async def test_verify_system_token_rejects_wrong_subject(monkeypatch: pytest.MonkeyPatch) -> None:
+    secret = "a" * 64
+    monkeypatch.setattr("atr.jwtoken._signing_key", lambda: secret)
+    monkeypatch.setattr("atr.ldap.is_active", mock.AsyncMock(side_effect=AssertionError("LDAP consulted")))
+    monkeypatch.setattr("atr.db.session", _fake_db_session(_make_pat(is_system=True)))
+
+    with pytest.raises(base.ASFQuartException):
+        await jwtoken.verify(_signed_jwt(secret, sub="someuser"))
+
+
+@pytest.mark.asyncio
+async def test_verify_system_token_rejects_non_system_pat(monkeypatch: pytest.MonkeyPatch) -> None:
+    secret = "a" * 64
+    monkeypatch.setattr("atr.jwtoken._signing_key", lambda: secret)
+    monkeypatch.setattr("atr.ldap.is_active", mock.AsyncMock(side_effect=AssertionError("LDAP consulted")))
+    monkeypatch.setattr("atr.db.session", _fake_db_session(_make_pat(is_system=False)))
+
+    with pytest.raises(base.ASFQuartException):
+        await jwtoken.verify(_signed_jwt(secret))
+
+
+@pytest.mark.asyncio
+async def test_verify_system_claim_without_pat_hash_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
+    secret = "a" * 64
+    monkeypatch.setattr("atr.jwtoken._signing_key", lambda: secret)
+    monkeypatch.setattr("atr.ldap.is_active", mock.AsyncMock(side_effect=AssertionError("LDAP consulted")))
+    with pytest.raises(base.ASFQuartException):
+        await jwtoken.verify(_signed_jwt(secret, atr_th=None))
+
+
+@pytest.mark.asyncio
+async def test_verify_user_token_requires_ldap_active(monkeypatch: pytest.MonkeyPatch) -> None:
+    secret = "a" * 64
+    monkeypatch.setattr("atr.jwtoken._signing_key", lambda: secret)
+    is_active = mock.AsyncMock(return_value=False)
+    monkeypatch.setattr("atr.ldap.is_active", is_active)
+
+    with pytest.raises(base.ASFQuartException):
+        await jwtoken.verify(_signed_jwt(secret, sub="someuser", atr_sys=False, atr_th=None))
+    is_active.assert_awaited_once()


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org