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/09/24 10:18:34 UTC

(tooling-trusted-releases) branch arm updated (00ce6c9f -> c1fe2e08)

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 00ce6c9f #1624 - allow setting explicit commit SHA in TP upload flow
     new c1fe2e08 #1624 - allow setting explicit commit SHA in TP upload flow

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   (00ce6c9f)
            \
             N -- N -- N   refs/heads/arm (c1fe2e08)

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/models/api.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)


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


(tooling-trusted-releases) 01/01: #1624 - allow setting explicit commit SHA in TP upload flow

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 c1fe2e087dc13fc6fb26b2901949e70f6d6330cd
Author: Alastair McFarlane <ar...@apache.org>
AuthorDate: Thu Sep 24 11:10:31 2026 +0100

    #1624 - allow setting explicit commit SHA in TP upload flow
---
 atr/api/__init__.py                             |  1 +
 atr/db/interaction.py                           |  8 +--
 atr/docs/authentication-security.md             |  5 +-
 atr/get/compose.py                              |  6 +-
 atr/models/api.py                               |  1 +
 atr/models/args.py                              |  1 +
 atr/models/attestable.py                        |  3 +-
 atr/models/sql.py                               |  2 +
 atr/source.py                                   | 21 +++++-
 atr/ssh.py                                      | 54 +++++++++-----
 atr/storage/writers/revision.py                 | 13 ++++
 atr/storage/writers/ssh.py                      |  5 ++
 atr/tasks/quarantine.py                         |  3 +
 migrations/versions/0131_2026.09.24_67d16fe4.py | 26 +++++++
 tests/unit/test_create_revision.py              | 33 +++++++++
 tests/unit/test_create_revision_quarantine.py   |  3 +
 tests/unit/test_quarantine_task.py              | 15 +++-
 tests/unit/test_source.py                       | 54 +++++++++++++-
 tests/unit/test_ssh_account_status.py           | 96 +++++++++++++++++++++++++
 tests/unit/test_workflow_jti_replay.py          | 18 +++++
 20 files changed, 335 insertions(+), 33 deletions(-)

diff --git a/atr/api/__init__.py b/atr/api/__init__.py
index f1f2a0fc..d7bb6b5b 100644
--- a/atr/api/__init__.py
+++ b/atr/api/__init__.py
@@ -1228,6 +1228,7 @@ async def publisher_ssh_register(
             project.safe_key,
             data.ssh_key,
             payload,
+            source_commit=data.source_commit,
         )
 
     return models.api.PublisherSshRegisterResults(
diff --git a/atr/db/interaction.py b/atr/db/interaction.py
index c0f427a3..2f78b822 100644
--- a/atr/db/interaction.py
+++ b/atr/db/interaction.py
@@ -45,14 +45,14 @@ import atr.user as user
 import atr.util as util
 import atr.web as web
 
+# Infra-provided service account with permission to run ATR workflows
+# audit_guidance required actor for ATR distribution workflows; must not be used for project TP workflows.
+GITHUB_TRUSTED_ROLE_NID: Final[int] = 254436773
 PENDING_QUARANTINE_VOTE_BLOCK_MESSAGE: Final[str] = (
     "Archive validation is still in progress. Please wait for it to complete before starting a vote."
 )
 
 _ATR_DEV_VOTE_RESOLUTION_BYPASS_HOST: Final[str] = "tooling-vm-ec2-de.apache.org"
-# Infra-provided service account with permission to run ATR workflows
-# audit_guidance required actor for ATR distribution workflows; must not be used for project TP workflows.
-_GITHUB_TRUSTED_ROLE_NID: Final[int] = 254436773
 _NO_EXPECTED_VOTE_ROUND: Final[object] = object()
 _TOOLING_COMMITTEE_KEY: Final[str] = "tooling"
 
@@ -1200,7 +1200,7 @@ async def validate_trusted_jwt(publisher: str, jwt: str) -> tuple[github.Trusted
     if publisher != "github":
         raise InteractionError(f"Publisher {publisher} not supported")
     payload = await jwtoken.verify_github_oidc(jwt)
-    if payload.actor_id != _GITHUB_TRUSTED_ROLE_NID:
+    if payload.actor_id != GITHUB_TRUSTED_ROLE_NID:
         try:
             asf_uid = await ldap.github_to_apache(payload.actor_id)
         except ldap.LookupError as e:
diff --git a/atr/docs/authentication-security.md b/atr/docs/authentication-security.md
index f892ff59..fcc44383 100644
--- a/atr/docs/authentication-security.md
+++ b/atr/docs/authentication-security.md
@@ -186,7 +186,7 @@ ATR uses a separate set of endpoints to orchestrate distribution to third-party
 
 **Trust chain.** An authenticated committer initiates a release distribution through ATR. ATR dispatches the workflow via the ASF Infrastructure service account, passing the required context (including the SSH public key) into the workflow. The workflow runs on GitHub Actions and calls back to ATR with a GitHub OIDC token.
 
-**Actor requirement.** `interaction.trusted_jwt_for_dist` checks that `actor_id` matches `_GITHUB_TRUSTED_ROLE_NID`, the hardcoded numeric ID of the ASF Infrastructure service account. If `actor_id` belongs to a human committer instead, the request is rejected. The check uses the numeric ID, which is stable across account renames.
+**Actor requirement.** `interaction.trusted_jwt_for_dist` checks that `actor_id` matches `GITHUB_TRUSTED_ROLE_NID`, the hardcoded numeric ID of the ASF Infrastructure service account. If `actor_id` belongs to a human committer instead, the request is rejected. The check uses the numeric ID, which is stable across account renames.
 
 The OIDC token proves that the callback came from a workflow ATR itself started. The original authorization is inherited from the committer who initiated the distribution in ATR — the service account carries no privileges of its own beyond triggering the workflow.
 
@@ -194,7 +194,8 @@ The workflow also carries the originating committer's ASF UID as a parameter. AT
 
 ### SSH key scope
 
-In both cases, the workflow calls ATR's SSH registration endpoint (`/publisher/ssh/register` for project TP, `/distribute/ssh/register` for distribution workflows), which generates a temporary SSH key bound to the specific project. The key cannot be used for any other project. The identity attached to the key differs: for project TP it is the committer resolved via LDAP from the OIDC `actor_id`; for distribution workflows it is the committer's ASF UID passed through the workflow, trusted [...]
+In both cases, the workflow calls ATR's SSH registration endpoint (`/publisher/ssh/register` for project TP, `/distribute/ssh/register` for distribution workflows), which generates a temporary SSH key bound to the specific project. The key cannot be used for any other project, and `ssh.SSHServer` checks this before it looks anything up, so a key can't be used to find out what exists in other projects. Distribution workflows only download, so their keys are read-only: a key whose `github_ [...]
+The identity attached to the key differs: for project TP it is the committer resolved via LDAP from the OIDC `actor_id`; for distribution workflows it is the committer's ASF UID passed through the workflow, trusted because only the service account — which only ATR can trigger — could have put it there.
 
 **Single-use registration.** An OIDC token registers a key once. `storage.writers.ssh.add_workflow_key` records the token's `jti` in `workflowjti` before it inserts the key, so a token replayed within its validity window fails on the primary key and mints nothing. Rows are pruned once the token's own `exp` has passed. Tokens are not single-use across the other OIDC endpoints, because a workflow mints one token per job and presents it to several of them.
 
diff --git a/atr/get/compose.py b/atr/get/compose.py
index 3b86795d..4f0bac45 100644
--- a/atr/get/compose.py
+++ b/atr/get/compose.py
@@ -301,7 +301,11 @@ async def _commit_hash_form_html(release: sql.Release) -> str:
     selected_source = await source.current(release)
     details = htm.Block(classes=".mb-3")
     if selected_source.sha:
-        basis = "Explicitly supplied" if selected_source.override else "Assumed from workflow"
+        basis = "Assumed from workflow"
+        if selected_source.override:
+            basis = "Explicitly supplied"
+        elif selected_source.declared:
+            basis = "Declared by workflow"
         details.append(htpy.p[f"{basis}: ", htpy.code[selected_source.sha]])
     if selected_source.repository:
         details.append(htpy.p[f"Source repository: {selected_source.repository}"])
diff --git a/atr/models/api.py b/atr/models/api.py
index e46b0e02..f3c00998 100644
--- a/atr/models/api.py
+++ b/atr/models/api.py
@@ -724,6 +724,7 @@ class PublisherSshRegisterArgs(schema.Strict):
     publisher: str = schema.example("user")
     jwt: str = schema.example("eyJhbGciOiJIUzI1[...]mMjLiuyu5CSpyHI=")
     ssh_key: str = schema.example("ssh-ed25519 AAAAC3NzaC1lZDI1NTEgH5C9okWi0dh25AAAAIOMqqnkVzrm0SdG6UOoqKLsabl9GKJl")
+    source_commit: safe.OptionalCommitHash = schema.default_example(None, "0123456789abcdef0123456789abcdef01234567")
 
 
 class PublisherSshRegisterResults(schema.Strict):
diff --git a/atr/models/args.py b/atr/models/args.py
index 5dca37ef..5a5eeb91 100644
--- a/atr/models/args.py
+++ b/atr/models/args.py
@@ -165,6 +165,7 @@ class QuarantineValidate(schema.Strict):
     quarantined_id: int
     archives: list[QuarantineArchiveEntry]
     github_payload: github.TrustedPublisherPayload | None = None
+    source_commit: safe.CommitHash | None = None
 
 
 def _ensure_footer_enum(value: Any) -> mail.MailFooterCategory | None:
diff --git a/atr/models/attestable.py b/atr/models/attestable.py
index 48d74af7..73224e8d 100644
--- a/atr/models/attestable.py
+++ b/atr/models/attestable.py
@@ -74,11 +74,12 @@ class PathEntryV2(schema.Strict):
 class SourceV2(schema.Strict):
     repository: str = ""
     default: str | None = None
+    declared: str | None = None
     override: str | None = None
 
     @property
     def sha(self) -> str:
-        return self.override or self.default or ""
+        return self.override or self.declared or self.default or ""
 
 
 class AttestableV2(schema.Strict):
diff --git a/atr/models/sql.py b/atr/models/sql.py
index 1bbc2680..193f785d 100644
--- a/atr/models/sql.py
+++ b/atr/models/sql.py
@@ -1027,6 +1027,8 @@ class WorkflowSSHKey(sqlmodel.SQLModel, table=True):
     github_payload: dict[str, Any] = sqlmodel.Field(
         default_factory=dict, sa_column=sqlalchemy.Column(sqlalchemy.JSON, nullable=False)
     )
+    # Declared by the workflow rather than signed by GitHub, so kept out of github_payload
+    source_commit: str | None = sqlmodel.Field(default=None)
     expires: int = sqlmodel.Field()
     revoked: bool = sqlmodel.Field(default=False)
 
diff --git a/atr/source.py b/atr/source.py
index d10c92da..c2356c51 100644
--- a/atr/source.py
+++ b/atr/source.py
@@ -31,11 +31,18 @@ def advance(
     source: atr.models.attestable.SourceV2,
     payload: github.TrustedPublisherPayload | None,
     override: db.Opt[str | None] = db.NOT_SET,
+    *,
+    declared: safe.CommitHash | None = None,
 ) -> atr.models.attestable.SourceV2:
     source = source.model_copy()
-    if (payload is not None) and ((not source.override) or (source.repository == payload.repository)):
-        source.repository = payload.repository
+    if payload is not None:
+        ensure_payload_repository(source, payload)
         source.default = payload.sha
+        # The payload sha is only the commit the run started from, so the workflow can tell us what it checked out
+        # An upload that doesn't say should clear any earlier value, otherwise it'd be stale
+        source.declared = str(declared) if (declared is not None) else None
+        # Any manual override described the earlier files, so the upload should win until someone corrects it again
+        source.override = None
     if not isinstance(override, db.NotSet):
         if override and (not source.repository):
             raise ValueError("Configure a GitHub repository for this project before setting its source commit.")
@@ -52,12 +59,20 @@ async def current(release: sql.Release) -> atr.models.attestable.SourceV2:
     return await initial(release, previous)
 
 
+def ensure_payload_repository(source: atr.models.attestable.SourceV2, payload: github.TrustedPublisherPayload) -> None:
+    # A payload from some other repository says nothing about this release's source
+    if source.repository != payload.repository:
+        expected = source.repository or "no configured repository"
+        raise ValueError(f"This release's source is {expected}, but the upload came from {payload.repository}")
+
+
 async def initial(
     release: sql.Release, previous: atr.models.attestable.Attestable | None
 ) -> atr.models.attestable.SourceV2:
     if isinstance(previous, atr.models.attestable.AttestableV2) and (previous.source is not None):
         source = previous.source.model_copy()
-        if not source.repository:
+        # The release policy says where the source lives, so it wins over whatever an earlier revision recorded
+        if release.project.policy_github_repository_name or (not source.repository):
             source.repository = repository(release.project)
         return source
     source = atr.models.attestable.SourceV2(repository=repository(release.project))
diff --git a/atr/ssh.py b/atr/ssh.py
index 9d4d15fd..0e61d94f 100644
--- a/atr/ssh.py
+++ b/atr/ssh.py
@@ -38,6 +38,7 @@ import ssh_audit.builtin_policies as builtin_policies
 
 import atr.config as config
 import atr.db as db
+import atr.db.interaction as interaction
 import atr.ldap as ldap
 import atr.log as log
 import atr.models.github as github
@@ -91,6 +92,9 @@ class SSHServer(asyncssh.SSHServer):
         self._conn = conn
         self._github_asf_uid: str | None = None
         self._github_payload: github.TrustedPublisherPayload | None = None
+        self._github_project_key: safe.ProjectKey | None = None
+        self._github_read_only = False
+        self._github_source_commit: safe.CommitHash | None = None
         peer_addr = conn.get_extra_info("peername")[0]
         log.info(f"SSH connection received from {peer_addr}")
         if not _rate_limit_check(global_ip_rate_buckets, peer_addr, _RATE_LIMIT_IP):
@@ -211,6 +215,11 @@ class SSHServer(asyncssh.SSHServer):
             return False
 
         self._github_payload = github.TrustedPublisherPayload.model_validate(workflow_key.github_payload)
+        self._github_project_key = safe.ProjectKey(workflow_key.project_key)
+        # Only distribution workflows run as the trusted role, and they only need to download
+        self._github_read_only = workflow_key.github_nid == interaction.GITHUB_TRUSTED_ROLE_NID
+        if workflow_key.source_commit is not None:
+            self._github_source_commit = safe.CommitHash(workflow_key.source_commit)
         return True
 
     def _get_asf_uid(self, process: asyncssh.SSHServerProcess) -> str:
@@ -227,6 +236,20 @@ class SSHServer(asyncssh.SSHServer):
             return None
         return self._github_payload
 
+    def _get_github_project_key(self, process: asyncssh.SSHServerProcess) -> safe.ProjectKey | None:
+        username = process.get_extra_info("username")
+        if username != "github":
+            return None
+        if self._github_project_key is None:
+            raise RsyncArgsError("GitHub authentication did not resolve a project")
+        return self._github_project_key
+
+    def _get_github_source_commit(self, process: asyncssh.SSHServerProcess) -> safe.CommitHash | None:
+        username = process.get_extra_info("username")
+        if username != "github":
+            return None
+        return self._github_source_commit
+
 
 async def rate_limit_cleanup_loop() -> None:
     """Periodically remove stale entries from the rate limit buckets."""
@@ -445,9 +468,16 @@ async def _step_04_command_validate(
     ### Calls _step_05a/b_command_path_validate ###
     ############################################
     if is_read_request:
-        project_key, version_key, tag = await _step_05a_command_path_validate_read(argv[-1])
+        project_key, version_key, tag = _step_05a_command_path_validate_read(argv[-1])
     else:
-        project_key, version_key, tag = await _step_05b_command_path_validate_write(argv[-1])
+        project_key, version_key, tag = _step_05b_command_path_validate_write(argv[-1])
+
+    # A workflow key is registered for one project, and the ASF UID behind it may well have access to others
+    workflow_project_key = server._get_github_project_key(process)
+    if (workflow_project_key is not None) and (project_key != workflow_project_key):
+        raise RsyncArgsError(f"This workflow key can only be used for project '{workflow_project_key}'")
+    if (not is_read_request) and server._github_read_only:
+        raise RsyncArgsError("This workflow key can only be used to download files")
 
     ssh_uid = server._get_asf_uid(process)
     async with db.session() as data:
@@ -475,7 +505,7 @@ async def _step_04_command_validate(
     return project_key, version_key, None, None
 
 
-async def _step_05a_command_path_validate_read(path: str) -> tuple[safe.ProjectKey, safe.VersionKey, str | None]:
+def _step_05a_command_path_validate_read(path: str) -> tuple[safe.ProjectKey, safe.VersionKey, str | None]:
     """Validate the path argument for rsync read commands, returning safe datatypes."""
     # READ: rsync --server --sender -vlogDtpre.iLsfxCIvu . /proj/v1/
     # Validating path: /proj/v1/
@@ -495,18 +525,10 @@ async def _step_05a_command_path_validate_read(path: str) -> tuple[safe.ProjectK
         raise RsyncArgsError("Version is invalid")
     if tag:
         _validate_tag_segment(tag)
-
-    async with db.session() as data:
-        release = await data.release(
-            project_key=str(project_key),
-            version=str(version_key),
-        ).get()
-        if release is None:
-            raise RsyncArgsError(f"Release '{path_project}-{path_version}' does not exist")
     return project_key, version_key, tag
 
 
-async def _step_05b_command_path_validate_write(path: str) -> tuple[safe.ProjectKey, safe.VersionKey, None]:
+def _step_05b_command_path_validate_write(path: str) -> tuple[safe.ProjectKey, safe.VersionKey, None]:
     """Validate the path argument for rsync write commands, returning safe datatypes."""
     # WRITE: rsync --server -vlogDtpre.iLsfxCIvu . /proj/v1/
     # Validating path: /proj/v1/
@@ -523,12 +545,6 @@ async def _step_05b_command_path_validate_write(path: str) -> tuple[safe.Project
         version_key = safe.VersionKey(path_version)
     except ValueError:
         raise RsyncArgsError("Version is invalid")
-
-    async with db.session() as data:
-        project = await data.project(key=str(project_key)).get()
-        if project is None:
-            raise RsyncArgsError(f"Project '{project_key}' does not exist")
-
     return project_key, version_key, None
 
 
@@ -697,6 +713,7 @@ async def _step_07b_process_validated_rsync_write(
 
         try:
             github_payload = server._get_github_payload(process)
+            source_commit = server._get_github_source_commit(process)
             result = await wacp.revision.create_revision_with_quarantine(
                 project_key,
                 version_key,
@@ -705,6 +722,7 @@ async def _step_07b_process_validated_rsync_write(
                 description=description,
                 modify=modify,
                 github_payload=github_payload,
+                source_commit=source_commit,
             )
             if isinstance(result, sql.Quarantined):
                 log.info(f"rsync upload quarantined for release {release_key}")
diff --git a/atr/storage/writers/revision.py b/atr/storage/writers/revision.py
index 0b5c0232..b67b71c9 100644
--- a/atr/storage/writers/revision.py
+++ b/atr/storage/writers/revision.py
@@ -99,6 +99,7 @@ async def finalise_revision(
     extracted_swhids: dict[str, str] | None = None,
     sha3_hashes: dict[str, str] | None = None,
     github_payload: github.TrustedPublisherPayload | None = None,
+    source_commit: safe.CommitHash | None = None,
 ) -> sql.Revision:
     try:
         previous_attestable, merge_base_revision_key, _, merged_release = await _lock_and_merge(
@@ -139,6 +140,7 @@ async def finalise_revision(
         extracted_swhids=extracted_swhids,
         sha3_hashes=sha3_hashes,
         github_payload=github_payload,
+        source_commit=source_commit,
     )
 
 
@@ -161,6 +163,7 @@ async def _commit_new_revision(
     extracted_swhids: dict[str, str] | None = None,
     sha3_hashes: dict[str, str] | None = None,
     github_payload: github.TrustedPublisherPayload | None = None,
+    source_commit: safe.CommitHash | None = None,
     source_override: db.Opt[str | None] = db.NOT_SET,
 ) -> sql.Revision:
     try:
@@ -168,6 +171,7 @@ async def _commit_new_revision(
             await source.initial(release, previous_attestable),
             github_payload,
             source_override,
+            declared=source_commit,
         )
         # This is the only place where models.Revision is constructed
         # That makes models.populate_revision_sequence_and_name safe against races
@@ -488,6 +492,7 @@ class CommitteeParticipant(FoundationCommitter):
         clone_from: safe.RevisionNumber | None = None,
         expected_revision: safe.RevisionNumber | None = None,
         github_payload: github.TrustedPublisherPayload | None = None,
+        source_commit: safe.CommitHash | None = None,
         source_override: db.Opt[str | None] = db.NOT_SET,
     ) -> sql.Revision | sql.Quarantined:
         """Create a new revision, quarantining archives that require validation."""
@@ -514,6 +519,10 @@ class CommitteeParticipant(FoundationCommitter):
             else:
                 old_revision = await interaction.latest_revision(release)
 
+        # Checked again when the revision is recorded, but this rejects the upload before any files arrive
+        if github_payload is not None:
+            source.ensure_payload_repository(await source.current(release), github_payload)
+
         if clone_from is not None:
             old_release_dir = paths.release_directory_base(release) / str(clone_from)
         else:
@@ -665,6 +674,7 @@ class CommitteeParticipant(FoundationCommitter):
                         temp_dir=temp_dir,
                         version_key=version_key,
                         github_payload=github_payload,
+                        source_commit=source_commit,
                     )
 
             return await _commit_new_revision(
@@ -683,6 +693,7 @@ class CommitteeParticipant(FoundationCommitter):
                 path_provenance=path_provenance,
                 sha3_hashes=sha3_hashes,
                 github_payload=github_payload,
+                source_commit=source_commit,
                 source_override=source_override,
             )
 
@@ -750,6 +761,7 @@ class CommitteeParticipant(FoundationCommitter):
         temp_dir: str,
         version_key: safe.VersionKey,
         github_payload: github.TrustedPublisherPayload | None = None,
+        source_commit: safe.CommitHash | None = None,
     ) -> sql.Quarantined:
         file_metadata = [
             sql.QuarantineFileEntryV1(
@@ -796,6 +808,7 @@ class CommitteeParticipant(FoundationCommitter):
                     "github_payload": (
                         github_payload.model_dump(exclude={"exp", "nbf"}) if (github_payload is not None) else None
                     ),
+                    "source_commit": source_commit,
                     "archives": [
                         {"rel_path": entry.rel_path, "content_hash": entry.content_hash} for entry in file_metadata
                     ],
diff --git a/atr/storage/writers/ssh.py b/atr/storage/writers/ssh.py
index bb8d8b69..d75a2b93 100644
--- a/atr/storage/writers/ssh.py
+++ b/atr/storage/writers/ssh.py
@@ -104,6 +104,8 @@ class CommitteeParticipant(FoundationCommitter):
         project_key: safe.ProjectKey,
         key: str,
         github_payload: github.TrustedPublisherPayload,
+        *,
+        source_commit: safe.CommitHash | None = None,
     ) -> tuple[str, int]:
         now = int(time.time())
         # Twenty minutes to upload all files
@@ -114,6 +116,7 @@ class CommitteeParticipant(FoundationCommitter):
         fingerprint = util.key_ssh_fingerprint(key)
         # Exclude nbf and exp as we've already validated this key - now protected by workflowkey "expires"
         json_payload = github_payload.model_dump(exclude={"exp", "nbf"})
+        wsk_source_commit = str(source_commit) if (source_commit is not None) else None
         wsk = sql.WorkflowSSHKey(
             fingerprint=fingerprint,
             key=key,
@@ -122,6 +125,7 @@ class CommitteeParticipant(FoundationCommitter):
             github_uid=github_uid,
             github_nid=github_nid,
             github_payload=json_payload,
+            source_commit=wsk_source_commit,
             expires=expires,
         )
         self.__data.add(wsk)
@@ -132,6 +136,7 @@ class CommitteeParticipant(FoundationCommitter):
             project_key=str(project_key),
             github_uid=github_uid,
             github_nid=github_nid,
+            source_commit=wsk_source_commit,
             expires=expires,
         )
         return fingerprint, expires
diff --git a/atr/tasks/quarantine.py b/atr/tasks/quarantine.py
index 49a4776b..a91db13b 100644
--- a/atr/tasks/quarantine.py
+++ b/atr/tasks/quarantine.py
@@ -151,6 +151,7 @@ async def validate(task_args: args.QuarantineValidate) -> results.Results | None
         str(quarantine_dir),
         swhid_dirs,
         github_payload=task_args.github_payload,
+        source_commit=task_args.source_commit,
     )
     return None
 
@@ -357,6 +358,7 @@ async def _promote(
     quarantine_dir: str,
     swhid_dirs: dict[str, str],
     github_payload: github.TrustedPublisherPayload | None = None,
+    source_commit: safe.CommitHash | None = None,
 ) -> None:
     quarantine_dir_path = pathlib.Path(quarantine_dir)
 
@@ -411,6 +413,7 @@ async def _promote(
             extracted_swhids=swhid_dirs,
             sha3_hashes=sha3_hashes,
             github_payload=github_payload,
+            source_commit=source_commit,
         )
 
     async with db.session() as data:
diff --git a/migrations/versions/0131_2026.09.24_67d16fe4.py b/migrations/versions/0131_2026.09.24_67d16fe4.py
new file mode 100644
index 00000000..c87a94cf
--- /dev/null
+++ b/migrations/versions/0131_2026.09.24_67d16fe4.py
@@ -0,0 +1,26 @@
+"""Add a declared source commit to GitHub SSH keys
+
+Revision ID: 0131_2026.09.24_67d16fe4
+Revises: 0130_2026.09.22_d8ffc630
+Create Date: 2026-09-24 08:45:15.192266+00:00
+"""
+
+import collections.abc as abc
+
+import alembic.op as op
+import sqlalchemy
+
+revision: str = "0131_2026.09.24_67d16fe4"
+down_revision: str | None = "0130_2026.09.22_d8ffc630"
+branch_labels: str | abc.Sequence[str] | None = None
+depends_on: str | abc.Sequence[str] | None = None
+
+
+def upgrade() -> None:
+    with op.batch_alter_table("workflowsshkey") as batch_op:
+        batch_op.add_column(sqlalchemy.Column("source_commit", sqlalchemy.String(), nullable=True))
+
+
+def downgrade() -> None:
+    with op.batch_alter_table("workflowsshkey") as batch_op:
+        batch_op.drop_column("source_commit")
diff --git a/tests/unit/test_create_revision.py b/tests/unit/test_create_revision.py
index 2d2009b1..bbd0c49f 100644
--- a/tests/unit/test_create_revision.py
+++ b/tests/unit/test_create_revision.py
@@ -224,6 +224,7 @@ async def test_commit_new_revision_writes_metadata_before_checks(
     )
     release.release_policy = None
     release.project.release_policy = None
+    release.project.policy_github_repository_name = "test"
     release.activity_at = datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)
     safe_data = MockSafeData(parent_key=None)
     payload = github_payload if has_github_payload else None
@@ -872,6 +873,38 @@ async def test_open_for_replace_silently_replaces_readonly_hardlink(tmp_path: pa
     assert target.stat().st_ino != prior_file.stat().st_ino
 
 
+@pytest.mark.asyncio
+async def test_payload_from_other_repository_rejected_before_modify(
+    tmp_path: pathlib.Path, github_payload: github.TrustedPublisherPayload
+):
+    modify = mock.AsyncMock()
+    release = mock.MagicMock()
+    release.phase = sql.ReleasePhase.RELEASE_CANDIDATE_DRAFT
+    release.project.status = sql.ProjectStatus.ACTIVE
+    mock_session = _mock_db_session(release)
+    participant = _make_participant()
+    recorded = atr.models.attestable.SourceV2(repository="apache/other")
+
+    with (
+        mock.patch.object(revision.db, "session", return_value=mock_session),
+        mock.patch.object(revision.interaction, "latest_revision", new_callable=mock.AsyncMock, return_value=None),
+        mock.patch.object(revision.source, "current", new_callable=mock.AsyncMock, return_value=recorded),
+        mock.patch.object(revision.paths, "get_tmp_dir", return_value=safe.StatePath(tmp_path)),
+    ):
+        with pytest.raises(ValueError, match="but the upload came from apache/test"):
+            await participant.create_revision_with_quarantine(
+                safe.ProjectKey("proj"),
+                safe.VersionKey("1.0"),
+                "test",
+                allowed_phases=frozenset({sql.ReleasePhase.RELEASE_CANDIDATE_DRAFT}),
+                modify=modify,
+                github_payload=github_payload,
+            )
+
+    modify.assert_not_awaited()
+    assert not os.listdir(tmp_path)
+
+
 @pytest.mark.asyncio
 async def test_v1_previous_attestable_suppresses_file_state_rows(tmp_path: pathlib.Path):
     temp_dir = safe.StatePath(tmp_path)
diff --git a/tests/unit/test_create_revision_quarantine.py b/tests/unit/test_create_revision_quarantine.py
index f987f278..a87e6e85 100644
--- a/tests/unit/test_create_revision_quarantine.py
+++ b/tests/unit/test_create_revision_quarantine.py
@@ -24,6 +24,7 @@ from typing import Final
 import pytest
 
 import atr.models.args as args
+import atr.models.attestable as attestable_models
 import atr.models.github as github
 import atr.models.safe as safe
 import atr.models.sql as sql
@@ -272,10 +273,12 @@ async def test_quarantine_branch_returns_quarantined_when_archives_detected(
     mock_session = _mock_db_session(release)
     participant = _make_participant()
     safe_data = MockQuarantineData(latest_revision_key=None)
+    recorded_source = attestable_models.SourceV2(repository=github_payload.repository)
 
     quarantine_dir = temp_dir / "quarantine" / "proj" / "1.0" / "testtoken"
 
     patches = [
+        mock.patch.object(revision.source, "current", new_callable=mock.AsyncMock, return_value=recorded_source),
         mock.patch.object(revision.aiofiles.os, "makedirs", new_callable=mock.AsyncMock),
         mock.patch.object(revision.aiofiles.os, "rename", new_callable=mock.AsyncMock),
         mock.patch.object(revision.attestable, "compute_sha3_hashes", new_callable=mock.AsyncMock, return_value={}),
diff --git a/tests/unit/test_quarantine_task.py b/tests/unit/test_quarantine_task.py
index 5108a4f1..5bcd68ab 100644
--- a/tests/unit/test_quarantine_task.py
+++ b/tests/unit/test_quarantine_task.py
@@ -409,6 +409,7 @@ async def test_promote_finalises_revision_and_deletes_quarantined(
     tmp_path: pathlib.Path, github_payload: github.TrustedPublisherPayload, has_github_payload: bool
 ):
     payload = github_payload if has_github_payload else None
+    source_commit = safe.CommitHash("d" * 40) if has_github_payload else None
     quarantine_dir_path = tmp_path / "quarantine"
     quarantine_dir_path.mkdir()
     (quarantine_dir_path / "file.txt").write_bytes(b"file content")
@@ -463,7 +464,14 @@ async def test_promote_finalises_revision_and_deletes_quarantined(
         mock.patch.object(quarantine.db, "session", side_effect=session_calls),
     ):
         await quarantine._promote(
-            quarantined_row, "proj", "1.0", "proj-1.0", quarantine_dir, {}, github_payload=payload
+            quarantined_row,
+            "proj",
+            "1.0",
+            "proj-1.0",
+            quarantine_dir,
+            {},
+            github_payload=payload,
+            source_commit=source_commit,
         )
 
     mock_release_data.release.assert_called_once_with(
@@ -473,6 +481,7 @@ async def test_promote_finalises_revision_and_deletes_quarantined(
     call_kwargs = mock_finalise.call_args.kwargs
     assert call_kwargs["was_quarantined"] is True
     assert mock_commit.await_args.kwargs["github_payload"] is payload
+    assert mock_commit.await_args.kwargs["source_commit"] == source_commit
     assert call_kwargs["project_key"] == "proj"
     assert call_kwargs["release"] is release
     assert call_kwargs["path_to_hash"] == {"file.txt": "hash1"}
@@ -657,9 +666,12 @@ async def test_validate_success_calls_promote(
 ):
     task_args = {"quarantined_id": 1, "archives": [{"rel_path": "ok.tar.gz", "content_hash": "abc"}]}
     payload = None
+    source_commit = None
     if has_github_payload:
         task_args["github_payload"] = github_payload.model_dump(exclude={"exp", "nbf"})
+        task_args["source_commit"] = "d" * 40
         payload = github.TrustedPublisherPayload.model_validate(task_args["github_payload"])
+        source_commit = safe.CommitHash("d" * 40)
     quarantine_dir = tmp_path / "quarantine"
     quarantine_dir.mkdir()
 
@@ -692,6 +704,7 @@ async def test_validate_success_calls_promote(
         str(quarantine_dir),
         {},
         github_payload=payload,
+        source_commit=source_commit,
     )
     mock_mark.assert_not_awaited()
 
diff --git a/tests/unit/test_source.py b/tests/unit/test_source.py
index 5165b6f2..3ec25cf7 100644
--- a/tests/unit/test_source.py
+++ b/tests/unit/test_source.py
@@ -27,14 +27,46 @@ import atr.models.sql as sql
 import atr.source as source
 
 
+@pytest.mark.parametrize("repository", ["apache/other", ""])
+def test_advance_rejects_payload_from_other_repository(repository: str, github_payload: github.TrustedPublisherPayload):
+    selected = atr.models.attestable.SourceV2(repository=repository, default="a" * 40, override="c" * 40)
+    with pytest.raises(ValueError, match="but the upload came from apache/test"):
+        source.advance(selected, github_payload, declared=safe.CommitHash("e" * 40))
+
+
+def test_advance_keeps_override_without_payload():
+    selected = atr.models.attestable.SourceV2(repository="apache/test", default="a" * 40, override="c" * 40)
+    result = source.advance(selected, None)
+    assert result.override == "c" * 40
+    assert result.sha == "c" * 40
+
+
 @pytest.mark.parametrize("override", [None, "c" * 40])
-def test_advance_keeps_source_choice(override: str | None, github_payload: github.TrustedPublisherPayload):
+def test_advance_payload_replaces_override(override: str | None, github_payload: github.TrustedPublisherPayload):
     selected = atr.models.attestable.SourceV2(repository="apache/test", default="a" * 40, override=override)
     result = source.advance(selected, github_payload)
     assert result.default == github_payload.sha
-    assert result.override == override
-    assert result.sha == (override or github_payload.sha)
+    assert result.override is None
+    assert result.sha == github_payload.sha
     assert selected.default == "a" * 40
+    assert selected.override == override
+
+
+def test_advance_prefers_declared_commit_over_payload(github_payload: github.TrustedPublisherPayload):
+    selected = atr.models.attestable.SourceV2(repository="apache/test", default="a" * 40)
+    result = source.advance(selected, github_payload, declared=safe.CommitHash("d" * 40))
+    assert result.default == github_payload.sha
+    assert result.declared == "d" * 40
+    assert result.sha == "d" * 40
+    assert source.advance(result, None, "c" * 40).sha == "c" * 40
+
+
+def test_advance_without_declaration_clears_earlier_one(github_payload: github.TrustedPublisherPayload):
+    selected = atr.models.attestable.SourceV2(repository="apache/test", default="a" * 40, declared="d" * 40)
+    assert source.advance(selected, None).declared == "d" * 40
+    result = source.advance(selected, github_payload)
+    assert result.declared is None
+    assert result.sha == github_payload.sha
 
 
 async def test_initial_accepts_repository_configured_after_first_revision():
@@ -47,6 +79,22 @@ async def test_initial_accepts_repository_configured_after_first_revision():
     assert previous.source.repository == ""
 
 
+async def test_initial_prefers_policy_repository_over_recorded_one():
+    project = sql.Project(
+        key="test",
+        name="Test",
+        repositories=["https://github.com/apache/test"],
+        release_policy=sql.ReleasePolicy(github_repository_name="moved"),
+    )
+    release = sql.Release(project=project, version="1.0")
+    recorded = atr.models.attestable.SourceV2(repository="apache/test", default="a" * 40, override="c" * 40)
+    previous = atr.models.attestable.AttestableV2(source=recorded)
+    selected = await source.initial(release, previous)
+    assert selected.repository == "apache/moved"
+    assert selected.override == "c" * 40
+    assert recorded.repository == "apache/test"
+
+
 @pytest.mark.parametrize("recorded_hash", ["b" * 40, "c" * 40])
 async def test_initial_preserves_legacy_choice(
     monkeypatch: pytest.MonkeyPatch, github_payload: github.TrustedPublisherPayload, recorded_hash: str
diff --git a/tests/unit/test_ssh_account_status.py b/tests/unit/test_ssh_account_status.py
index 80ddf043..1212ccfb 100644
--- a/tests/unit/test_ssh_account_status.py
+++ b/tests/unit/test_ssh_account_status.py
@@ -21,6 +21,9 @@ from typing import TYPE_CHECKING
 import asyncssh
 import pytest
 
+import atr.db.interaction as interaction
+import atr.models.github as github
+import atr.models.safe as safe
 import atr.ssh as ssh
 
 if TYPE_CHECKING:
@@ -94,6 +97,59 @@ async def test_step_02_rejects_disabled_account():
         await ssh._step_02_handle_safely(process, server)
 
 
+@pytest.mark.asyncio
+async def test_step_04_allows_workflow_key_for_its_own_project(monkeypatch: "MonkeyPatch"):
+    server = _make_workflow_server("test")
+    mock_data = mock.MagicMock()
+    mock_data.project.return_value.get = mock.AsyncMock(return_value=None)
+    mock_session = mock.AsyncMock()
+    mock_session.__aenter__.return_value = mock_data
+    monkeypatch.setattr("atr.db.session", lambda: mock_session)
+    process = _make_process(username="github")
+    # Reaching the project lookup means the workflow key's project binding was satisfied
+    with pytest.raises(ssh.RsyncArgsError, match="Project 'test' does not exist"):
+        await ssh._step_04_command_validate(process, [".", "/test/1.0/"], False, server)
+
+
+@pytest.mark.asyncio
+async def test_step_04_allows_read_only_workflow_key_to_download(monkeypatch: "MonkeyPatch"):
+    server = _make_workflow_server("test")
+    server._github_read_only = True
+    mock_data = mock.MagicMock()
+    mock_data.project.return_value.get = mock.AsyncMock(return_value=None)
+    mock_session = mock.AsyncMock()
+    mock_session.__aenter__.return_value = mock_data
+    monkeypatch.setattr("atr.db.session", lambda: mock_session)
+    process = _make_process(username="github")
+    # Reaching the project lookup means the read-only restriction was satisfied
+    with pytest.raises(ssh.RsyncArgsError, match="Project 'test' does not exist"):
+        await ssh._step_04_command_validate(process, [".", "/test/1.0/"], True, server)
+
+
+@pytest.mark.asyncio
+async def test_step_04_rejects_read_only_workflow_key_upload(monkeypatch: "MonkeyPatch"):
+    server = _make_workflow_server("test")
+    server._github_read_only = True
+    session = mock.MagicMock()
+    monkeypatch.setattr("atr.db.session", session)
+    process = _make_process(username="github")
+    with pytest.raises(ssh.RsyncArgsError, match="can only be used to download files"):
+        await ssh._step_04_command_validate(process, [".", "/test/1.0/"], False, server)
+    session.assert_not_called()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("is_read_request", [True, False])
+async def test_step_04_rejects_workflow_key_for_other_project(monkeypatch: "MonkeyPatch", is_read_request: bool):
+    server = _make_workflow_server("test")
+    session = mock.MagicMock()
+    monkeypatch.setattr("atr.db.session", session)
+    process = _make_process(username="github")
+    with pytest.raises(ssh.RsyncArgsError, match="can only be used for project 'test'"):
+        await ssh._step_04_command_validate(process, [".", "/other/1.0/"], is_read_request, server)
+    session.assert_not_called()
+
+
 @pytest.mark.asyncio
 @pytest.mark.usefixtures("_patch_ldap_active")
 async def test_validate_public_key_allows_active_workflow_user(monkeypatch: "MonkeyPatch"):
@@ -104,6 +160,9 @@ async def test_validate_public_key_allows_active_workflow_user(monkeypatch: "Mon
     mock_workflow_key.asf_uid = "alice"
     mock_workflow_key.revoked = False
     mock_workflow_key.expires = 9999999999
+    mock_workflow_key.github_nid = 1
+    mock_workflow_key.project_key = "test"
+    mock_workflow_key.source_commit = None
     mock_workflow_key.github_payload = {
         "actor": "alice",
         "actor_id": 1,
@@ -141,6 +200,8 @@ async def test_validate_public_key_allows_active_workflow_user(monkeypatch: "Mon
     monkeypatch.setattr("atr.db.session", lambda: mock_session)
     result = await server.validate_public_key("github", key)
     assert result is True
+    assert server._github_project_key == safe.ProjectKey("test")
+    assert server._github_read_only is False
 
 
 @pytest.mark.asyncio
@@ -153,6 +214,9 @@ async def test_validate_public_key_closes_db_session_before_ldap(monkeypatch: "M
     mock_workflow_key.asf_uid = "alice"
     mock_workflow_key.revoked = False
     mock_workflow_key.expires = 9999999999
+    mock_workflow_key.github_nid = 1
+    mock_workflow_key.project_key = "test"
+    mock_workflow_key.source_commit = None
     mock_workflow_key.github_payload = {
         "actor": "alice",
         "actor_id": 1,
@@ -204,6 +268,28 @@ async def test_validate_public_key_closes_db_session_before_ldap(monkeypatch: "M
     assert session_closed is True
 
 
+@pytest.mark.asyncio
+@pytest.mark.usefixtures("_patch_ldap_active")
+async def test_validate_public_key_marks_trusted_role_key_read_only(
+    monkeypatch: "MonkeyPatch", github_payload: github.TrustedPublisherPayload
+):
+    server = _make_server()
+    key = mock.MagicMock(spec=asyncssh.SSHKey)
+    key.get_fingerprint.return_value = "SHA256:abc"
+    mock_workflow_key = mock.MagicMock()
+    mock_workflow_key.asf_uid = "alice"
+    mock_workflow_key.revoked = False
+    mock_workflow_key.expires = 9999999999
+    mock_workflow_key.github_nid = interaction.GITHUB_TRUSTED_ROLE_NID
+    mock_workflow_key.project_key = "test"
+    mock_workflow_key.source_commit = None
+    mock_workflow_key.github_payload = github_payload.model_dump(exclude={"exp", "nbf"})
+    monkeypatch.setattr("atr.db.session", lambda: WorkflowKeySession(mock_workflow_key, lambda: None))
+    result = await server.validate_public_key("github", key)
+    assert result is True
+    assert server._github_read_only is True
+
+
 @pytest.mark.asyncio
 @pytest.mark.usefixtures("_patch_ldap_disabled")
 async def test_validate_public_key_rejects_disabled_workflow_user(monkeypatch: "MonkeyPatch"):
@@ -242,6 +328,16 @@ def _make_server() -> ssh.SSHServer:
     server = ssh.SSHServer.__new__(ssh.SSHServer)
     server._github_asf_uid = None
     server._github_payload = None
+    server._github_project_key = None
+    server._github_read_only = False
+    server._github_source_commit = None
+    return server
+
+
+def _make_workflow_server(project_key: str) -> ssh.SSHServer:
+    server = _make_server()
+    server._github_asf_uid = "alice"
+    server._github_project_key = safe.ProjectKey(project_key)
     return server
 
 
diff --git a/tests/unit/test_workflow_jti_replay.py b/tests/unit/test_workflow_jti_replay.py
index d2a33529..f83b88d8 100644
--- a/tests/unit/test_workflow_jti_replay.py
+++ b/tests/unit/test_workflow_jti_replay.py
@@ -30,6 +30,24 @@ import atr.storage.writers.ssh as ssh
 _DISTANT_EXPIRY = 2**31 - 1
 
 
+@pytest.mark.asyncio
+@pytest.mark.parametrize("source_commit", [None, safe.CommitHash("d" * 40)])
+async def test_declared_source_commit_is_stored_with_the_key(
+    monkeypatch: pytest.MonkeyPatch, source_commit: safe.CommitHash | None
+) -> None:
+    monkeypatch.setattr(ssh.util, "key_ssh_fingerprint", lambda _key: "SHA256:fingerprint")
+    data = _data()
+    writer = _writer(data)
+
+    await writer.add_workflow_key(
+        "test-user", 12345, safe.ProjectKey("alpha-one"), "ssh-ed25519 AAAA", _payload(), source_commit=source_commit
+    )
+
+    key = _added_of_type(data, sql.WorkflowSSHKey)[0]
+    assert key.source_commit == (str(source_commit) if (source_commit is not None) else None)
+    assert "source_commit" not in key.github_payload
+
+
 @pytest.mark.asyncio
 async def test_recorded_token_expiry_follows_the_token_rather_than_the_key(monkeypatch: pytest.MonkeyPatch) -> None:
     monkeypatch.setattr(ssh.util, "key_ssh_fingerprint", lambda _key: "SHA256:fingerprint")


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