From 2fecff45c070fcb0a20a47563e61b6e7cd9e449d Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Wed, 25 Nov 2026 14:42:39 +0800 Subject: [PATCH 1/3] Enable Java Pack bridge workflows Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 10 +- automation_bridge/bridge.py | 48 +++--- docs/guide.md | 62 ++++---- tests/test_automation_bridge.py | 264 ++++++++++++++++++++++++++++---- 4 files changed, 310 insertions(+), 74 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 514c85b..12da199 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -319,9 +319,13 @@ The agent is driven by a workflow in the target repo Function verifies GitHub identity without exchanging the token for Entra credentials. No App webhook or corporate FIC is used. The bridge's reviewed ingress Function App allowlist setting additionally - admits `microsoft/vscode-java-pack` for manual issue-loop dispatch from any - workflow on its protected default branch; it grants no automatic events or - team-memory. `automation_bridge/repository_allowlist.example.json` documents + admits `microsoft/vscode-java-pack` issue-loop events only from its exact + `.github/workflows/issueLens-run.yml` workflow and same-repository team-memory + only from `.github/workflows/team-memory-coordinator.yml` on protected `main`. + Java Pack source and validated wiki destination must both be that repository; + its wiki reservation is separate from IssueLens. The pinned action requires + explicit `source-repository: microsoft/vscode-java-pack` for manual requests. + `automation_bridge/repository_allowlist.example.json` documents the initial setting value; it is not loaded from the Function ZIP. 2. The worker uses its managed identity to POST the existing `{ input }` payload to the deployed agent's `/invocations` API. Bridge validation and diff --git a/automation_bridge/bridge.py b/automation_bridge/bridge.py index 3f1b4e8..153dbfb 100644 --- a/automation_bridge/bridge.py +++ b/automation_bridge/bridge.py @@ -27,6 +27,9 @@ PILOT_REPOSITORY = action.COORDINATOR_REPOSITORY PILOT_BRANCH = "main" +JAVA_REPOSITORY = "microsoft/vscode-java-pack" +JAVA_REPOSITORY_ID = 104967329 +JAVA_WORKFLOW = ".github/workflows/issueLens-run.yml" GITHUB_ISSUER = "https://token.actions.githubusercontent.com" KEYS = jwt.PyJWKClient(GITHUB_ISSUER + "/.well-known/jwks", timeout=5) JOB_ID = re.compile(r"[0-9a-f]{64}") @@ -49,7 +52,8 @@ def load_repository_allowlist(value: str, pilot_repository_id: int) -> frozenset require(isinstance(ids, list) and ids and all(type(identifier) is int and identifier > 0 for identifier in ids) and len(set(ids)) == len(ids) - and type(pilot_repository_id) is int and pilot_repository_id in ids, + and type(pilot_repository_id) is int and pilot_repository_id != JAVA_REPOSITORY_ID + and pilot_repository_id in ids and set(ids) <= {pilot_repository_id, JAVA_REPOSITORY_ID}, "Invalid bridge repository ID allowlist") return frozenset(ids) @@ -75,6 +79,8 @@ def workflow_claims(token: str, audience: str, pilot_repository_id: int, allowli or claims["repository"] == PILOT_REPOSITORY) and (claims["repository"] != PILOT_REPOSITORY or int(claims["repository_id"]) == pilot_repository_id) + and ((claims["repository"] == JAVA_REPOSITORY) + == (int(claims["repository_id"]) == JAVA_REPOSITORY_ID)) and claims["repository_visibility"] == "public" and isinstance(claims["ref"], str) and claims["ref"].startswith("refs/heads/") and claims.get("runner_environment") == "github-hosted", @@ -92,14 +98,14 @@ def workflow_claims(token: str, audience: str, pilot_repository_id: int, allowli else: raise ValueError("Workflow is not enabled for this bridge") else: - prefix = f"{claims['repository']}/.github/workflows/" - suffix = "@" + claims["ref"] - require(claims["event_name"] == "workflow_dispatch" - and isinstance(claims["workflow_ref"], str) - and claims["workflow_ref"].startswith(prefix) - and claims["workflow_ref"].endswith(suffix) - and re.fullmatch(r"[A-Za-z0-9_.-]+\.ya?ml", claims["workflow_ref"][len(prefix):-len(suffix)]), - "Only manual workflow dispatches from enrolled repositories are allowed") + require(claims["repository"] == JAVA_REPOSITORY and claims["ref"] == "refs/heads/main", + "Workflow is not enabled for this bridge") + if claims["workflow_ref"] == workflow_ref(action.COORDINATOR_WORKFLOW, JAVA_REPOSITORY): + require(claims["event_name"] == "workflow_dispatch", "Unsupported workflow event") + return _validated_claims(claims, "team-memory", int(claims["repository_id"])) + require(claims["workflow_ref"] == workflow_ref(JAVA_WORKFLOW, JAVA_REPOSITORY) + and claims["event_name"] in {"issues", "issue_comment", "workflow_dispatch"}, + "Workflow is not enabled for this bridge") return _validated_claims(claims, "issue-loop", int(claims["repository_id"])) @@ -124,6 +130,7 @@ def default_branch_protected(claims: dict) -> bool: and isinstance(branch_name, str) and branch_name, "Invalid GitHub repository response") if (project["full_name"].casefold() != repository.casefold() + or (repository == JAVA_REPOSITORY and project["full_name"] != JAVA_REPOSITORY) or project["id"] != claims["repository_id"] or project["private"] or project["visibility"] != "public" or claims["ref"] != f"refs/heads/{branch_name}"): return False @@ -197,21 +204,22 @@ def _issue_job(metadata: dict, claims: dict) -> str: _MERGE_FIELDS = {"pull_number", "merge_commit_sha", "merged_at", "source_identity"} -def _validate_merge(merge: dict): +def _validate_merge(merge: dict, repository: str): number = _positive_int(merge.get("pull_number")) sha = action.full_sha(merge.get("merge_commit_sha")) merged_at = merge.get("merged_at") - require(merge.get("source_identity") == f"{PILOT_REPOSITORY}#{number}:{sha}" + require(merge.get("source_identity") == f"{repository}#{number}:{sha}" and isinstance(merged_at, str) and re.fullmatch(r"[0-9T:Z.+-]{1,64}", merged_at), "Invalid merged PR identity") return number def _memory_job(metadata: dict, claims: dict) -> str: + repository = claims["repository"] require(metadata.get("repository_id") == claims["repository_id"] and metadata.get("base_ref") == PILOT_BRANCH - and metadata.get("coordinator_repository") == PILOT_REPOSITORY - and metadata.get("required_wiki_repository") == PILOT_REPOSITORY + and metadata.get("coordinator_repository") == repository + and metadata.get("required_wiki_repository") == repository and metadata.get("coordinator_workflow_ref") == claims["workflow_ref"] and metadata.get("coordinator_workflow_sha") == claims["workflow_sha"] and metadata.get("coordinator_run_id") == claims["run_id"] @@ -233,9 +241,9 @@ def _memory_job(metadata: dict, claims: dict) -> str: before, after = (action.full_sha(metadata[field]) for field in ("push_before", "push_after")) action.full_sha(metadata["source_tip_sha"]) require(before != after and metadata["range_origin"] == "authorized-reconciliation" - and metadata["source_identity"] == f"{PILOT_REPOSITORY}@{before}..{after}" + and metadata["source_identity"] == f"{repository}@{before}..{after}" and metadata["event_action"] == "push" and metadata["workflow_sha"] == after - and metadata["workflow_ref"] == workflow_ref(action.DISPATCH_WORKFLOW) + and metadata["workflow_ref"] == workflow_ref(action.DISPATCH_WORKFLOW, repository) and _positive_int(metadata["commit_count"]) <= action.MAX_PUSH_COMMITS, "Invalid reconciliation range metadata") _positive_int(metadata["run_id"]) @@ -244,7 +252,7 @@ def _memory_job(metadata: dict, claims: dict) -> str: require(isinstance(pulls, list) and 0 < len(pulls) <= action.MAX_BATCH_PRS and all(isinstance(pull, dict) and set(pull) == _MERGE_FIELDS for pull in pulls), "Invalid reconciliation PR inventory") - require(len({_validate_merge(pull) for pull in pulls}) == len(pulls), "Duplicate merged PRs") + require(len({_validate_merge(pull, repository) for pull in pulls}) == len(pulls), "Duplicate merged PRs") else: require(set(metadata) == fields | _MERGE_FIELDS and metadata.get("event_name") == "workflow_dispatch" and metadata.get("event_action") == "workflow_dispatch" @@ -252,7 +260,7 @@ def _memory_job(metadata: dict, claims: dict) -> str: and all(metadata.get(field) == claims[field] for field in ( "workflow_ref", "workflow_sha", "run_id", "run_attempt", )), "Invalid manual team-memory metadata") - _validate_merge(metadata) + _validate_merge(metadata, repository) return "wiki" @@ -334,16 +342,18 @@ def receipt(job) -> dict: def _verify_created_comment(metadata: dict, digest: str) -> None: + repository = metadata["repository"] + require(repository in {PILOT_REPOSITORY, JAVA_REPOSITORY}, "Invalid comment repository") identifier = _positive_int(metadata["comment_id"]) number = _positive_int(metadata["issue_number"]) - comment = action.github_read(f"/repos/{PILOT_REPOSITORY}/issues/comments/{identifier}", token="") + comment = action.github_read(f"/repos/{repository}/issues/comments/{identifier}", token="") issue_url = comment.get("issue_url") created = comment.get("created_at") body = comment.get("body") require( comment.get("id") == identifier and isinstance(issue_url, str) - and issue_url.casefold() == f"https://api.github.com/repos/{PILOT_REPOSITORY}/issues/{number}".casefold() + and issue_url.casefold() == f"https://api.github.com/repos/{repository}/issues/{number}".casefold() and isinstance(created, str) and created and created == comment.get("updated_at") and isinstance(body, str) and hashlib.sha256(body.encode("utf-8")).hexdigest() == digest, "GitHub comment no longer matches its created revision", diff --git a/docs/guide.md b/docs/guide.md index 9b57c2d..9dd1f44 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1054,9 +1054,8 @@ routing and command validation; no new permanent agent contract is introduced. ### IssueLens Function bridge pilot Configure the ingress Function's reviewed repository allowlist to admit -`microsoft/IssueLens` and, for the first Java Pack pilot, only manual issue-loop -dispatches from `microsoft/vscode-java-pack`. No other Java Pack events or -team-memory jobs should be admitted. Keep the GitHub App webhook unchanged. Obtain +`microsoft/IssueLens` and `microsoft/vscode-java-pack` issue-loop and +same-repository team-memory jobs. Keep the GitHub App webhook unchanged. Obtain approval for the GitHub-facing endpoint, direct trust of the GitHub Actions issuer, network access, and the Azure release path before provisioning or enabling anything. The Function validates a GitHub token addressed to itself; @@ -1076,7 +1075,7 @@ from the application job table. | Target | Configuration and access | | --- | --- | | Both Function apps | `ISSUELENS_BRIDGE_TABLE_ACCOUNT` points to the account containing precreated `IssueLensBridgeJobs`. Both need Table data read/write on that table. `ISSUELENS_BRIDGE_QUEUE` and `ISSUELENS_BRIDGE_SERVICE_BUS__fullyQualifiedNamespace` identify the same dedicated Service Bus queue. Use a queue with duplicate detection; reservations remain authoritative even outside the broker window. | -| Ingress | `ISSUELENS_BRIDGE_ROLE=ingress`, `ISSUELENS_BRIDGE_REPOSITORY_ID` set to the existing IssueLens numeric GitHub repository ID (`1303440932`), `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST` set to the reviewed JSON ID array, and `ISSUELENS_BRIDGE_OIDC_AUDIENCE` set to the exact HTTPS `/api/issuelens/v1/jobs` URL on the approved `azurewebsites.net` endpoint. The IssueLens ID must be in the allowlist or ingress fails closed. Other enrolled IDs come only from the trusted setting, not a workflow input or a replacement for the existing ID setting. The receiver verifies signature, audience, issuer, public repository identity, GitHub-hosted runner, current default branch and protection; non-IssueLens repositories can submit manual issue-loop jobs from any workflow on that branch. IssueLens retains its exact workflow/event restrictions. Grant queue **Data Sender** only. Enforce HTTPS and set `FUNCTIONS_REQUEST_BODY_SIZE_LIMIT=32768` to cap requests before they reach Python. | +| Ingress | `ISSUELENS_BRIDGE_ROLE=ingress`, `ISSUELENS_BRIDGE_REPOSITORY_ID` set to the existing IssueLens numeric GitHub repository ID (`1303440932`), `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST` set to the reviewed JSON ID array, and `ISSUELENS_BRIDGE_OIDC_AUDIENCE` set to the exact HTTPS `/api/issuelens/v1/jobs` URL on the approved `azurewebsites.net` endpoint. The IssueLens ID must be in the allowlist or ingress fails closed. Only IssueLens and Java Pack IDs are supported. The receiver verifies signature, audience, issuer, public repository identity, GitHub-hosted runner, current default branch and protection; Java Pack is restricted to its exact reviewed workflows on `main`. IssueLens retains its exact workflow/event restrictions. Grant queue **Data Sender** only. Enforce HTTPS and set `FUNCTIONS_REQUEST_BODY_SIZE_LIMIT=32768` to cap requests before they reach Python. | | Worker | `ISSUELENS_BRIDGE_ROLE=worker`, `ISSUELENS_BRIDGE_FOUNDRY_URL` set to the existing deployed agent's full invocations URL (including API version). Grant queue **Data Receiver** and the narrowest applicable Foundry invocation access to the worker managed identity. It requests an Entra token for `https://ai.azure.com/.default`. No repository write, deployment, signing key, or GitHub App key access is needed. | Keep `main` protected. If the signed token supplies `ref_protected`, the @@ -1091,43 +1090,54 @@ Use `automation_bridge/repository_allowlist.example.json` as the initial repository IDs. The existing `ISSUELENS_BRIDGE_REPOSITORY_ID` setting must remain in that array and continues to identify IssueLens. The setting is limited to 32 KiB; missing IssueLens enrollment, malformed JSON, duplicate or -invalid IDs, and missing settings fail closed. - -For enrolled non-IssueLens repositories, the bridge accepts only manual -`workflow_dispatch` issue-loop jobs from GitHub-hosted runners on the current -protected default branch. The bridge checks repository ID, public visibility, -canonical name, current default branch, and branch protection using GitHub -metadata; it accepts no dispatch-supplied repository list or job type. The -existing IssueLens issue workflow keeps its event behavior, and team-memory -remains limited to the exact IssueLens coordinator workflow. +invalid IDs, unreviewed IDs, and missing settings fail closed. + +For enrolled Java Pack, the bridge accepts `issues`, `issue_comment`, and +`workflow_dispatch` issue-loop events only from `.github/workflows/issueLens-run.yml` +on protected `main`. The same issue action and human-comment restrictions apply +as for IssueLens. The bridge checks repository ID, public visibility, canonical +name, current default branch, and branch protection using GitHub metadata; it +accepts no dispatch-supplied repository list or arbitrary job type. The +existing IssueLens issue workflow keeps its event behavior. + +Java Pack team-memory requires a GitHub-hosted `workflow_dispatch` from +`.github/workflows/team-memory-coordinator.yml` on protected `main`. The +coordinator, source, and validated wiki destination must all be +`microsoft/vscode-java-pack`; cross-repository sources are not admitted. +Manual PR and coordinated push-range requests share the Java Pack wiki +reservation, separate from IssueLens. The pinned action +`b88dadd40754d640cbb82f4d9a5e9d36e8386981` requires an explicit +`source-repository: microsoft/vscode-java-pack` even for manual PR requests +to generate the coordinated envelope. Source run metadata cannot prove the +original push boundary or flags. A consumer must independently configure its +own coordinator queue, source read credentials, validated wiki policy, and +App access; bridge admission does not grant these permissions or guarantee +publication. Restrict permission to modify Function App settings to authorized operators: the allowlist controls admission and must never come from workflow or dispatch inputs. Review each repository's public identity, default branch protection, -workflow code, and App permissions before adding its ID. Azure applies app -setting changes by restarting the Function App; onboarding an ID needs no ZIP -redeployment. Removing an entry also prevents its existing runs from polling +workflow code, and App permissions before adding its ID. Only the two reviewed +IDs are supported; onboarding another repository requires a code change. Azure +applies app setting changes by restarting the Function App. Removing an entry +also prevents its existing runs from polling their receipts, so reconcile in-flight jobs before removal. Configuration and release approval remain separate from this code change. Java Pack enrollment requires a separately approved bridge release and caller workflow change. The allowlist admits public `microsoft/vscode-java-pack` -(repository ID `104967329`) for manual issue-loop dispatch from any GitHub-hosted -workflow on its protected current default branch. Its existing workflow is -disabled and currently uses the legacy direct transport. Update and enable that -workflow only after approval, restrict the pilot to manual dispatch on the -protected default branch, provide +(repository ID `104967329`) only from its exact reviewed workflows on protected +`main`. Update and enable those workflows only after approval, provide the approved `ISSUELENS_BRIDGE_URL` Actions secret, and use the composite action with `request-type: issue-loop`, `transport: bridge`, `issue-number`, and -`bridge-url`. The job needs `contents: read`, `issues: read`, and +`bridge-url`. The issue-loop job needs `issues: read` and `id-token: write`; manual dispatch preflight verifies the issue exists and is not a pull request. Confirm the GitHub App has installation access and the necessary issue permissions for any authorized writes. Use privacy-appropriate output settings and a controlled issue; this is a write-capable invocation. -The existing Java Pack pin `c431d42dddf4e6bf20329b0ac96dbd8a4bf04006` -does not support bridge inputs; the already merged IssueLens action revision -`b88dadd40754d640cbb82f4d9a5e9d36e8386981` does. Review and pin an approved -full revision before enabling. The bridge trusts the signed workflow identity +The merged IssueLens action revision +`b88dadd40754d640cbb82f4d9a5e9d36e8386981` supports these bridge inputs. +Review and pin an approved full revision before enabling. The bridge trusts the signed workflow identity and its protected-branch code, not a separately attested payload or a pinned workflow SHA. Changes to this allowlist require authorized configuration review; workflow inputs cannot enroll repositories. diff --git a/tests/test_automation_bridge.py b/tests/test_automation_bridge.py index f89ab50..39fd827 100644 --- a/tests/test_automation_bridge.py +++ b/tests/test_automation_bridge.py @@ -1,3 +1,4 @@ +import copy import hashlib import importlib.util import json @@ -128,19 +129,20 @@ def test_pilot_case_only_repository_rename_is_rejected(self): with self.assertRaisesRegex(ValueError, "Workflow is not in the IssueLens pilot scope"): self.workflow_claims(renamed, URL, PILOT_REPOSITORY_ID) - def test_java_pack_manual_dispatch_is_allowed_from_an_enrolled_workflow(self): + def test_java_pack_admission_is_limited_to_its_reviewed_workflow(self): accepted = self.workflow_claims(self.java_token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) self.assertEqual(bridge.validate_request(self.java_payload(), accepted), "repo-104967329-issue-12") - additional_workflow = self.workflow_claims(self.java_token( - workflow_ref=bridge.workflow_ref(".github/workflows/another-triage.yaml", JAVA_REPOSITORY), - ref_protected="true", - ), URL, PILOT_REPOSITORY_ID) - self.assertEqual(additional_workflow["kind"], "issue-loop") + for event in ("issues", "issue_comment", "workflow_dispatch"): + self.assertEqual(self.workflow_claims( + self.java_token(event_name=event, ref_protected="true"), URL, PILOT_REPOSITORY_ID, + )["kind"], "issue-loop") for overrides in ( {"repository": PILOT_REPOSITORY}, {"repository_id": "104967330"}, {"repository_id": "not-an-id"}, {"repository_visibility": "private"}, {"ref": "refs/tags/v1"}, {"ref_protected": "false"}, - {"runner_environment": "self-hosted"}, {"event_name": "issues"}, - {"event_name": "issue_comment"}, {"workflow_ref": bridge.workflow_ref(ISSUE_WORKFLOW)}, + {"runner_environment": "self-hosted"}, {"event_name": "push"}, + {"repository": "microsoft/VSCode-java-pack"}, + {"ref": "refs/heads/other"}, {"workflow_ref": bridge.workflow_ref(ISSUE_WORKFLOW)}, + {"workflow_ref": bridge.workflow_ref(".github/workflows/another-triage.yaml", JAVA_REPOSITORY)}, {"aud": ENDPOINT}, ): with self.subTest(overrides=overrides), self.assertRaises((ValueError, jwt.PyJWTError)): @@ -170,25 +172,33 @@ def test_ingress_rejects_requests_if_configured_issuelens_id_disagrees_with_mani self.assertEqual(status(self.request(JOB)).status_code, 401) jobs.assert_not_called() - def test_ingress_admits_a_new_configured_repository_without_changing_the_bundle(self): - repository, repository_id = "example/project", 12345678 - workflow = ".github/workflows/triage.yml" + def test_ingress_rejects_an_unreviewed_repository_in_the_allowlist(self): ids = json.loads(ALLOWLIST_JSON) - ids.append(repository_id) - ingress, submit, _ = self.load_ingress(json.dumps(ids)) - token = self.token( - repository=repository, repository_id=str(repository_id), event_name="workflow_dispatch", - workflow_ref=bridge.workflow_ref(workflow, repository), ref_protected="true", - ) - payload = self.java_payload(repository=repository) - with patch.object(bridge.action, "github_read", return_value={ - "id": repository_id, "full_name": repository, "private": False, - "visibility": "public", "default_branch": "main", - }), patch.object(ingress, "jobs") as jobs, patch.object(ingress, "service_bus"): - jobs.return_value.reserve.return_value = {"RowKey": JOB, "state": bridge.QUEUED} - response = submit(self.request(token=token, payload=payload)) - self.assertEqual(response.status_code, 202, response.get_body()) - self.assertEqual(jobs.return_value.reserve.call_args.args[1], "repo-12345678-issue-12") + ids.append(12345678) + with self.assertRaises(ValueError): + self.load_ingress(json.dumps(ids)) + allowlist = bridge.load_repository_allowlist(json.dumps([PILOT_REPOSITORY_ID]), PILOT_REPOSITORY_ID) + with self.assertRaises(ValueError): + bridge.workflow_claims(self.java_token(), URL, PILOT_REPOSITORY_ID, allowlist) + + def test_java_pack_event_actions_follow_existing_issue_rules(self): + for event, operation in (("issues", "opened"), ("issues", "reopened"), + ("issue_comment", "created"), ("issue_comment", "edited")): + claims = self.workflow_claims(self.java_token(event_name=event), URL, PILOT_REPOSITORY_ID) + metadata = issue_metadata(repository=JAVA_REPOSITORY, event_name=event, event_action=operation, + comment_added=operation == "created", comment_edited=operation == "edited") + if event == "issues": + metadata.update(comment_id=None, comment_author_login=None, comment_author_association=None) + if operation != "created": + metadata.pop("comment_sha256") + with self.subTest(event=event, operation=operation): + self.assertEqual(bridge.validate_request({"request_type": "issue-loop", "metadata": metadata}, claims), + "repo-104967329-issue-12") + with self.assertRaises(ValueError): + bridge.validate_request({"request_type": "issue-loop", "metadata": metadata | {"event_action": "deleted"}}, claims) + if event == "issue_comment": + with self.assertRaises(ValueError): + bridge.validate_request({"request_type": "issue-loop", "metadata": metadata | {"actor_type": "Bot"}}, claims) def test_existing_team_memory_workflow_remains_enabled(self): claims = self.workflow_claims(self.token( @@ -208,6 +218,146 @@ def test_existing_team_memory_workflow_remains_enabled(self): } self.assertEqual(bridge.validate_request({"request_type": "team-memory", "metadata": metadata}, claims), "wiki") + def test_packaged_java_coordinator_manual_and_push_contract(self): + project = {"full_name": JAVA_REPOSITORY, "id": JAVA_REPOSITORY_ID, + "default_branch": "main", "visibility": "public"} + coordinator_ref = bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY) + before, after = "d" * 40, "e" * 40 + merged_at = "2026-11-24T00:00:00Z" + pull = {"number": 12, "merged": True, "state": "closed", "merged_at": merged_at, + "merge_commit_sha": after, "base": {"ref": "main", "repo": project}} + source_run = {"id": 31, "run_attempt": 2, "event": "push", + "path": bridge.action.DISPATCH_WORKFLOW, "head_branch": "main", "head_sha": after, + "repository": project, "head_repository": project, + "actor": {"login": "maintainer"}, "triggering_actor": {"login": "maintainer"}} + comparison = {"base_commit": {"sha": before}, "merge_base_commit": {"sha": before}, + "status": "ahead", "ahead_by": 1, "behind_by": 0, "total_commits": 1, + "commits": [{"sha": after}]} + node = {"number": 12, "state": "MERGED", "merged": True, "mergedAt": merged_at, + "baseRefName": "main", "baseRepository": {"databaseId": JAVA_REPOSITORY_ID, + "nameWithOwner": JAVA_REPOSITORY}, + "mergeCommit": {"oid": after}} + associations = {"data": {"repository": { + "databaseId": JAVA_REPOSITORY_ID, "nameWithOwner": JAVA_REPOSITORY, + "defaultBranchRef": {"name": "main", "target": {"oid": after}}, + "c0": {"oid": after, "associatedPullRequests": { + "totalCount": 1, "pageInfo": {"hasNextPage": False}, "nodes": [node], + }}, + }}} + environment = { + "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": BRANCH, + "GITHUB_WORKFLOW_REF": coordinator_ref, "GITHUB_WORKFLOW_SHA": "1" * 40, + "GITHUB_ACTOR": "maintainer", "GITHUB_TRIGGERING_ACTOR": "maintainer", + "GITHUB_RUN_ID": "20", "GITHUB_RUN_ATTEMPT": "1", "SOURCE_REPOSITORY": JAVA_REPOSITORY, + "SOURCE_REPOSITORIES": json.dumps({JAVA_REPOSITORY: JAVA_REPOSITORY_ID}), + "SOURCE_GH_TOKEN": "fixture-token", + } + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + archive = root / "bridge.zip" + bundle.build(archive) + with ZipFile(archive) as source: + source.extractall(root) + spec = importlib.util.spec_from_file_location("packaged_memory_bridge", root / "bridge.py") + packaged = importlib.util.module_from_spec(spec) + spec.loader.exec_module(packaged) + allowlist = packaged.load_repository_allowlist(ALLOWLIST_JSON, PILOT_REPOSITORY_ID) + with patch.object(packaged.KEYS, "get_signing_key_from_jwt", return_value=Mock(key=self.key.public_key())): + claims = packaged.workflow_claims( + self.java_token(workflow_ref=coordinator_ref, ref_protected="true"), + URL, PILOT_REPOSITORY_ID, allowlist, + ) + self.assertEqual(claims["kind"], "team-memory") + for overrides in ( + {"event_name": "push"}, {"workflow_ref": bridge.workflow_ref(MEMORY_WORKFLOW)}, + {"ref": "refs/heads/other"}, {"runner_environment": "self-hosted"}, + {"repository_id": str(PILOT_REPOSITORY_ID)}, + ): + with self.subTest(claims=overrides), self.assertRaises((ValueError, jwt.PyJWTError)): + packaged.workflow_claims(self.java_token(**({"workflow_ref": coordinator_ref} | overrides)), + URL, PILOT_REPOSITORY_ID, allowlist) + worker = packaged.FoundryWorker(ENDPOINT, Mock(get_token=Mock(return_value=Mock(token="token")))) + for wrong_run in ( + source_run | {"repository": project | {"id": PILOT_REPOSITORY_ID}}, + source_run | {"head_repository": project | {"id": PILOT_REPOSITORY_ID}}, + source_run | {"id": 32}, + ): + variables = {"SOURCE_RUN_ID": "31", "SOURCE_RUN_ATTEMPT": "2", + "PUSH_BEFORE": before, "PUSH_AFTER": after} + with patch.dict(os.environ, environment | variables, clear=True), \ + patch.object(packaged.action, "github_read", side_effect=[project, wrong_run]), \ + self.assertRaises(ValueError): + packaged.action.prepare_team_memory(JAVA_REPOSITORY, {"repository": project}) + for mode in ("manual", "push"): + variables = ({"DISPATCH_PR": "12"} if mode == "manual" else { + "SOURCE_RUN_ID": "31", "SOURCE_RUN_ATTEMPT": "2", + "PUSH_BEFORE": before, "PUSH_AFTER": after, + }) + reads = ([project, pull] if mode == "manual" else [ + project, source_run, {"name": "main", "commit": {"sha": after}}, comparison, associations, + ]) + with self.subTest(mode=mode), patch.dict(os.environ, environment | variables, clear=True), \ + patch.object(packaged.action, "github_read", side_effect=reads): + envelope = packaged.action.prepare_team_memory(JAVA_REPOSITORY, {"repository": project}) + metadata = envelope["metadata"] + payload = {"request_type": "team-memory", "metadata": metadata} + self.assertEqual(packaged.validate_request(payload, claims), "repo-104967329-wiki") + self.assertEqual(json.loads(worker.prepare({"payload": json.dumps(payload)}).data), envelope["request"]) + for key, wrong in ( + ("repository", PILOT_REPOSITORY), ("repository_id", PILOT_REPOSITORY_ID), + ("coordinator_repository", PILOT_REPOSITORY), ("required_wiki_repository", PILOT_REPOSITORY), + ("coordinator_run_id", 21), ("coordinator_run_attempt", 2), + ("coordinator_workflow_sha", "2" * 40), ("source_identity", "wrong"), + ("workflow_ref", bridge.workflow_ref(MEMORY_WORKFLOW)), + ): + invalid = copy.deepcopy(payload) + invalid["metadata"][key] = wrong + with self.subTest(mode=mode, key=key), self.assertRaises(ValueError): + packaged.validate_request(invalid, claims) + if mode == "push": + invalid = copy.deepcopy(payload) + invalid["metadata"]["pull_requests"][0]["source_identity"] = f"{PILOT_REPOSITORY}#12:{after}" + with self.assertRaises(ValueError): + packaged.validate_request(invalid, claims) + result = {"source_repository": JAVA_REPOSITORY, "status": "updated", "reason": "Verified", + "wiki_repository": JAVA_REPOSITORY, "wiki_sha": "f" * 40} + if mode == "manual": + result.update(pull_number=12, merge_commit_sha=after) + else: + result.update(push_before=before, push_after=after, results=[{ + "pull_number": 12, "merge_commit_sha": after, "status": "updated", "reason": "Verified", + }]) + self.assertEqual(json.loads(packaged._memory_receipt(json.dumps(result), metadata))["status"], "updated") + for field in ("source_repository", "wiki_repository"): + with self.subTest(mode=mode, result=field), self.assertRaises(ValueError): + packaged._memory_receipt(json.dumps(result | {field: PILOT_REPOSITORY}), metadata) + legacy_environment = environment | {"DISPATCH_PR": "12"} + del legacy_environment["SOURCE_REPOSITORY"] + with patch.dict(os.environ, legacy_environment, clear=True), \ + patch.object(packaged.action, "github_read", side_effect=[project, pull]): + legacy = packaged.action.prepare_team_memory(JAVA_REPOSITORY, {"repository": project}) + with self.assertRaises(ValueError): + packaged.validate_request({"request_type": "team-memory", "metadata": legacy["metadata"]}, claims) + + def test_java_memory_receipt_is_owned_by_the_coordinator_run(self): + ingress, _, status = self.load_ingress() + token = self.java_token(workflow_ref=bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY)) + claims = self.workflow_claims(token, URL, PILOT_REPOSITORY_ID) + pilot = self.workflow_claims(self.token( + workflow_ref=bridge.workflow_ref(MEMORY_WORKFLOW), event_name="workflow_dispatch", + ), URL, PILOT_REPOSITORY_ID) + identifier = bridge.job_id(claims) + self.assertNotEqual(identifier, bridge.job_id(pilot)) + self.assertEqual(identifier, bridge.job_id(claims | {"run_attempt": 2})) + with patch.object(ingress, "jobs") as jobs: + jobs.return_value.get.return_value = {"RowKey": identifier, "state": bridge.COMPLETED} + self.assertEqual(status(self.request(identifier, token=token)).status_code, 200) + self.assertEqual(status(self.request(identifier)).status_code, 404) + different_run = self.java_token( + workflow_ref=bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY), run_id="21", + ) + self.assertEqual(status(self.request(identifier, token=different_run)).status_code, 404) + def test_java_pack_fallback_and_same_run_receipt_are_repository_bound(self): ingress, submit, status = self.load_ingress() token = self.java_token() @@ -241,6 +391,13 @@ def test_java_pack_fallback_and_same_run_receipt_are_repository_bound(self): ): self.assertEqual(submit(self.request(token=token, payload=self.java_payload())).status_code, 401) jobs.assert_not_called() + with ( + patch.object(bridge.action, "github_read", + return_value=repository_info | {"full_name": "microsoft/VSCode-java-pack"}), + patch.object(ingress, "jobs") as jobs, + ): + self.assertEqual(submit(self.request(token=token, payload=self.java_payload())).status_code, 401) + jobs.assert_not_called() def test_java_pack_action_preflight_produces_an_admissible_manual_job(self): project = {"full_name": JAVA_REPOSITORY, "id": JAVA_REPOSITORY_ID, "default_branch": "main"} @@ -263,6 +420,60 @@ def test_java_pack_action_preflight_produces_an_admissible_manual_job(self): ) self.assertEqual(json.loads(request.data), envelope["request"]) + def test_packaged_action_and_bridge_handle_java_issue_and_comment_events(self): + project = {"full_name": JAVA_REPOSITORY, "id": JAVA_REPOSITORY_ID, "default_branch": "main"} + env = { + "GITHUB_REF": BRANCH, "GITHUB_WORKFLOW_REF": bridge.workflow_ref(JAVA_WORKFLOW, JAVA_REPOSITORY), + "GITHUB_WORKFLOW_SHA": "1" * 40, "GITHUB_ACTOR": "maintainer", "TRANSPORT": "bridge", + } + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + archive = root / "bridge.zip" + bundle.build(archive) + with ZipFile(archive) as source: + source.extractall(root) + spec = importlib.util.spec_from_file_location("packaged_bridge", root / "bridge.py") + packaged = importlib.util.module_from_spec(spec) + spec.loader.exec_module(packaged) + allowlist = packaged.load_repository_allowlist(ALLOWLIST_JSON, PILOT_REPOSITORY_ID) + worker = packaged.FoundryWorker(ENDPOINT, Mock(get_token=Mock(return_value=Mock(token="token")))) + for event_name, event in ( + ("issues", {"action": "opened", "issue": {"number": 12}, + "sender": {"login": "maintainer", "type": "User"}}), + ("issue_comment", {"action": "created", "issue": {"number": 12}, + "comment": {"id": 41, "body": "test comment", + "user": {"login": "maintainer", "type": "User"}, + "author_association": "MEMBER"}, + "sender": {"login": "maintainer", "type": "User"}}), + ): + event["repository"] = project + with self.subTest(event=event_name), \ + patch.dict(os.environ, env | {"GITHUB_EVENT_NAME": event_name}, clear=True), \ + patch.object(packaged.KEYS, "get_signing_key_from_jwt", return_value=Mock(key=self.key.public_key())), \ + patch.object(packaged.action, "github_read", return_value=project): + envelope = packaged.action.prepare_issue_loop(JAVA_REPOSITORY, event) + claims = packaged.workflow_claims( + self.java_token(event_name=event_name, ref_protected="true"), + URL, PILOT_REPOSITORY_ID, allowlist, + ) + payload = {"request_type": "issue-loop", "metadata": envelope["metadata"]} + self.assertEqual(packaged.validate_request(payload, claims), "repo-104967329-issue-12") + wrong = {"request_type": "issue-loop", "metadata": payload["metadata"] | {"repository": PILOT_REPOSITORY}} + with self.assertRaises(ValueError): + packaged.validate_request(wrong, claims) + comment = current_comment() | {"issue_url": f"https://api.github.com/repos/{JAVA_REPOSITORY}/issues/12"} + with patch.object(packaged.action, "github_read", return_value=comment) as read: + request = worker.prepare({"payload": json.dumps(payload)}) + self.assertEqual(json.loads(request.data), envelope["request"]) + if event_name == "issue_comment": + read.assert_called_once_with(f"/repos/{JAVA_REPOSITORY}/issues/comments/41", token="") + else: + read.assert_not_called() + if event_name == "issue_comment": + with patch.object(packaged.action, "github_read", return_value=current_comment()): + with self.assertRaises(ValueError): + worker.prepare({"payload": json.dumps(payload)}) + def test_only_the_expected_workflow_identity_is_accepted(self): accepted = self.workflow_claims(self.token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) self.assertEqual(bridge.validate_request(issue_payload(), accepted), "issue-12") @@ -367,6 +578,7 @@ def test_invalid_id_allowlist_is_rejected_as_a_whole(self): "oversize": " " * (32 * 1024 + 1), "object instead of list": json.dumps({"repositories": ids}), "missing IssueLens ID": json.dumps([JAVA_REPOSITORY_ID]), + "unreviewed ID": json.dumps(ids + [12345678]), } for label, content in invalid.items(): with self.subTest(label=label), self.assertRaises(ValueError): From dea5ad29bd1dbccdb3089734483a617d883f1c53 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Wed, 25 Nov 2026 15:08:34 +0800 Subject: [PATCH 2/3] Configure bridge workflow admission per repository Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 17 +- automation_bridge/bridge.py | 157 +++++++++++++------ automation_bridge/function_app.py | 8 +- docs/guide.md | 132 +++++++++------- tests/test_automation_bridge.py | 250 +++++++++++++++++++++++------- 5 files changed, 400 insertions(+), 164 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 12da199..5810139 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -318,15 +318,14 @@ The agent is driven by a workflow in the target repo Azure Function bridge with a bridge-audience GitHub Actions token. The Function verifies GitHub identity without exchanging the token for Entra credentials. No App webhook or corporate FIC is used. - The bridge's reviewed ingress Function App allowlist setting additionally - admits `microsoft/vscode-java-pack` issue-loop events only from its exact - `.github/workflows/issueLens-run.yml` workflow and same-repository team-memory - only from `.github/workflows/team-memory-coordinator.yml` on protected `main`. - Java Pack source and validated wiki destination must both be that repository; - its wiki reservation is separate from IssueLens. The pinned action requires - explicit `source-repository: microsoft/vscode-java-pack` for manual requests. - `automation_bridge/repository_allowlist.example.json` documents - the initial setting value; it is not loaded from the Function ZIP. + The ingress allowlist enrolls numeric repository IDs. Non-IssueLens IDs + are manual issue-loop only unless `ISSUELENS_BRIDGE_REPOSITORY_POLICIES` + configures exact repository, workflow and events for protected `main`. + Same-repository team-memory is a separate opt-in from the fixed coordinator; + source, coordinator and validated wiki destination must match. The worker + revalidates created comments using the repository stored at admission. + The settings and Java Pack example are documented in `docs/guide.md`; + the ZIP does not load an example file or enroll Java Pack in code. 2. The worker uses its managed identity to POST the existing `{ input }` payload to the deployed agent's `/invocations` API. Bridge validation and queueing stay outside the hosted agent. The agent remains independently diff --git a/automation_bridge/bridge.py b/automation_bridge/bridge.py index 153dbfb..02e7356 100644 --- a/automation_bridge/bridge.py +++ b/automation_bridge/bridge.py @@ -9,6 +9,7 @@ import urllib.error import urllib.parse import urllib.request +from dataclasses import dataclass from pathlib import Path import jwt @@ -27,9 +28,13 @@ PILOT_REPOSITORY = action.COORDINATOR_REPOSITORY PILOT_BRANCH = "main" -JAVA_REPOSITORY = "microsoft/vscode-java-pack" -JAVA_REPOSITORY_ID = 104967329 -JAVA_WORKFLOW = ".github/workflows/issueLens-run.yml" +WORKFLOW_DIRECTORY = ".github/workflows/" +WORKFLOW_BASENAME = re.compile(r"[A-Za-z0-9_.-]+\.ya?ml") +ISSUE_EVENT_ACTIONS = { + "issues": ("opened", "reopened"), + "issue_comment": ("created", "edited"), + "workflow_dispatch": ("workflow_dispatch",), +} GITHUB_ISSUER = "https://token.actions.githubusercontent.com" KEYS = jwt.PyJWKClient(GITHUB_ISSUER + "/.well-known/jwks", timeout=5) JOB_ID = re.compile(r"[0-9a-f]{64}") @@ -52,13 +57,62 @@ def load_repository_allowlist(value: str, pilot_repository_id: int) -> frozenset require(isinstance(ids, list) and ids and all(type(identifier) is int and identifier > 0 for identifier in ids) and len(set(ids)) == len(ids) - and type(pilot_repository_id) is int and pilot_repository_id != JAVA_REPOSITORY_ID - and pilot_repository_id in ids and set(ids) <= {pilot_repository_id, JAVA_REPOSITORY_ID}, + and type(pilot_repository_id) is int and pilot_repository_id in ids, "Invalid bridge repository ID allowlist") return frozenset(ids) -def workflow_claims(token: str, audience: str, pilot_repository_id: int, allowlist: frozenset[int]) -> dict: +@dataclass(frozen=True) +class RepositoryPolicy: + repository: str + issue_workflow: str + issue_events: frozenset[str] + team_memory: bool + + +def load_repository_policies( + value: str | None, pilot_repository_id: int, allowlist: frozenset[int], +) -> dict[int, RepositoryPolicy]: + if value is None: + return {} + require(isinstance(value, str) and 0 < len(value.encode("utf-8")) <= 32 * 1024, + "Invalid bridge repository policy setting size") + entries = json.loads(value, object_pairs_hook=action.unique_object) + require(isinstance(entries, dict), "Expected bridge repository policies keyed by repository ID") + policies = {} + names = {PILOT_REPOSITORY.casefold()} + required = {"repository", "issue_workflow", "issue_events"} + reserved_workflows = {action.COORDINATOR_WORKFLOW.casefold(), action.DISPATCH_WORKFLOW.casefold()} + for key, entry in entries.items(): + require(re.fullmatch(r"[1-9][0-9]*", key), "Invalid bridge repository policy ID") + repository_id = int(key) + require(repository_id != pilot_repository_id and repository_id in allowlist, + "Bridge repository policy ID must be enrolled and non-IssueLens") + require(isinstance(entry, dict) and required <= set(entry) <= required | {"team_memory"}, + "Invalid bridge repository policy fields") + repository = entry["repository"] + require(isinstance(repository, str) and re.fullmatch(action.SOURCE_REPOSITORY_PATTERN, repository) + and ".." not in repository and repository.casefold() not in names, + "Invalid or ambiguous bridge repository policy name") + workflow = entry["issue_workflow"] + require(isinstance(workflow, str) and workflow.startswith(WORKFLOW_DIRECTORY) + and WORKFLOW_BASENAME.fullmatch(workflow[len(WORKFLOW_DIRECTORY):]) + and workflow.casefold() not in reserved_workflows, + "Invalid bridge issue workflow path") + events, team_memory = entry["issue_events"], entry.get("team_memory", False) + require(isinstance(events, list) and events + and all(isinstance(event, str) and event in ISSUE_EVENT_ACTIONS for event in events) + and len(set(events)) == len(events) and type(team_memory) is bool, + "Invalid bridge repository policy events or team-memory opt-in") + names.add(repository.casefold()) + policies[repository_id] = RepositoryPolicy(repository, workflow, frozenset(events), team_memory) + return policies + + +def workflow_claims( + token: str, audience: str, pilot_repository_id: int, allowlist: frozenset[int], + policies: dict[int, RepositoryPolicy], +) -> dict: require(type(pilot_repository_id) is int and pilot_repository_id in allowlist, "Configured IssueLens repository ID does not match the bridge allowlist") require(len(token) <= 16 * 1024, "Invalid workflow token size") @@ -70,48 +124,57 @@ def workflow_claims(token: str, audience: str, pilot_repository_id: int, allowli "ref", "workflow_ref", "workflow_sha", "event_name", "run_id", "run_attempt", "actor", ], "strict_aud": True}, ) - require(isinstance(claims["repository"], str) - and re.fullmatch(r"[A-Za-z0-9-]+/[A-Za-z0-9_.-]+", claims["repository"]) + repository = claims["repository"] + require(isinstance(repository, str) and re.fullmatch(r"[A-Za-z0-9-]+/[A-Za-z0-9_.-]+", repository) and isinstance(claims["repository_id"], str) - and claims["repository_id"].isdecimal() - and int(claims["repository_id"]) in allowlist - and (int(claims["repository_id"]) != pilot_repository_id - or claims["repository"] == PILOT_REPOSITORY) - and (claims["repository"] != PILOT_REPOSITORY - or int(claims["repository_id"]) == pilot_repository_id) - and ((claims["repository"] == JAVA_REPOSITORY) - == (int(claims["repository_id"]) == JAVA_REPOSITORY_ID)) + and re.fullmatch(r"[1-9][0-9]*", claims["repository_id"]) + and isinstance(claims["event_name"], str) and claims["repository_visibility"] == "public" and isinstance(claims["ref"], str) and claims["ref"].startswith("refs/heads/") and claims.get("runner_environment") == "github-hosted", "Workflow is not in the IssueLens pilot scope") + repository_id = int(claims["repository_id"]) + require(repository_id in allowlist + and (repository_id != pilot_repository_id or repository == PILOT_REPOSITORY) + and (repository_id == pilot_repository_id or repository.casefold() != PILOT_REPOSITORY.casefold()), + "Workflow is not in the IssueLens pilot scope") if "ref_protected" in claims: protected = claims["ref_protected"] require(protected is True or protected == "true", "Workflow ref was not protected") - if claims["repository"] == PILOT_REPOSITORY: + policy = policies.get(repository_id) + if repository_id == pilot_repository_id: if claims["workflow_ref"] == workflow_ref(".github/workflows/issue-triage.yml"): - require(claims["event_name"] in {"issues", "issue_comment", "workflow_dispatch"}, - "Unsupported workflow event") + require(claims["event_name"] in ISSUE_EVENT_ACTIONS, "Unsupported workflow event") elif claims["workflow_ref"] == workflow_ref(action.COORDINATOR_WORKFLOW): require(claims["event_name"] == "workflow_dispatch", "Unsupported workflow event") - return _validated_claims(claims, "team-memory", int(claims["repository_id"])) + return _validated_claims(claims, "team-memory", repository_id) else: raise ValueError("Workflow is not enabled for this bridge") - else: - require(claims["repository"] == JAVA_REPOSITORY and claims["ref"] == "refs/heads/main", - "Workflow is not enabled for this bridge") - if claims["workflow_ref"] == workflow_ref(action.COORDINATOR_WORKFLOW, JAVA_REPOSITORY): + elif policy is not None: + require(repository == policy.repository and claims["ref"] == f"refs/heads/{PILOT_BRANCH}", + "Workflow repository or branch does not match bridge policy") + if policy.team_memory and claims["workflow_ref"] == workflow_ref(action.COORDINATOR_WORKFLOW, repository): require(claims["event_name"] == "workflow_dispatch", "Unsupported workflow event") - return _validated_claims(claims, "team-memory", int(claims["repository_id"])) - require(claims["workflow_ref"] == workflow_ref(JAVA_WORKFLOW, JAVA_REPOSITORY) - and claims["event_name"] in {"issues", "issue_comment", "workflow_dispatch"}, + return _validated_claims(claims, "team-memory", repository_id, detailed_policy=True) + require(claims["workflow_ref"] == workflow_ref(policy.issue_workflow, repository) + and claims["event_name"] in policy.issue_events, "Workflow is not enabled for this bridge") - return _validated_claims(claims, "issue-loop", int(claims["repository_id"])) - - -def _validated_claims(claims: dict, kind: str, repository_id: int) -> dict: + else: + require(not any(repository.casefold() == entry.repository.casefold() for entry in policies.values()), + "Workflow repository ID does not match bridge policy") + prefix = f"{repository}/{WORKFLOW_DIRECTORY}" + suffix = "@" + claims["ref"] + workflow = claims["workflow_ref"] + require(claims["event_name"] == "workflow_dispatch" and isinstance(workflow, str) + and workflow.startswith(prefix) and workflow.endswith(suffix) + and WORKFLOW_BASENAME.fullmatch(workflow[len(prefix):-len(suffix)]), + "Only manual workflow dispatches from enrolled repositories are allowed") + return _validated_claims(claims, "issue-loop", repository_id, detailed_policy=policy is not None) + + +def _validated_claims(claims: dict, kind: str, repository_id: int, *, detailed_policy: bool = False) -> dict: return { - **claims, "kind": kind, "repository_id": repository_id, + **claims, "kind": kind, "repository_id": repository_id, "detailed_policy": detailed_policy, "run_id": action.positive(claims["run_id"]), "run_attempt": action.positive(claims["run_attempt"]), "workflow_sha": action.full_sha(claims["workflow_sha"]), } @@ -130,11 +193,11 @@ def default_branch_protected(claims: dict) -> bool: and isinstance(branch_name, str) and branch_name, "Invalid GitHub repository response") if (project["full_name"].casefold() != repository.casefold() - or (repository == JAVA_REPOSITORY and project["full_name"] != JAVA_REPOSITORY) + or (claims["detailed_policy"] and project["full_name"] != repository) or project["id"] != claims["repository_id"] or project["private"] or project["visibility"] != "public" or claims["ref"] != f"refs/heads/{branch_name}"): return False - if "ref_protected" in claims: + if "ref_protected" in claims and not claims["detailed_policy"]: return True branch_path = urllib.parse.quote(branch_name, safe="") branch = action.github_read(f"/repos/{repository}/branches/{branch_path}", token="", timeout=5) @@ -167,11 +230,8 @@ def _positive_int(value): def _issue_job(metadata: dict, claims: dict) -> str: event = claims["event_name"] operation = metadata.get("event_action") - require(metadata.get("event_name") == event and operation in { - "issues": ("opened", "reopened"), - "issue_comment": ("created", "edited"), - "workflow_dispatch": ("workflow_dispatch",), - }[event], "Issue-event identity mismatch") + require(metadata.get("event_name") == event and operation in ISSUE_EVENT_ACTIONS[event], + "Issue-event identity mismatch") comment_event = event == "issue_comment" created = comment_event and operation == "created" require(set(metadata) == { @@ -283,13 +343,13 @@ def get(self, identifier: str): except ResourceNotFoundError: return None - def reserve(self, identifier: str, target: str, payload: bytes): + def reserve(self, identifier: str, target: str, payload: bytes, *, repository: str): existing = self.get(identifier) if existing is not None: return existing job = { "PartitionKey": PARTITION, "RowKey": identifier, "target": target, - "created": int(time.time()), "state": QUEUED, "payload": payload, + "created": int(time.time()), "state": QUEUED, "payload": payload, "repository": repository, } try: self.table.submit_transaction([ @@ -341,9 +401,7 @@ def receipt(job) -> dict: return value -def _verify_created_comment(metadata: dict, digest: str) -> None: - repository = metadata["repository"] - require(repository in {PILOT_REPOSITORY, JAVA_REPOSITORY}, "Invalid comment repository") +def _verify_created_comment(repository: str, metadata: dict, digest: str) -> None: identifier = _positive_int(metadata["comment_id"]) number = _positive_int(metadata["issue_number"]) comment = action.github_read(f"/repos/{repository}/issues/comments/{identifier}", token="") @@ -373,11 +431,20 @@ def __init__(self, url: str, credential: ManagedIdentityCredential): def prepare(self, job) -> urllib.request.Request: payload = json.loads(job["payload"]) kind, metadata = payload["request_type"], payload["metadata"] + repository = job.get("repository") + if "repository" in job: + require(repository == metadata.get("repository"), "Bridge job repository mismatch") if kind == "issue-loop": digest = metadata.pop("comment_sha256", None) if metadata["comment_added"]: require(isinstance(digest, str) and JOB_ID.fullmatch(digest), "Created comment requires its revision digest") - _verify_created_comment(metadata, digest) + if repository is None: + # Only IssueLens could enqueue created comments before the repository field existed. + require(metadata.get("repository") == PILOT_REPOSITORY + and job.get("target") == f"issue-{_positive_int(metadata.get('issue_number'))}", + "Created comment requires an admitted repository") + repository = PILOT_REPOSITORY + _verify_created_comment(repository, metadata, digest) invocation = action.build_issue_loop_request(metadata) elif kind == "team-memory": invocation = action.build_team_memory_request(metadata) diff --git a/automation_bridge/function_app.py b/automation_bridge/function_app.py index 8f5d910..637cd02 100644 --- a/automation_bridge/function_app.py +++ b/automation_bridge/function_app.py @@ -62,8 +62,7 @@ def authorized(request): "A workflow token is required") return bridge.workflow_claims( auth[len("Bearer "):], os.environ["ISSUELENS_BRIDGE_OIDC_AUDIENCE"], - bridge.action.positive(os.environ["ISSUELENS_BRIDGE_REPOSITORY_ID"]), - repository_ids, + pilot_repository_id, repository_ids, repository_policies, ) @@ -73,6 +72,9 @@ def authorized(request): repository_ids = bridge.load_repository_allowlist( os.environ.get("ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST", ""), pilot_repository_id, ) + repository_policies = bridge.load_repository_policies( + os.environ.get("ISSUELENS_BRIDGE_REPOSITORY_POLICIES"), pilot_repository_id, repository_ids, + ) @app.route(route="issuelens/v1/jobs", methods=["POST"], trigger_arg_name="request") def submit(request: func.HttpRequest) -> func.HttpResponse: @@ -99,7 +101,7 @@ def submit(request: func.HttpRequest) -> func.HttpResponse: return respond({"error": "workflow_not_authorized"}, 401) identifier = bridge.job_id(claims) try: - job = jobs().reserve(identifier, target, body) + job = jobs().reserve(identifier, target, body, repository=claims["repository"]) if job["state"] == bridge.QUEUED: # A repeated send can only reference the original reservation. with service_bus().get_queue_sender(os.environ["ISSUELENS_BRIDGE_QUEUE"]) as sender: diff --git a/docs/guide.md b/docs/guide.md index 9dd1f44..3be6cef 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1053,9 +1053,8 @@ routing and command validation; no new permanent agent contract is introduced. ### IssueLens Function bridge pilot -Configure the ingress Function's reviewed repository allowlist to admit -`microsoft/IssueLens` and `microsoft/vscode-java-pack` issue-loop and -same-repository team-memory jobs. Keep the GitHub App webhook unchanged. Obtain +Configure repository enrollment and workflow policy through the ingress +Function app settings. Keep the GitHub App webhook unchanged. Obtain approval for the GitHub-facing endpoint, direct trust of the GitHub Actions issuer, network access, and the Azure release path before provisioning or enabling anything. The Function validates a GitHub token addressed to itself; @@ -1066,8 +1065,8 @@ workflow revision is responsible for validating the event before submission. Build the Function source bundle from the reviewed bridge and action revision: `python -m automation_bridge.bundle `. The ZIP contains only the two Functions roles and the reused workflow helpers, with a separate dependency -manifest. A missing or invalid ingress allowlist setting prevents ingress from -initializing. Publish it through an approved release path to +manifest. A missing or invalid ingress allowlist or an invalid supplied policy +prevents ingress from initializing. Publish it through an approved release path to **two** Function apps with distinct managed identities. Use a plan that supports a 40-minute function timeout for the worker. Use identity-backed Functions host storage separately from the application job table. @@ -1075,59 +1074,81 @@ from the application job table. | Target | Configuration and access | | --- | --- | | Both Function apps | `ISSUELENS_BRIDGE_TABLE_ACCOUNT` points to the account containing precreated `IssueLensBridgeJobs`. Both need Table data read/write on that table. `ISSUELENS_BRIDGE_QUEUE` and `ISSUELENS_BRIDGE_SERVICE_BUS__fullyQualifiedNamespace` identify the same dedicated Service Bus queue. Use a queue with duplicate detection; reservations remain authoritative even outside the broker window. | -| Ingress | `ISSUELENS_BRIDGE_ROLE=ingress`, `ISSUELENS_BRIDGE_REPOSITORY_ID` set to the existing IssueLens numeric GitHub repository ID (`1303440932`), `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST` set to the reviewed JSON ID array, and `ISSUELENS_BRIDGE_OIDC_AUDIENCE` set to the exact HTTPS `/api/issuelens/v1/jobs` URL on the approved `azurewebsites.net` endpoint. The IssueLens ID must be in the allowlist or ingress fails closed. Only IssueLens and Java Pack IDs are supported. The receiver verifies signature, audience, issuer, public repository identity, GitHub-hosted runner, current default branch and protection; Java Pack is restricted to its exact reviewed workflows on `main`. IssueLens retains its exact workflow/event restrictions. Grant queue **Data Sender** only. Enforce HTTPS and set `FUNCTIONS_REQUEST_BODY_SIZE_LIMIT=32768` to cap requests before they reach Python. | +| Ingress | `ISSUELENS_BRIDGE_ROLE=ingress`, `ISSUELENS_BRIDGE_REPOSITORY_ID` set to the existing IssueLens numeric GitHub repository ID (`1303440932`), `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST` set to the reviewed JSON ID array, and `ISSUELENS_BRIDGE_OIDC_AUDIENCE` set to the exact HTTPS `/api/issuelens/v1/jobs` URL on the approved `azurewebsites.net` endpoint. Use optional `ISSUELENS_BRIDGE_REPOSITORY_POLICIES` for exact workflow/event policies for enrolled non-IssueLens repositories. Grant queue **Data Sender** only. Enforce HTTPS and set `FUNCTIONS_REQUEST_BODY_SIZE_LIMIT=32768` to cap requests before they reach Python. | | Worker | `ISSUELENS_BRIDGE_ROLE=worker`, `ISSUELENS_BRIDGE_FOUNDRY_URL` set to the existing deployed agent's full invocations URL (including API version). Grant queue **Data Receiver** and the narrowest applicable Foundry invocation access to the worker managed identity. It requests an Entra token for `https://ai.azure.com/.default`. No repository write, deployment, signing key, or GitHub App key access is needed. | -Keep `main` protected. If the signed token supplies `ref_protected`, the -bridge rejects a value that does not confirm protection. If the claim is -missing, the ingress must confirm current protection through GitHub's public -branch API before reserving or queueing a job. An unprotected branch or an -unavailable check stops admission. Status polls still require the owning -workflow run's signed identity, but do not repeat the branch API check. +The bridge verifies the signed workflow identity, public GitHub-hosted runner +scope, and current public repository/default branch before admission. If a +signed `ref_protected` claim is supplied it must affirm protection. For a +detailed policy, or if that claim is absent, ingress must independently +confirm current protection through GitHub's public branch API. Unprotected +branches and unavailable checks stop admission. Status polls still require +the owning run's signed identity under the active policy; they do not repeat +the branch API check. Use `automation_bridge/repository_allowlist.example.json` as the initial `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST` value: a JSON array of numeric GitHub repository IDs. The existing `ISSUELENS_BRIDGE_REPOSITORY_ID` setting must remain in that array and continues to identify IssueLens. The setting is -limited to 32 KiB; missing IssueLens enrollment, malformed JSON, duplicate or -invalid IDs, unreviewed IDs, and missing settings fail closed. - -For enrolled Java Pack, the bridge accepts `issues`, `issue_comment`, and -`workflow_dispatch` issue-loop events only from `.github/workflows/issueLens-run.yml` -on protected `main`. The same issue action and human-comment restrictions apply -as for IssueLens. The bridge checks repository ID, public visibility, canonical -name, current default branch, and branch protection using GitHub metadata; it -accepts no dispatch-supplied repository list or arbitrary job type. The -existing IssueLens issue workflow keeps its event behavior. - -Java Pack team-memory requires a GitHub-hosted `workflow_dispatch` from -`.github/workflows/team-memory-coordinator.yml` on protected `main`. The -coordinator, source, and validated wiki destination must all be -`microsoft/vscode-java-pack`; cross-repository sources are not admitted. -Manual PR and coordinated push-range requests share the Java Pack wiki -reservation, separate from IssueLens. The pinned action -`b88dadd40754d640cbb82f4d9a5e9d36e8386981` requires an explicit -`source-repository: microsoft/vscode-java-pack` even for manual PR requests -to generate the coordinated envelope. Source run metadata cannot prove the -original push boundary or flags. A consumer must independently configure its -own coordinator queue, source read credentials, validated wiki policy, and -App access; bridge admission does not grant these permissions or guarantee -publication. +limited to 32 KiB; IDs must be positive, unique integers. An enrolled +non-IssueLens ID without a detailed policy can submit only manual +`workflow_dispatch` issue-loop jobs from a workflow on its protected default +branch. ID enrollment alone does not admit automatic events or team-memory. +IssueLens keeps its built-in workflow and event restrictions. + +`ISSUELENS_BRIDGE_REPOSITORY_POLICIES` is an optional JSON object (up to 32 KiB) +keyed by enrolled non-IssueLens repository IDs as decimal strings without +leading zeroes. Omit it or use `{}` for ID-only enrollment. Each entry requires +an exact canonical `repository` (`owner/repository`), `issue_workflow` (a +single `.github/workflows/` YAML file, distinct from the team-memory workflows), +and a nonempty, unique `issue_events` array drawn from `issues`, `issue_comment`, +and `workflow_dispatch`. `team_memory` is an optional JSON boolean, off unless +explicitly `true`. Invalid JSON, unknown fields, duplicate keys or canonical +names (including case variants), and entries for unenrolled or IssueLens IDs +fail closed. For a detailed entry, the exact ID, repository spelling, workflow +and event must match. There is no fallback to ID-only admission on mismatch. +The supported policy contract requires `main` to be the repository's protected +default branch. Issue action and human-comment restrictions are unchanged. + +Team-memory opt-in admits only `workflow_dispatch` from the exact +`.github/workflows/team-memory-coordinator.yml` workflow. Coordinated push +ranges must identify `.github/workflows/team-memory-post-merge.yml` in the +same repository. Coordinator, source and validated wiki destination must all +match the authenticated repository. Manual PR and coordinated range requests +share that repository's wiki reservation, separate from other repositories. +Source run metadata cannot prove the original push boundary or flags. Each +consumer still needs its own coordinator queue, source read credentials, +validated wiki policy and App access. Bridge admission does not grant those +permissions or guarantee publication. Restrict permission to modify Function App settings to authorized operators: the allowlist controls admission and must never come from workflow or dispatch inputs. Review each repository's public identity, default branch protection, -workflow code, and App permissions before adding its ID. Only the two reviewed -IDs are supported; onboarding another repository requires a code change. Azure -applies app setting changes by restarting the Function App. Removing an entry -also prevents its existing runs from polling -their receipts, so reconcile in-flight jobs before removal. Configuration and -release approval remain separate from this code change. - -Java Pack enrollment requires a separately approved bridge release and caller -workflow change. The allowlist admits public `microsoft/vscode-java-pack` -(repository ID `104967329`) only from its exact reviewed workflows on protected -`main`. Update and enable those workflows only after approval, provide +workflow code, and App permissions before adding an ID or expanding its policy. +Azure applies app setting changes by restarting the Function App. Policy +changes can prevent affected runs from continuing to poll their receipts; +reconcile in-flight jobs first. Removing a detailed policy retains ID-only +manual issue-loop admission; remove both the entry and the ID to revoke +enrollment. Configuration and release require separate approval. + +For Java Pack, retain `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST=[1303440932,104967329]` +and set this value for `ISSUELENS_BRIDGE_REPOSITORY_POLICIES` on ingress: + +```json +{ + "104967329": { + "repository": "microsoft/vscode-java-pack", + "issue_workflow": ".github/workflows/issueLens-run.yml", + "issue_events": ["issues", "issue_comment", "workflow_dispatch"], + "team_memory": true + } +} +``` + +Keep the Java Pack workflows disabled during rollout. After approval, deploy +the same ZIP built from the merged IssueLens revision to worker first and +then ingress, and confirm ingress has the reviewed policy before enabling +the merged caller workflows. Provide the approved `ISSUELENS_BRIDGE_URL` Actions secret, and use the composite action with `request-type: issue-loop`, `transport: bridge`, `issue-number`, and `bridge-url`. The issue-loop job needs `issues: read` and @@ -1135,12 +1156,12 @@ with `request-type: issue-loop`, `transport: bridge`, `issue-number`, and not a pull request. Confirm the GitHub App has installation access and the necessary issue permissions for any authorized writes. Use privacy-appropriate output settings and a controlled issue; this is a write-capable invocation. -The merged IssueLens action revision -`b88dadd40754d640cbb82f4d9a5e9d36e8386981` supports these bridge inputs. -Review and pin an approved full revision before enabling. The bridge trusts the signed workflow identity -and its protected-branch code, not a separately attested payload or a pinned -workflow SHA. Changes to this allowlist require authorized configuration -review; workflow inputs cannot enroll repositories. +The existing Java Pack action pin +`b88dadd40754d640cbb82f4d9a5e9d36e8386981` supports these bridge inputs and +requires `source-repository: microsoft/vscode-java-pack` even for manual PR +requests to generate the coordinated envelope. The bridge trusts the signed +workflow identity and its protected-branch code, not a separately attested +payload or a pinned workflow SHA. Workflow inputs cannot change enrollment. The worker POSTs the standard `{ "input": "..." }` payload to the existing `/invocations` API. No replacement agent, host configuration change, or Foundry @@ -1164,12 +1185,13 @@ run on a controlled merged PR, and leave `ISSUELENS_TEAM_MEMORY_ENABLED` off until the manual path and resulting App-attributed writes have been verified. The action sends metadata only, never issue/comment text or `GITHUB_TOKEN`. For a new comment it sends a digest. The worker checks the current revision -using an unauthenticated public GitHub read before the Foundry call. This +using an unauthenticated public GitHub read scoped to the authenticated +repository stored with the admitted job, before the Foundry call. This point-in-time check does not lock the comment against later edits; the agent's existing authoritative comment, command, and replay checks remain in place. The coordinator waits on the job receipt; acknowledgement is not maintenance -success. Reservations cover one issue per repository or the one IssueLens wiki through +success. Reservations cover one issue or wiki per repository through completion, including when a GitHub waiter is canceled. The queue contains job IDs only. The table keeps pending job metadata and bounded terminal identifiers and outcomes, not raw agent text. A runner retry may recover the same queued diff --git a/tests/test_automation_bridge.py b/tests/test_automation_bridge.py index 39fd827..a5454e8 100644 --- a/tests/test_automation_bridge.py +++ b/tests/test_automation_bridge.py @@ -30,11 +30,23 @@ JAVA_REPOSITORY = "microsoft/vscode-java-pack" JAVA_REPOSITORY_ID = 104967329 JAVA_WORKFLOW = ".github/workflows/issueLens-run.yml" +OTHER_REPOSITORY = "example/Project-Two" +OTHER_REPOSITORY_ID = 24681012 +OTHER_WORKFLOW = ".github/workflows/route-issues.yaml" URL = "https://issuelens.azurewebsites.net/api/issuelens/v1/jobs" ENDPOINT = "https://account.services.ai.azure.com/test/protocols/invocations?api-version=2025-11-15-preview" JOB = "7" * 64 COMMENT_URL = f"https://api.github.com/repos/{PILOT_REPOSITORY}/issues/comments/41" ALLOWLIST_JSON = pathlib.Path(bridge.__file__).with_name("repository_allowlist.example.json").read_text(encoding="utf-8") +EXTENDED_ALLOWLIST = json.dumps([*json.loads(ALLOWLIST_JSON), OTHER_REPOSITORY_ID]) +JAVA_POLICY = { + "repository": JAVA_REPOSITORY, "issue_workflow": JAVA_WORKFLOW, + "issue_events": ["issues", "issue_comment", "workflow_dispatch"], "team_memory": True, +} +OTHER_POLICY = { + "repository": OTHER_REPOSITORY, "issue_workflow": OTHER_WORKFLOW, "issue_events": ["issue_comment"], +} +POLICIES_JSON = json.dumps({JAVA_REPOSITORY_ID: JAVA_POLICY}) def issue_metadata(**overrides): @@ -59,6 +71,21 @@ def current_comment(): } +def manual_memory_payload(claims): + repository = claims["repository"] + return {"request_type": "team-memory", "metadata": { + "repository": repository, "repository_id": claims["repository_id"], "base_ref": "main", + "event_name": "workflow_dispatch", "event_action": "workflow_dispatch", + "actor_login": "maintainer", "triggering_actor": "maintainer", + "workflow_ref": claims["workflow_ref"], "workflow_sha": claims["workflow_sha"], + "run_id": 20, "run_attempt": 1, "coordinator_repository": repository, + "coordinator_workflow_ref": claims["workflow_ref"], "coordinator_workflow_sha": claims["workflow_sha"], + "coordinator_run_id": 20, "coordinator_run_attempt": 1, "required_wiki_repository": repository, + "pull_number": 12, "merge_commit_sha": "a" * 40, "merged_at": "2026-11-24T00:00:00Z", + "source_identity": f"{repository}#12:{'a' * 40}", + }} + + class BridgeIdentityTests(unittest.TestCase): @classmethod def setUpClass(cls): @@ -78,16 +105,22 @@ def setUp(self): def token(self, **overrides): return jwt.encode(self.claims | overrides, self.key, algorithm="RS256") - def workflow_claims(self, token, audience, repository_id): - allowlist = bridge.load_repository_allowlist(ALLOWLIST_JSON, PILOT_REPOSITORY_ID) - return bridge.workflow_claims(token, audience, repository_id, allowlist) + def workflow_claims(self, token, audience, repository_id, *, allowlist_json=ALLOWLIST_JSON, + policies_json=POLICIES_JSON): + allowlist = bridge.load_repository_allowlist(allowlist_json, PILOT_REPOSITORY_ID) + policies = bridge.load_repository_policies(policies_json, PILOT_REPOSITORY_ID, allowlist) + return bridge.workflow_claims(token, audience, repository_id, allowlist, policies) - def load_ingress(self, allowlist=ALLOWLIST_JSON): + def load_ingress(self, allowlist=ALLOWLIST_JSON, policies=POLICIES_JSON, pilot_id=PILOT_REPOSITORY_ID): self.enterContext(patch.dict(os.environ, { - "ISSUELENS_BRIDGE_ROLE": "ingress", "ISSUELENS_BRIDGE_REPOSITORY_ID": str(PILOT_REPOSITORY_ID), + "ISSUELENS_BRIDGE_ROLE": "ingress", "ISSUELENS_BRIDGE_REPOSITORY_ID": str(pilot_id), "ISSUELENS_BRIDGE_OIDC_AUDIENCE": URL, "ISSUELENS_BRIDGE_QUEUE": "test-jobs", "ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST": allowlist, })) + if policies is None: + os.environ.pop("ISSUELENS_BRIDGE_REPOSITORY_POLICIES", None) + else: + os.environ["ISSUELENS_BRIDGE_REPOSITORY_POLICIES"] = policies path = pathlib.Path(bridge.__file__).with_name("function_app.py") spec = importlib.util.spec_from_file_location("test_bridge_ingress", path) assert spec is not None and spec.loader is not None @@ -162,24 +195,79 @@ def test_java_pack_admission_is_limited_to_its_reviewed_workflow(self): self.assertNotEqual(bridge.job_id(pilot), bridge.job_id(accepted)) self.assertEqual(bridge.job_id(accepted), bridge.job_id(accepted | {"run_attempt": 2})) - def test_ingress_rejects_requests_if_configured_issuelens_id_disagrees_with_manifest(self): - ingress, submit, status = self.load_ingress() - with ( - patch.dict(os.environ, {"ISSUELENS_BRIDGE_REPOSITORY_ID": str(JAVA_REPOSITORY_ID)}), - patch.object(ingress, "jobs") as jobs, + def test_ingress_rejects_inconsistent_issuelens_id_or_unenrolled_policy_at_startup(self): + for settings in ( + {"pilot_id": JAVA_REPOSITORY_ID}, + {"pilot_id": OTHER_REPOSITORY_ID}, + {"allowlist": json.dumps([PILOT_REPOSITORY_ID])}, ): - self.assertEqual(submit(self.request()).status_code, 401) - self.assertEqual(status(self.request(JOB)).status_code, 401) - jobs.assert_not_called() + with self.subTest(settings=settings), self.assertRaises(ValueError): + self.load_ingress(**settings) + + def test_id_only_enrollment_keeps_the_legacy_manual_contract(self): + ref = "refs/heads/trunk" + workflow = bridge.workflow_ref(".github/workflows/any-manual.yaml", JAVA_REPOSITORY, "trunk") + for config in (None, json.dumps({OTHER_REPOSITORY_ID: OTHER_POLICY})): + def authenticate(**overrides): + token = self.java_token(**({"ref": ref, "workflow_ref": workflow} | overrides)) + return self.workflow_claims( + token, URL, PILOT_REPOSITORY_ID, allowlist_json=EXTENDED_ALLOWLIST, policies_json=config, + ) - def test_ingress_rejects_an_unreviewed_repository_in_the_allowlist(self): - ids = json.loads(ALLOWLIST_JSON) - ids.append(12345678) + with self.subTest(config=config): + claims = authenticate() + self.assertEqual(bridge.validate_request(self.java_payload(), claims), "repo-104967329-issue-12") + for event in ("issues", "issue_comment", "push"): + with self.assertRaises(ValueError): + authenticate(event_name=event) + coordinator = authenticate(workflow_ref=bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY, "trunk")) + self.assertEqual(coordinator["kind"], "issue-loop") + with self.assertRaises(ValueError): + bridge.validate_request({"request_type": "team-memory", "metadata": {}}, coordinator) + with self.assertRaises(ValueError): + self.workflow_claims(self.java_token(), URL, PILOT_REPOSITORY_ID, + allowlist_json=json.dumps([PILOT_REPOSITORY_ID]), policies_json=None) + + def test_detailed_policy_scopes_events_and_team_memory_per_repository(self): + def authenticate(*, policy=OTHER_POLICY, **overrides): + configured = json.dumps({JAVA_REPOSITORY_ID: JAVA_POLICY, OTHER_REPOSITORY_ID: policy}) + claims = { + "repository": OTHER_REPOSITORY, "repository_id": str(OTHER_REPOSITORY_ID), + "workflow_ref": bridge.workflow_ref(OTHER_WORKFLOW, OTHER_REPOSITORY), + } | overrides + return self.workflow_claims(self.token(**claims), URL, PILOT_REPOSITORY_ID, + allowlist_json=EXTENDED_ALLOWLIST, policies_json=configured) + + claims = authenticate() + payload = issue_payload(repository=OTHER_REPOSITORY) + self.assertEqual(bridge.validate_request(payload, claims), f"repo-{OTHER_REPOSITORY_ID}-issue-12") + java = self.workflow_claims(self.java_token(event_name="issue_comment"), URL, PILOT_REPOSITORY_ID) + self.assertNotEqual(bridge.job_id(java), bridge.job_id(claims)) + coordinator = {"workflow_ref": bridge.workflow_ref(MEMORY_WORKFLOW, OTHER_REPOSITORY), + "event_name": "workflow_dispatch"} + for mismatch in ( + {"event_name": "issues"}, {"event_name": "workflow_dispatch"}, coordinator, + {"repository": JAVA_REPOSITORY}, {"repository_id": str(JAVA_REPOSITORY_ID)}, + {"repository": OTHER_REPOSITORY.lower()}, {"ref": "refs/heads/trunk"}, + {"workflow_ref": bridge.workflow_ref(OTHER_WORKFLOW.lower(), OTHER_REPOSITORY.lower())}, + {"workflow_ref": bridge.workflow_ref(JAVA_WORKFLOW, OTHER_REPOSITORY)}, + ): + with self.subTest(mismatch=mismatch), self.assertRaises(ValueError): + authenticate(**mismatch) + memory = authenticate(policy=OTHER_POLICY | {"team_memory": True}, **coordinator) + wiki_payload = manual_memory_payload(memory) + self.assertEqual(bridge.validate_request(wiki_payload, memory), f"repo-{OTHER_REPOSITORY_ID}-wiki") + self.assertNotEqual(bridge.job_id(memory), bridge.job_id(claims)) + wiki_payload["metadata"]["required_wiki_repository"] = JAVA_REPOSITORY with self.assertRaises(ValueError): - self.load_ingress(json.dumps(ids)) - allowlist = bridge.load_repository_allowlist(json.dumps([PILOT_REPOSITORY_ID]), PILOT_REPOSITORY_ID) + bridge.validate_request(wiki_payload, memory) with self.assertRaises(ValueError): - bridge.workflow_claims(self.java_token(), URL, PILOT_REPOSITORY_ID, allowlist) + authenticate(policy=OTHER_POLICY | {"team_memory": True}, **(coordinator | {"event_name": "push"})) + + def test_detailed_policy_name_cannot_fall_back_to_an_id_only_enrollment(self): + misleading_token = self.java_token(repository_id=str(OTHER_REPOSITORY_ID)) + with self.assertRaisesRegex(ValueError, "repository ID does not match"): + self.workflow_claims(misleading_token, URL, PILOT_REPOSITORY_ID, allowlist_json=EXTENDED_ALLOWLIST) def test_java_pack_event_actions_follow_existing_issue_rules(self): for event, operation in (("issues", "opened"), ("issues", "reopened"), @@ -205,18 +293,7 @@ def test_existing_team_memory_workflow_remains_enabled(self): workflow_ref=bridge.workflow_ref(MEMORY_WORKFLOW), event_name="workflow_dispatch", ref_protected="true", ), URL, PILOT_REPOSITORY_ID) - metadata = { - "repository": PILOT_REPOSITORY, "repository_id": PILOT_REPOSITORY_ID, "base_ref": "main", - "event_name": "workflow_dispatch", "event_action": "workflow_dispatch", - "actor_login": "maintainer", "triggering_actor": "maintainer", - "workflow_ref": claims["workflow_ref"], "workflow_sha": claims["workflow_sha"], - "run_id": 20, "run_attempt": 1, "coordinator_repository": PILOT_REPOSITORY, - "coordinator_workflow_ref": claims["workflow_ref"], "coordinator_workflow_sha": claims["workflow_sha"], - "coordinator_run_id": 20, "coordinator_run_attempt": 1, "required_wiki_repository": PILOT_REPOSITORY, - "pull_number": 12, "merge_commit_sha": "a" * 40, "merged_at": "2026-11-24T00:00:00Z", - "source_identity": f"{PILOT_REPOSITORY}#12:{'a' * 40}", - } - self.assertEqual(bridge.validate_request({"request_type": "team-memory", "metadata": metadata}, claims), "wiki") + self.assertEqual(bridge.validate_request(manual_memory_payload(claims), claims), "wiki") def test_packaged_java_coordinator_manual_and_push_contract(self): project = {"full_name": JAVA_REPOSITORY, "id": JAVA_REPOSITORY_ID, @@ -262,10 +339,11 @@ def test_packaged_java_coordinator_manual_and_push_contract(self): packaged = importlib.util.module_from_spec(spec) spec.loader.exec_module(packaged) allowlist = packaged.load_repository_allowlist(ALLOWLIST_JSON, PILOT_REPOSITORY_ID) + policies = packaged.load_repository_policies(POLICIES_JSON, PILOT_REPOSITORY_ID, allowlist) with patch.object(packaged.KEYS, "get_signing_key_from_jwt", return_value=Mock(key=self.key.public_key())): claims = packaged.workflow_claims( self.java_token(workflow_ref=coordinator_ref, ref_protected="true"), - URL, PILOT_REPOSITORY_ID, allowlist, + URL, PILOT_REPOSITORY_ID, allowlist, policies, ) self.assertEqual(claims["kind"], "team-memory") for overrides in ( @@ -275,7 +353,7 @@ def test_packaged_java_coordinator_manual_and_push_contract(self): ): with self.subTest(claims=overrides), self.assertRaises((ValueError, jwt.PyJWTError)): packaged.workflow_claims(self.java_token(**({"workflow_ref": coordinator_ref} | overrides)), - URL, PILOT_REPOSITORY_ID, allowlist) + URL, PILOT_REPOSITORY_ID, allowlist, policies) worker = packaged.FoundryWorker(ENDPOINT, Mock(get_token=Mock(return_value=Mock(token="token")))) for wrong_run in ( source_run | {"repository": project | {"id": PILOT_REPOSITORY_ID}}, @@ -302,7 +380,8 @@ def test_packaged_java_coordinator_manual_and_push_contract(self): metadata = envelope["metadata"] payload = {"request_type": "team-memory", "metadata": metadata} self.assertEqual(packaged.validate_request(payload, claims), "repo-104967329-wiki") - self.assertEqual(json.loads(worker.prepare({"payload": json.dumps(payload)}).data), envelope["request"]) + job = {"repository": claims["repository"], "payload": json.dumps(payload)} + self.assertEqual(json.loads(worker.prepare(job).data), envelope["request"]) for key, wrong in ( ("repository", PILOT_REPOSITORY), ("repository_id", PILOT_REPOSITORY_ID), ("coordinator_repository", PILOT_REPOSITORY), ("required_wiki_repository", PILOT_REPOSITORY), @@ -358,9 +437,9 @@ def test_java_memory_receipt_is_owned_by_the_coordinator_run(self): ) self.assertEqual(status(self.request(identifier, token=different_run)).status_code, 404) - def test_java_pack_fallback_and_same_run_receipt_are_repository_bound(self): + def test_detailed_policy_requires_current_canonical_repository_and_branch_protection(self): ingress, submit, status = self.load_ingress() - token = self.java_token() + token = self.java_token(ref_protected="true") claims = self.workflow_claims(token, URL, PILOT_REPOSITORY_ID) identifier = bridge.job_id(claims) repository_info = { @@ -381,6 +460,7 @@ def test_java_pack_fallback_and_same_run_receipt_are_repository_bound(self): "/repos/microsoft/vscode-java-pack/branches/main", ]) self.assertEqual(jobs.return_value.reserve.call_args.args[1], "repo-104967329-issue-12") + self.assertEqual(jobs.return_value.reserve.call_args.kwargs, {"repository": JAVA_REPOSITORY}) self.assertEqual(status(self.request(identifier, token=token)).status_code, 200) self.assertEqual(status(self.request(identifier)).status_code, 404) with ( @@ -416,7 +496,7 @@ def test_java_pack_action_preflight_produces_an_admissible_manual_job(self): payload = {"request_type": "issue-loop", "metadata": envelope["metadata"]} self.assertEqual(bridge.validate_request(payload, claims), "repo-104967329-issue-12") request = bridge.FoundryWorker(ENDPOINT, Mock(get_token=Mock(return_value=Mock(token="token")))).prepare( - {"payload": json.dumps(payload)} + {"repository": claims["repository"], "payload": json.dumps(payload)} ) self.assertEqual(json.loads(request.data), envelope["request"]) @@ -436,6 +516,7 @@ def test_packaged_action_and_bridge_handle_java_issue_and_comment_events(self): packaged = importlib.util.module_from_spec(spec) spec.loader.exec_module(packaged) allowlist = packaged.load_repository_allowlist(ALLOWLIST_JSON, PILOT_REPOSITORY_ID) + policies = packaged.load_repository_policies(POLICIES_JSON, PILOT_REPOSITORY_ID, allowlist) worker = packaged.FoundryWorker(ENDPOINT, Mock(get_token=Mock(return_value=Mock(token="token")))) for event_name, event in ( ("issues", {"action": "opened", "issue": {"number": 12}, @@ -454,7 +535,7 @@ def test_packaged_action_and_bridge_handle_java_issue_and_comment_events(self): envelope = packaged.action.prepare_issue_loop(JAVA_REPOSITORY, event) claims = packaged.workflow_claims( self.java_token(event_name=event_name, ref_protected="true"), - URL, PILOT_REPOSITORY_ID, allowlist, + URL, PILOT_REPOSITORY_ID, allowlist, policies, ) payload = {"request_type": "issue-loop", "metadata": envelope["metadata"]} self.assertEqual(packaged.validate_request(payload, claims), "repo-104967329-issue-12") @@ -462,8 +543,9 @@ def test_packaged_action_and_bridge_handle_java_issue_and_comment_events(self): with self.assertRaises(ValueError): packaged.validate_request(wrong, claims) comment = current_comment() | {"issue_url": f"https://api.github.com/repos/{JAVA_REPOSITORY}/issues/12"} + job = {"repository": claims["repository"], "payload": json.dumps(payload)} with patch.object(packaged.action, "github_read", return_value=comment) as read: - request = worker.prepare({"payload": json.dumps(payload)}) + request = worker.prepare(job) self.assertEqual(json.loads(request.data), envelope["request"]) if event_name == "issue_comment": read.assert_called_once_with(f"/repos/{JAVA_REPOSITORY}/issues/comments/41", token="") @@ -472,7 +554,7 @@ def test_packaged_action_and_bridge_handle_java_issue_and_comment_events(self): if event_name == "issue_comment": with patch.object(packaged.action, "github_read", return_value=current_comment()): with self.assertRaises(ValueError): - worker.prepare({"payload": json.dumps(payload)}) + worker.prepare(job) def test_only_the_expected_workflow_identity_is_accepted(self): accepted = self.workflow_claims(self.token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) @@ -566,7 +648,7 @@ def test_missing_protection_claim_does_not_admit_jobs_without_confirmed_protecti bus.assert_not_called() -class BridgeAllowlistTests(unittest.TestCase): +class BridgeConfigurationTests(unittest.TestCase): def test_invalid_id_allowlist_is_rejected_as_a_whole(self): original = ALLOWLIST_JSON ids = json.loads(original) @@ -578,12 +660,42 @@ def test_invalid_id_allowlist_is_rejected_as_a_whole(self): "oversize": " " * (32 * 1024 + 1), "object instead of list": json.dumps({"repositories": ids}), "missing IssueLens ID": json.dumps([JAVA_REPOSITORY_ID]), - "unreviewed ID": json.dumps(ids + [12345678]), + "non-positive ID": json.dumps(ids + [0]), } for label, content in invalid.items(): with self.subTest(label=label), self.assertRaises(ValueError): bridge.load_repository_allowlist(content, PILOT_REPOSITORY_ID) + def test_malformed_or_ambiguous_repository_policies_fail_closed(self): + allowlist = bridge.load_repository_allowlist(EXTENDED_ALLOWLIST, PILOT_REPOSITORY_ID) + other_id = str(OTHER_REPOSITORY_ID) + with_duplicate_id = f"{{{json.dumps(other_id)}: {json.dumps(OTHER_POLICY)}, {json.dumps(other_id)}: null}}" + invalid = { + "empty string": "", + "invalid JSON": "{", + "oversize": " " * (32 * 1024 + 1), + "array instead of object": "[]", + "duplicate ID": with_duplicate_id, + "non-canonical ID": json.dumps({"0" + other_id: OTHER_POLICY}), + "unenrolled ID": json.dumps({42: OTHER_POLICY}), + "IssueLens ID": json.dumps({PILOT_REPOSITORY_ID: OTHER_POLICY}), + "IssueLens name": json.dumps({other_id: OTHER_POLICY | {"repository": PILOT_REPOSITORY.lower()}}), + "duplicate name": json.dumps({ + JAVA_REPOSITORY_ID: JAVA_POLICY, other_id: OTHER_POLICY | {"repository": JAVA_REPOSITORY.upper()}, + }), + } + for field_override in ( + {"repo": OTHER_REPOSITORY}, {"repository": "https://github.com/example/repo"}, + {"issue_workflow": ".github/workflows/subdir/issue.yml"}, + {"issue_workflow": MEMORY_WORKFLOW}, {"issue_workflow": bridge.action.DISPATCH_WORKFLOW}, + {"issue_events": ["pull_request"]}, {"issue_events": ["issue_comment", "issue_comment"]}, + {"issue_events": []}, {"issue_events": [None]}, {"team_memory": "true"}, + ): + invalid[str(field_override)] = json.dumps({other_id: OTHER_POLICY | field_override}) + for label, content in invalid.items(): + with self.subTest(label=label), self.assertRaises(ValueError): + bridge.load_repository_policies(content, PILOT_REPOSITORY_ID, allowlist) + class BridgeActionTests(unittest.TestCase): def test_workflow_token_uses_the_bridge_audience_and_a_github_origin(self): @@ -693,7 +805,7 @@ def test_worker_verifies_created_comment_without_forwarding_body_or_digest(self) patch.object(bridge.urllib.request, "build_opener") as opener: get = opener.return_value.open get.return_value.__enter__.return_value.read.return_value = json.dumps(current_comment()).encode() - request = self.worker.prepare({"payload": json.dumps(payload)}) + request = self.worker.prepare({"target": "issue-12", "payload": json.dumps(payload)}) github_request, = get.call_args.args self.assertEqual((github_request.full_url, github_request.get_method()), (COMMENT_URL, "GET")) self.assertFalse(github_request.has_header("Authorization")) @@ -704,7 +816,8 @@ def test_worker_verifies_created_comment_without_forwarding_body_or_digest(self) self.assertNotIn(b"test comment", request.data) def test_changed_or_unavailable_comment_never_reaches_foundry(self): - job = {"state": bridge.RUNNING, "created": int(time.time()), "payload": json.dumps(issue_payload())} + job = {"state": bridge.RUNNING, "created": int(time.time()), "repository": PILOT_REPOSITORY, + "payload": json.dumps(issue_payload())} for comment in ( {**current_comment(), "body": "Edited within the same second"}, {**current_comment(), "updated_at": "2026-11-24T00:00:01Z"}, @@ -721,6 +834,28 @@ def test_changed_or_unavailable_comment_never_reaches_foundry(self): opener.assert_not_called() self.credential.get_token.assert_not_called() + def test_worker_uses_durably_admitted_repository_not_the_queued_payload_for_comments(self): + store = bridge.JobStore(Mock()) + target = f"repo-{OTHER_REPOSITORY_ID}-issue-12" + with patch.object(store, "get", return_value=None): + job = store.reserve(JOB, target, json.dumps(issue_payload(repository=OTHER_REPOSITORY)).encode(), + repository=OTHER_REPOSITORY) + operations, = store.table.submit_transaction.call_args.args + self.assertEqual(operations[1][1]["repository"], OTHER_REPOSITORY) + current = current_comment() | {"issue_url": f"https://api.github.com/repos/{OTHER_REPOSITORY}/issues/12"} + with patch.object(bridge.action, "github_read", return_value=current) as read: + self.worker.prepare(job) + read.assert_called_once_with(f"/repos/{OTHER_REPOSITORY}/issues/comments/41", token="") + tampered = job | {"payload": json.dumps(issue_payload())} + unbound = {key: value for key, value in job.items() if key != "repository"} + self.credential.reset_mock() + with patch.object(bridge.action, "github_read") as read: + for rejected in (tampered, unbound, unbound | {"payload": json.dumps(issue_payload())}): + with self.subTest(job=rejected), self.assertRaises(ValueError): + self.worker.prepare(rejected) + read.assert_not_called() + self.credential.get_token.assert_not_called() + def test_conflicting_reservation_does_not_replace_the_active_job(self): conflict = TableTransactionError() conflict.status_code = 409 @@ -728,13 +863,13 @@ def test_conflicting_reservation_does_not_replace_the_active_job(self): with patch.object(store, "get", side_effect=[None, None]): store.table.submit_transaction.side_effect = conflict with self.assertRaises(bridge.BusyError): - store.reserve(JOB, "wiki", b"verified source metadata") + store.reserve(JOB, "wiki", b"verified source metadata", repository=PILOT_REPOSITORY) def test_same_run_keeps_its_original_payload(self): store = bridge.JobStore(Mock()) original = {"RowKey": JOB, "state": "queued", "payload": b"original"} store.table.get_entity.return_value = original - self.assertIs(store.reserve(JOB, "wiki", b"replacement"), original) + self.assertIs(store.reserve(JOB, "wiki", b"replacement", repository=PILOT_REPOSITORY), original) store.table.submit_transaction.assert_not_called() def test_settlement_does_not_release_a_different_jobs_reservation(self): @@ -828,14 +963,20 @@ def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): "issuelens_action.py", "stream_output.py", }) source.extractall(root) - for role, expected in (("ingress", "status,submit"), ("worker", "process")): - with self.subTest(role=role): + for role, expected, policies in ( + ("ingress", "status,submit", None), ("ingress", "status,submit", POLICIES_JSON), + ("worker", "process", None), + ): + with self.subTest(role=role, policies=policies): environment = {**os.environ, "ISSUELENS_BRIDGE_ROLE": role} environment.pop("ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST", None) environment.pop("ISSUELENS_BRIDGE_REPOSITORY_ID", None) + environment.pop("ISSUELENS_BRIDGE_REPOSITORY_POLICIES", None) if role == "ingress": environment["ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST"] = ALLOWLIST_JSON environment["ISSUELENS_BRIDGE_REPOSITORY_ID"] = str(PILOT_REPOSITORY_ID) + if policies is not None: + environment["ISSUELENS_BRIDGE_REPOSITORY_POLICIES"] = policies result = subprocess.run( [sys.executable, "-c", ( "from inspect import signature\n" @@ -852,12 +993,17 @@ def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): ) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout.strip(), expected) - for value in (None, "", "{invalid"): + allowlist_setting = "ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST" + policy_setting = "ISSUELENS_BRIDGE_REPOSITORY_POLICIES" + for setting, value in ((allowlist_setting, None), (allowlist_setting, ""), (policy_setting, "{invalid")): environment = {**os.environ, "ISSUELENS_BRIDGE_ROLE": "ingress"} - environment.pop("ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST", None) + environment[allowlist_setting] = ALLOWLIST_JSON + environment.pop(policy_setting, None) environment["ISSUELENS_BRIDGE_REPOSITORY_ID"] = str(PILOT_REPOSITORY_ID) - if value is not None: - environment["ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST"] = value + if value is None: + del environment[setting] + else: + environment[setting] = value result = subprocess.run( [sys.executable, "-c", "import function_app"], cwd=root, env=environment, From 0785b23909cf9a6d38b9623d1088965fda178776 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Wed, 25 Nov 2026 15:52:17 +0800 Subject: [PATCH 3/3] Use the bridge repository allowlist for both job types Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 15 +- automation_bridge/bridge.py | 88 ++---------- automation_bridge/function_app.py | 5 +- docs/guide.md | 100 +++++-------- tests/test_automation_bridge.py | 225 ++++++++++++------------------ 5 files changed, 152 insertions(+), 281 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 5810139..97d6cdd 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -318,14 +318,13 @@ The agent is driven by a workflow in the target repo Azure Function bridge with a bridge-audience GitHub Actions token. The Function verifies GitHub identity without exchanging the token for Entra credentials. No App webhook or corporate FIC is used. - The ingress allowlist enrolls numeric repository IDs. Non-IssueLens IDs - are manual issue-loop only unless `ISSUELENS_BRIDGE_REPOSITORY_POLICIES` - configures exact repository, workflow and events for protected `main`. - Same-repository team-memory is a separate opt-in from the fixed coordinator; - source, coordinator and validated wiki destination must match. The worker - revalidates created comments using the repository stored at admission. - The settings and Java Pack example are documented in `docs/guide.md`; - the ZIP does not load an example file or enroll Java Pack in code. + The ingress allowlist enrolls numeric repository IDs for manual and + automatic issue-loop jobs from their protected default branch, and + same-repository team-memory via the fixed coordinator on protected default + `main`. Source, coordinator and validated wiki destination must match. + IssueLens keeps its stricter built-in workflow rules. The worker revalidates + created comments using the repository stored at admission. The ZIP does not + load the example allowlist or enroll Java Pack in code. 2. The worker uses its managed identity to POST the existing `{ input }` payload to the deployed agent's `/invocations` API. Bridge validation and queueing stay outside the hosted agent. The agent remains independently diff --git a/automation_bridge/bridge.py b/automation_bridge/bridge.py index 02e7356..32e33d6 100644 --- a/automation_bridge/bridge.py +++ b/automation_bridge/bridge.py @@ -9,7 +9,6 @@ import urllib.error import urllib.parse import urllib.request -from dataclasses import dataclass from pathlib import Path import jwt @@ -62,57 +61,7 @@ def load_repository_allowlist(value: str, pilot_repository_id: int) -> frozenset return frozenset(ids) -@dataclass(frozen=True) -class RepositoryPolicy: - repository: str - issue_workflow: str - issue_events: frozenset[str] - team_memory: bool - - -def load_repository_policies( - value: str | None, pilot_repository_id: int, allowlist: frozenset[int], -) -> dict[int, RepositoryPolicy]: - if value is None: - return {} - require(isinstance(value, str) and 0 < len(value.encode("utf-8")) <= 32 * 1024, - "Invalid bridge repository policy setting size") - entries = json.loads(value, object_pairs_hook=action.unique_object) - require(isinstance(entries, dict), "Expected bridge repository policies keyed by repository ID") - policies = {} - names = {PILOT_REPOSITORY.casefold()} - required = {"repository", "issue_workflow", "issue_events"} - reserved_workflows = {action.COORDINATOR_WORKFLOW.casefold(), action.DISPATCH_WORKFLOW.casefold()} - for key, entry in entries.items(): - require(re.fullmatch(r"[1-9][0-9]*", key), "Invalid bridge repository policy ID") - repository_id = int(key) - require(repository_id != pilot_repository_id and repository_id in allowlist, - "Bridge repository policy ID must be enrolled and non-IssueLens") - require(isinstance(entry, dict) and required <= set(entry) <= required | {"team_memory"}, - "Invalid bridge repository policy fields") - repository = entry["repository"] - require(isinstance(repository, str) and re.fullmatch(action.SOURCE_REPOSITORY_PATTERN, repository) - and ".." not in repository and repository.casefold() not in names, - "Invalid or ambiguous bridge repository policy name") - workflow = entry["issue_workflow"] - require(isinstance(workflow, str) and workflow.startswith(WORKFLOW_DIRECTORY) - and WORKFLOW_BASENAME.fullmatch(workflow[len(WORKFLOW_DIRECTORY):]) - and workflow.casefold() not in reserved_workflows, - "Invalid bridge issue workflow path") - events, team_memory = entry["issue_events"], entry.get("team_memory", False) - require(isinstance(events, list) and events - and all(isinstance(event, str) and event in ISSUE_EVENT_ACTIONS for event in events) - and len(set(events)) == len(events) and type(team_memory) is bool, - "Invalid bridge repository policy events or team-memory opt-in") - names.add(repository.casefold()) - policies[repository_id] = RepositoryPolicy(repository, workflow, frozenset(events), team_memory) - return policies - - -def workflow_claims( - token: str, audience: str, pilot_repository_id: int, allowlist: frozenset[int], - policies: dict[int, RepositoryPolicy], -) -> dict: +def workflow_claims(token: str, audience: str, pilot_repository_id: int, allowlist: frozenset[int]) -> dict: require(type(pilot_repository_id) is int and pilot_repository_id in allowlist, "Configured IssueLens repository ID does not match the bridge allowlist") require(len(token) <= 16 * 1024, "Invalid workflow token size") @@ -141,7 +90,6 @@ def workflow_claims( if "ref_protected" in claims: protected = claims["ref_protected"] require(protected is True or protected == "true", "Workflow ref was not protected") - policy = policies.get(repository_id) if repository_id == pilot_repository_id: if claims["workflow_ref"] == workflow_ref(".github/workflows/issue-triage.yml"): require(claims["event_name"] in ISSUE_EVENT_ACTIONS, "Unsupported workflow event") @@ -150,31 +98,26 @@ def workflow_claims( return _validated_claims(claims, "team-memory", repository_id) else: raise ValueError("Workflow is not enabled for this bridge") - elif policy is not None: - require(repository == policy.repository and claims["ref"] == f"refs/heads/{PILOT_BRANCH}", - "Workflow repository or branch does not match bridge policy") - if policy.team_memory and claims["workflow_ref"] == workflow_ref(action.COORDINATOR_WORKFLOW, repository): - require(claims["event_name"] == "workflow_dispatch", "Unsupported workflow event") - return _validated_claims(claims, "team-memory", repository_id, detailed_policy=True) - require(claims["workflow_ref"] == workflow_ref(policy.issue_workflow, repository) - and claims["event_name"] in policy.issue_events, - "Workflow is not enabled for this bridge") else: - require(not any(repository.casefold() == entry.repository.casefold() for entry in policies.values()), - "Workflow repository ID does not match bridge policy") prefix = f"{repository}/{WORKFLOW_DIRECTORY}" suffix = "@" + claims["ref"] workflow = claims["workflow_ref"] - require(claims["event_name"] == "workflow_dispatch" and isinstance(workflow, str) - and workflow.startswith(prefix) and workflow.endswith(suffix) - and WORKFLOW_BASENAME.fullmatch(workflow[len(prefix):-len(suffix)]), - "Only manual workflow dispatches from enrolled repositories are allowed") - return _validated_claims(claims, "issue-loop", repository_id, detailed_policy=policy is not None) + require(isinstance(workflow, str) and workflow.startswith(prefix) and workflow.endswith(suffix), + "Workflow repository or ref does not match the signed claims") + basename = workflow[len(prefix):-len(suffix)] + require(WORKFLOW_BASENAME.fullmatch(basename), "Invalid issue-loop workflow path") + path = WORKFLOW_DIRECTORY + basename + if path.casefold() == action.COORDINATOR_WORKFLOW.casefold(): + require(workflow == workflow_ref(action.COORDINATOR_WORKFLOW, repository) + and claims["event_name"] == "workflow_dispatch", "Unsupported team-memory workflow or event") + return _validated_claims(claims, "team-memory", repository_id) + require(claims["event_name"] in ISSUE_EVENT_ACTIONS, "Unsupported workflow event") + return _validated_claims(claims, "issue-loop", repository_id) -def _validated_claims(claims: dict, kind: str, repository_id: int, *, detailed_policy: bool = False) -> dict: +def _validated_claims(claims: dict, kind: str, repository_id: int) -> dict: return { - **claims, "kind": kind, "repository_id": repository_id, "detailed_policy": detailed_policy, + **claims, "kind": kind, "repository_id": repository_id, "run_id": action.positive(claims["run_id"]), "run_attempt": action.positive(claims["run_attempt"]), "workflow_sha": action.full_sha(claims["workflow_sha"]), } @@ -193,11 +136,10 @@ def default_branch_protected(claims: dict) -> bool: and isinstance(branch_name, str) and branch_name, "Invalid GitHub repository response") if (project["full_name"].casefold() != repository.casefold() - or (claims["detailed_policy"] and project["full_name"] != repository) or project["id"] != claims["repository_id"] or project["private"] or project["visibility"] != "public" or claims["ref"] != f"refs/heads/{branch_name}"): return False - if "ref_protected" in claims and not claims["detailed_policy"]: + if "ref_protected" in claims: return True branch_path = urllib.parse.quote(branch_name, safe="") branch = action.github_read(f"/repos/{repository}/branches/{branch_path}", token="", timeout=5) diff --git a/automation_bridge/function_app.py b/automation_bridge/function_app.py index 637cd02..bed5f0a 100644 --- a/automation_bridge/function_app.py +++ b/automation_bridge/function_app.py @@ -62,7 +62,7 @@ def authorized(request): "A workflow token is required") return bridge.workflow_claims( auth[len("Bearer "):], os.environ["ISSUELENS_BRIDGE_OIDC_AUDIENCE"], - pilot_repository_id, repository_ids, repository_policies, + pilot_repository_id, repository_ids, ) @@ -72,9 +72,6 @@ def authorized(request): repository_ids = bridge.load_repository_allowlist( os.environ.get("ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST", ""), pilot_repository_id, ) - repository_policies = bridge.load_repository_policies( - os.environ.get("ISSUELENS_BRIDGE_REPOSITORY_POLICIES"), pilot_repository_id, repository_ids, - ) @app.route(route="issuelens/v1/jobs", methods=["POST"], trigger_arg_name="request") def submit(request: func.HttpRequest) -> func.HttpResponse: diff --git a/docs/guide.md b/docs/guide.md index 3be6cef..d78d1b4 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1053,8 +1053,8 @@ routing and command validation; no new permanent agent contract is introduced. ### IssueLens Function bridge pilot -Configure repository enrollment and workflow policy through the ingress -Function app settings. Keep the GitHub App webhook unchanged. Obtain +Configure repository enrollment through the ingress Function app allowlist. +Keep the GitHub App webhook unchanged. Obtain approval for the GitHub-facing endpoint, direct trust of the GitHub Actions issuer, network access, and the Azure release path before provisioning or enabling anything. The Function validates a GitHub token addressed to itself; @@ -1065,8 +1065,8 @@ workflow revision is responsible for validating the event before submission. Build the Function source bundle from the reviewed bridge and action revision: `python -m automation_bridge.bundle `. The ZIP contains only the two Functions roles and the reused workflow helpers, with a separate dependency -manifest. A missing or invalid ingress allowlist or an invalid supplied policy -prevents ingress from initializing. Publish it through an approved release path to +manifest. A missing or invalid allowlist prevents ingress from initializing. +Publish it through an approved release path to **two** Function apps with distinct managed identities. Use a plan that supports a 40-minute function timeout for the worker. Use identity-backed Functions host storage separately from the application job table. @@ -1074,46 +1074,35 @@ from the application job table. | Target | Configuration and access | | --- | --- | | Both Function apps | `ISSUELENS_BRIDGE_TABLE_ACCOUNT` points to the account containing precreated `IssueLensBridgeJobs`. Both need Table data read/write on that table. `ISSUELENS_BRIDGE_QUEUE` and `ISSUELENS_BRIDGE_SERVICE_BUS__fullyQualifiedNamespace` identify the same dedicated Service Bus queue. Use a queue with duplicate detection; reservations remain authoritative even outside the broker window. | -| Ingress | `ISSUELENS_BRIDGE_ROLE=ingress`, `ISSUELENS_BRIDGE_REPOSITORY_ID` set to the existing IssueLens numeric GitHub repository ID (`1303440932`), `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST` set to the reviewed JSON ID array, and `ISSUELENS_BRIDGE_OIDC_AUDIENCE` set to the exact HTTPS `/api/issuelens/v1/jobs` URL on the approved `azurewebsites.net` endpoint. Use optional `ISSUELENS_BRIDGE_REPOSITORY_POLICIES` for exact workflow/event policies for enrolled non-IssueLens repositories. Grant queue **Data Sender** only. Enforce HTTPS and set `FUNCTIONS_REQUEST_BODY_SIZE_LIMIT=32768` to cap requests before they reach Python. | +| Ingress | `ISSUELENS_BRIDGE_ROLE=ingress`, `ISSUELENS_BRIDGE_REPOSITORY_ID` set to the existing IssueLens numeric GitHub repository ID (`1303440932`), `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST` set to the reviewed JSON ID array, and `ISSUELENS_BRIDGE_OIDC_AUDIENCE` set to the exact HTTPS `/api/issuelens/v1/jobs` URL on the approved `azurewebsites.net` endpoint. Grant queue **Data Sender** only. Enforce HTTPS and set `FUNCTIONS_REQUEST_BODY_SIZE_LIMIT=32768` to cap requests before they reach Python. | | Worker | `ISSUELENS_BRIDGE_ROLE=worker`, `ISSUELENS_BRIDGE_FOUNDRY_URL` set to the existing deployed agent's full invocations URL (including API version). Grant queue **Data Receiver** and the narrowest applicable Foundry invocation access to the worker managed identity. It requests an Entra token for `https://ai.azure.com/.default`. No repository write, deployment, signing key, or GitHub App key access is needed. | -The bridge verifies the signed workflow identity, public GitHub-hosted runner -scope, and current public repository/default branch before admission. If a -signed `ref_protected` claim is supplied it must affirm protection. For a -detailed policy, or if that claim is absent, ingress must independently -confirm current protection through GitHub's public branch API. Unprotected -branches and unavailable checks stop admission. Status polls still require -the owning run's signed identity under the active policy; they do not repeat -the branch API check. +The bridge verifies the signed workflow identity and GitHub-hosted runner, +and confirms the public repository and current default branch through GitHub +metadata before admission. A supplied `ref_protected` claim must affirm +protection. If it is absent, ingress must confirm protection through GitHub's +public branch API. Unprotected branches and unavailable checks stop admission. +Status polls require the owning run's signed identity; they do not repeat the +branch API check. Use `automation_bridge/repository_allowlist.example.json` as the initial `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST` value: a JSON array of numeric GitHub repository IDs. The existing `ISSUELENS_BRIDGE_REPOSITORY_ID` setting must remain in that array and continues to identify IssueLens. The setting is -limited to 32 KiB; IDs must be positive, unique integers. An enrolled -non-IssueLens ID without a detailed policy can submit only manual -`workflow_dispatch` issue-loop jobs from a workflow on its protected default -branch. ID enrollment alone does not admit automatic events or team-memory. -IssueLens keeps its built-in workflow and event restrictions. - -`ISSUELENS_BRIDGE_REPOSITORY_POLICIES` is an optional JSON object (up to 32 KiB) -keyed by enrolled non-IssueLens repository IDs as decimal strings without -leading zeroes. Omit it or use `{}` for ID-only enrollment. Each entry requires -an exact canonical `repository` (`owner/repository`), `issue_workflow` (a -single `.github/workflows/` YAML file, distinct from the team-memory workflows), -and a nonempty, unique `issue_events` array drawn from `issues`, `issue_comment`, -and `workflow_dispatch`. `team_memory` is an optional JSON boolean, off unless -explicitly `true`. Invalid JSON, unknown fields, duplicate keys or canonical -names (including case variants), and entries for unenrolled or IssueLens IDs -fail closed. For a detailed entry, the exact ID, repository spelling, workflow -and event must match. There is no fallback to ID-only admission on mismatch. -The supported policy contract requires `main` to be the repository's protected -default branch. Issue action and human-comment restrictions are unchanged. - -Team-memory opt-in admits only `workflow_dispatch` from the exact -`.github/workflows/team-memory-coordinator.yml` workflow. Coordinated push -ranges must identify `.github/workflows/team-memory-post-merge.yml` in the -same repository. Coordinator, source and validated wiki destination must all +limited to 32 KiB; IDs must be positive, unique integers. **Enrolling a public +repository grants bridge admission for both issue-loop and same-repository +team-memory jobs.** There is no additional setting or per-workflow enrollment. +Issue-loop jobs may come from any `.github/workflows/` YAML file in the signed +repository on its protected default branch, for `issues`, `issue_comment`, +or `workflow_dispatch`. The same issue action and human-comment restrictions +apply. IssueLens keeps its built-in workflow and event restrictions. + +The standard coordinator is never an issue-loop caller. Team-memory admission +requires `workflow_dispatch` from the exact +`.github/workflows/team-memory-coordinator.yml` workflow on protected default +`main`. Coordinated push ranges must identify +`.github/workflows/team-memory-post-merge.yml` in the same repository. +Coordinator, source and validated wiki destination must all match the authenticated repository. Manual PR and coordinated range requests share that repository's wiki reservation, separate from other repositories. Source run metadata cannot prove the original push boundary or flags. Each @@ -1123,32 +1112,19 @@ permissions or guarantee publication. Restrict permission to modify Function App settings to authorized operators: the allowlist controls admission and must never come from workflow or dispatch -inputs. Review each repository's public identity, default branch protection, -workflow code, and App permissions before adding an ID or expanding its policy. -Azure applies app setting changes by restarting the Function App. Policy -changes can prevent affected runs from continuing to poll their receipts; -reconcile in-flight jobs first. Removing a detailed policy retains ID-only -manual issue-loop admission; remove both the entry and the ID to revoke -enrollment. Configuration and release require separate approval. - -For Java Pack, retain `ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST=[1303440932,104967329]` -and set this value for `ISSUELENS_BRIDGE_REPOSITORY_POLICIES` on ingress: - -```json -{ - "104967329": { - "repository": "microsoft/vscode-java-pack", - "issue_workflow": ".github/workflows/issueLens-run.yml", - "issue_events": ["issues", "issue_comment", "workflow_dispatch"], - "team_memory": true - } -} -``` - +inputs. Review each enrolled repository's public identity, default branch +protection, workflow code, and App permissions before releasing the expanded +admission. Azure applies app setting changes by restarting the Function App. +Removing an ID revokes admission and receipt polling for that repository; +reconcile in-flight jobs first. Configuration and release require separate +approval. + +For Java Pack, the existing +`ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST=[1303440932,104967329]` is sufficient. Keep the Java Pack workflows disabled during rollout. After approval, deploy -the same ZIP built from the merged IssueLens revision to worker first and -then ingress, and confirm ingress has the reviewed policy before enabling -the merged caller workflows. Provide +the same ZIP built from the merged IssueLens revision to the worker first, +then ingress. Confirm both roles are ready before enabling the merged caller +workflows. Provide the approved `ISSUELENS_BRIDGE_URL` Actions secret, and use the composite action with `request-type: issue-loop`, `transport: bridge`, `issue-number`, and `bridge-url`. The issue-loop job needs `issues: read` and diff --git a/tests/test_automation_bridge.py b/tests/test_automation_bridge.py index a5454e8..44834a3 100644 --- a/tests/test_automation_bridge.py +++ b/tests/test_automation_bridge.py @@ -39,14 +39,6 @@ COMMENT_URL = f"https://api.github.com/repos/{PILOT_REPOSITORY}/issues/comments/41" ALLOWLIST_JSON = pathlib.Path(bridge.__file__).with_name("repository_allowlist.example.json").read_text(encoding="utf-8") EXTENDED_ALLOWLIST = json.dumps([*json.loads(ALLOWLIST_JSON), OTHER_REPOSITORY_ID]) -JAVA_POLICY = { - "repository": JAVA_REPOSITORY, "issue_workflow": JAVA_WORKFLOW, - "issue_events": ["issues", "issue_comment", "workflow_dispatch"], "team_memory": True, -} -OTHER_POLICY = { - "repository": OTHER_REPOSITORY, "issue_workflow": OTHER_WORKFLOW, "issue_events": ["issue_comment"], -} -POLICIES_JSON = json.dumps({JAVA_REPOSITORY_ID: JAVA_POLICY}) def issue_metadata(**overrides): @@ -105,22 +97,16 @@ def setUp(self): def token(self, **overrides): return jwt.encode(self.claims | overrides, self.key, algorithm="RS256") - def workflow_claims(self, token, audience, repository_id, *, allowlist_json=ALLOWLIST_JSON, - policies_json=POLICIES_JSON): + def workflow_claims(self, token, audience, repository_id, *, allowlist_json=ALLOWLIST_JSON): allowlist = bridge.load_repository_allowlist(allowlist_json, PILOT_REPOSITORY_ID) - policies = bridge.load_repository_policies(policies_json, PILOT_REPOSITORY_ID, allowlist) - return bridge.workflow_claims(token, audience, repository_id, allowlist, policies) + return bridge.workflow_claims(token, audience, repository_id, allowlist) - def load_ingress(self, allowlist=ALLOWLIST_JSON, policies=POLICIES_JSON, pilot_id=PILOT_REPOSITORY_ID): + def load_ingress(self, allowlist=ALLOWLIST_JSON, pilot_id=PILOT_REPOSITORY_ID): self.enterContext(patch.dict(os.environ, { "ISSUELENS_BRIDGE_ROLE": "ingress", "ISSUELENS_BRIDGE_REPOSITORY_ID": str(pilot_id), "ISSUELENS_BRIDGE_OIDC_AUDIENCE": URL, "ISSUELENS_BRIDGE_QUEUE": "test-jobs", "ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST": allowlist, })) - if policies is None: - os.environ.pop("ISSUELENS_BRIDGE_REPOSITORY_POLICIES", None) - else: - os.environ["ISSUELENS_BRIDGE_REPOSITORY_POLICIES"] = policies path = pathlib.Path(bridge.__file__).with_name("function_app.py") spec = importlib.util.spec_from_file_location("test_bridge_ingress", path) assert spec is not None and spec.loader is not None @@ -162,7 +148,7 @@ def test_pilot_case_only_repository_rename_is_rejected(self): with self.assertRaisesRegex(ValueError, "Workflow is not in the IssueLens pilot scope"): self.workflow_claims(renamed, URL, PILOT_REPOSITORY_ID) - def test_java_pack_admission_is_limited_to_its_reviewed_workflow(self): + def test_java_pack_issue_loop_is_bound_to_the_signed_repository_and_event(self): accepted = self.workflow_claims(self.java_token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) self.assertEqual(bridge.validate_request(self.java_payload(), accepted), "repo-104967329-issue-12") for event in ("issues", "issue_comment", "workflow_dispatch"): @@ -175,7 +161,7 @@ def test_java_pack_admission_is_limited_to_its_reviewed_workflow(self): {"runner_environment": "self-hosted"}, {"event_name": "push"}, {"repository": "microsoft/VSCode-java-pack"}, {"ref": "refs/heads/other"}, {"workflow_ref": bridge.workflow_ref(ISSUE_WORKFLOW)}, - {"workflow_ref": bridge.workflow_ref(".github/workflows/another-triage.yaml", JAVA_REPOSITORY)}, + {"workflow_ref": bridge.workflow_ref(".github/workflows/nested/triage.yaml", JAVA_REPOSITORY)}, {"aud": ENDPOINT}, ): with self.subTest(overrides=overrides), self.assertRaises((ValueError, jwt.PyJWTError)): @@ -195,79 +181,88 @@ def test_java_pack_admission_is_limited_to_its_reviewed_workflow(self): self.assertNotEqual(bridge.job_id(pilot), bridge.job_id(accepted)) self.assertEqual(bridge.job_id(accepted), bridge.job_id(accepted | {"run_attempt": 2})) - def test_ingress_rejects_inconsistent_issuelens_id_or_unenrolled_policy_at_startup(self): + def test_ingress_rejects_an_allowlist_missing_its_configured_issuelens_id(self): for settings in ( - {"pilot_id": JAVA_REPOSITORY_ID}, {"pilot_id": OTHER_REPOSITORY_ID}, - {"allowlist": json.dumps([PILOT_REPOSITORY_ID])}, + {"allowlist": json.dumps([JAVA_REPOSITORY_ID])}, ): with self.subTest(settings=settings), self.assertRaises(ValueError): self.load_ingress(**settings) - def test_id_only_enrollment_keeps_the_legacy_manual_contract(self): - ref = "refs/heads/trunk" - workflow = bridge.workflow_ref(".github/workflows/any-manual.yaml", JAVA_REPOSITORY, "trunk") - for config in (None, json.dumps({OTHER_REPOSITORY_ID: OTHER_POLICY})): - def authenticate(**overrides): - token = self.java_token(**({"ref": ref, "workflow_ref": workflow} | overrides)) - return self.workflow_claims( - token, URL, PILOT_REPOSITORY_ID, allowlist_json=EXTENDED_ALLOWLIST, policies_json=config, + def test_enrolled_repository_can_submit_manual_and_automatic_jobs_on_protected_trunk(self): + ingress, submit, _ = self.load_ingress(EXTENDED_ALLOWLIST) + repository = {"full_name": OTHER_REPOSITORY, "id": OTHER_REPOSITORY_ID, + "default_branch": "trunk", "private": False, "visibility": "public"} + claims = {"repository": OTHER_REPOSITORY, "repository_id": str(OTHER_REPOSITORY_ID), + "ref": "refs/heads/trunk", + "workflow_ref": bridge.workflow_ref(OTHER_WORKFLOW, OTHER_REPOSITORY, "trunk")} + opened = issue_metadata(repository=OTHER_REPOSITORY, event_name="issues", event_action="opened", + comment_id=None, comment_author_login=None, comment_author_association=None, + comment_added=False) + opened.pop("comment_sha256") + for event, payload in ( + ("workflow_dispatch", self.java_payload(repository=OTHER_REPOSITORY)), + ("issues", {"request_type": "issue-loop", "metadata": opened}), + ("issue_comment", issue_payload(repository=OTHER_REPOSITORY)), + ): + token = self.token(**claims, event_name=event) + with ( + self.subTest(event=event), + patch.object(bridge.action, "github_read", side_effect=[ + repository, {"name": "trunk", "protected": True}, + ]) as github, + patch.object(ingress, "jobs") as jobs, + patch.object(ingress, "service_bus"), + ): + jobs.return_value.reserve.return_value = {"RowKey": JOB, "state": bridge.QUEUED} + request = self.request(token=token, payload=payload) + response = submit(request) + self.assertEqual(response.status_code, 202, response.get_body()) + job_claims = self.workflow_claims(token, URL, PILOT_REPOSITORY_ID, allowlist_json=EXTENDED_ALLOWLIST) + jobs.return_value.reserve.assert_called_once_with( + bridge.job_id(job_claims), f"repo-{OTHER_REPOSITORY_ID}-issue-12", request.get_body(), + repository=OTHER_REPOSITORY, ) - - with self.subTest(config=config): - claims = authenticate() - self.assertEqual(bridge.validate_request(self.java_payload(), claims), "repo-104967329-issue-12") - for event in ("issues", "issue_comment", "push"): - with self.assertRaises(ValueError): - authenticate(event_name=event) - coordinator = authenticate(workflow_ref=bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY, "trunk")) - self.assertEqual(coordinator["kind"], "issue-loop") - with self.assertRaises(ValueError): - bridge.validate_request({"request_type": "team-memory", "metadata": {}}, coordinator) + github.assert_called_with(f"/repos/{OTHER_REPOSITORY}/branches/trunk", token="", timeout=5) with self.assertRaises(ValueError): - self.workflow_claims(self.java_token(), URL, PILOT_REPOSITORY_ID, - allowlist_json=json.dumps([PILOT_REPOSITORY_ID]), policies_json=None) + self.workflow_claims(self.token(**claims), URL, PILOT_REPOSITORY_ID) - def test_detailed_policy_scopes_events_and_team_memory_per_repository(self): - def authenticate(*, policy=OTHER_POLICY, **overrides): - configured = json.dumps({JAVA_REPOSITORY_ID: JAVA_POLICY, OTHER_REPOSITORY_ID: policy}) + def test_enrolled_repository_coordinator_is_same_repo_wiki_only_and_requires_main(self): + def authenticate(**overrides): claims = { "repository": OTHER_REPOSITORY, "repository_id": str(OTHER_REPOSITORY_ID), - "workflow_ref": bridge.workflow_ref(OTHER_WORKFLOW, OTHER_REPOSITORY), + "workflow_ref": bridge.workflow_ref(MEMORY_WORKFLOW, OTHER_REPOSITORY), + "event_name": "workflow_dispatch", } | overrides return self.workflow_claims(self.token(**claims), URL, PILOT_REPOSITORY_ID, - allowlist_json=EXTENDED_ALLOWLIST, policies_json=configured) - - claims = authenticate() - payload = issue_payload(repository=OTHER_REPOSITORY) - self.assertEqual(bridge.validate_request(payload, claims), f"repo-{OTHER_REPOSITORY_ID}-issue-12") - java = self.workflow_claims(self.java_token(event_name="issue_comment"), URL, PILOT_REPOSITORY_ID) - self.assertNotEqual(bridge.job_id(java), bridge.job_id(claims)) - coordinator = {"workflow_ref": bridge.workflow_ref(MEMORY_WORKFLOW, OTHER_REPOSITORY), - "event_name": "workflow_dispatch"} - for mismatch in ( - {"event_name": "issues"}, {"event_name": "workflow_dispatch"}, coordinator, - {"repository": JAVA_REPOSITORY}, {"repository_id": str(JAVA_REPOSITORY_ID)}, - {"repository": OTHER_REPOSITORY.lower()}, {"ref": "refs/heads/trunk"}, - {"workflow_ref": bridge.workflow_ref(OTHER_WORKFLOW.lower(), OTHER_REPOSITORY.lower())}, - {"workflow_ref": bridge.workflow_ref(JAVA_WORKFLOW, OTHER_REPOSITORY)}, - ): - with self.subTest(mismatch=mismatch), self.assertRaises(ValueError): - authenticate(**mismatch) - memory = authenticate(policy=OTHER_POLICY | {"team_memory": True}, **coordinator) + allowlist_json=EXTENDED_ALLOWLIST) + + memory = authenticate() + issue = authenticate(workflow_ref=bridge.workflow_ref(OTHER_WORKFLOW, OTHER_REPOSITORY)) + java = self.workflow_claims( + self.java_token(workflow_ref=bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY)), + URL, PILOT_REPOSITORY_ID, + ) wiki_payload = manual_memory_payload(memory) self.assertEqual(bridge.validate_request(wiki_payload, memory), f"repo-{OTHER_REPOSITORY_ID}-wiki") - self.assertNotEqual(bridge.job_id(memory), bridge.job_id(claims)) + self.assertNotEqual(bridge.job_id(memory), bridge.job_id(issue)) + self.assertNotEqual(bridge.job_id(memory), bridge.job_id(java)) + with self.assertRaises(ValueError): + bridge.validate_request(wiki_payload, issue) + with self.assertRaises(ValueError): + bridge.validate_request(self.java_payload(repository=OTHER_REPOSITORY), memory) wiki_payload["metadata"]["required_wiki_repository"] = JAVA_REPOSITORY with self.assertRaises(ValueError): bridge.validate_request(wiki_payload, memory) - with self.assertRaises(ValueError): - authenticate(policy=OTHER_POLICY | {"team_memory": True}, **(coordinator | {"event_name": "push"})) - - def test_detailed_policy_name_cannot_fall_back_to_an_id_only_enrollment(self): - misleading_token = self.java_token(repository_id=str(OTHER_REPOSITORY_ID)) - with self.assertRaisesRegex(ValueError, "repository ID does not match"): - self.workflow_claims(misleading_token, URL, PILOT_REPOSITORY_ID, allowlist_json=EXTENDED_ALLOWLIST) + for mismatch in ( + {"event_name": "issues"}, {"event_name": "issue_comment"}, {"event_name": "push"}, + {"ref": "refs/heads/trunk", "workflow_ref": bridge.workflow_ref(MEMORY_WORKFLOW, OTHER_REPOSITORY, "trunk")}, + {"workflow_ref": bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY)}, + {"workflow_ref": bridge.workflow_ref(".github/workflows/TEAM-MEMORY-COORDINATOR.yml", OTHER_REPOSITORY)}, + {"ref_protected": "false"}, {"repository_id": str(PILOT_REPOSITORY_ID)}, + ): + with self.subTest(mismatch=mismatch), self.assertRaises(ValueError): + authenticate(**mismatch) def test_java_pack_event_actions_follow_existing_issue_rules(self): for event, operation in (("issues", "opened"), ("issues", "reopened"), @@ -339,11 +334,10 @@ def test_packaged_java_coordinator_manual_and_push_contract(self): packaged = importlib.util.module_from_spec(spec) spec.loader.exec_module(packaged) allowlist = packaged.load_repository_allowlist(ALLOWLIST_JSON, PILOT_REPOSITORY_ID) - policies = packaged.load_repository_policies(POLICIES_JSON, PILOT_REPOSITORY_ID, allowlist) with patch.object(packaged.KEYS, "get_signing_key_from_jwt", return_value=Mock(key=self.key.public_key())): claims = packaged.workflow_claims( self.java_token(workflow_ref=coordinator_ref, ref_protected="true"), - URL, PILOT_REPOSITORY_ID, allowlist, policies, + URL, PILOT_REPOSITORY_ID, allowlist, ) self.assertEqual(claims["kind"], "team-memory") for overrides in ( @@ -353,7 +347,7 @@ def test_packaged_java_coordinator_manual_and_push_contract(self): ): with self.subTest(claims=overrides), self.assertRaises((ValueError, jwt.PyJWTError)): packaged.workflow_claims(self.java_token(**({"workflow_ref": coordinator_ref} | overrides)), - URL, PILOT_REPOSITORY_ID, allowlist, policies) + URL, PILOT_REPOSITORY_ID, allowlist) worker = packaged.FoundryWorker(ENDPOINT, Mock(get_token=Mock(return_value=Mock(token="token")))) for wrong_run in ( source_run | {"repository": project | {"id": PILOT_REPOSITORY_ID}}, @@ -437,9 +431,9 @@ def test_java_memory_receipt_is_owned_by_the_coordinator_run(self): ) self.assertEqual(status(self.request(identifier, token=different_run)).status_code, 404) - def test_detailed_policy_requires_current_canonical_repository_and_branch_protection(self): + def test_enrolled_repo_submit_requires_public_repo_identity_and_current_protected_default(self): ingress, submit, status = self.load_ingress() - token = self.java_token(ref_protected="true") + token = self.java_token() claims = self.workflow_claims(token, URL, PILOT_REPOSITORY_ID) identifier = bridge.job_id(claims) repository_info = { @@ -471,13 +465,17 @@ def test_detailed_policy_requires_current_canonical_repository_and_branch_protec ): self.assertEqual(submit(self.request(token=token, payload=self.java_payload())).status_code, 401) jobs.assert_not_called() - with ( - patch.object(bridge.action, "github_read", - return_value=repository_info | {"full_name": "microsoft/VSCode-java-pack"}), - patch.object(ingress, "jobs") as jobs, + for mismatch in ( + {"full_name": OTHER_REPOSITORY}, {"id": OTHER_REPOSITORY_ID}, {"private": True}, + {"visibility": "internal"}, {"default_branch": "trunk"}, ): - self.assertEqual(submit(self.request(token=token, payload=self.java_payload())).status_code, 401) - jobs.assert_not_called() + with ( + self.subTest(mismatch=mismatch), + patch.object(bridge.action, "github_read", return_value=repository_info | mismatch), + patch.object(ingress, "jobs") as jobs, + ): + self.assertEqual(submit(self.request(token=token, payload=self.java_payload())).status_code, 401) + jobs.assert_not_called() def test_java_pack_action_preflight_produces_an_admissible_manual_job(self): project = {"full_name": JAVA_REPOSITORY, "id": JAVA_REPOSITORY_ID, "default_branch": "main"} @@ -516,7 +514,6 @@ def test_packaged_action_and_bridge_handle_java_issue_and_comment_events(self): packaged = importlib.util.module_from_spec(spec) spec.loader.exec_module(packaged) allowlist = packaged.load_repository_allowlist(ALLOWLIST_JSON, PILOT_REPOSITORY_ID) - policies = packaged.load_repository_policies(POLICIES_JSON, PILOT_REPOSITORY_ID, allowlist) worker = packaged.FoundryWorker(ENDPOINT, Mock(get_token=Mock(return_value=Mock(token="token")))) for event_name, event in ( ("issues", {"action": "opened", "issue": {"number": 12}, @@ -535,7 +532,7 @@ def test_packaged_action_and_bridge_handle_java_issue_and_comment_events(self): envelope = packaged.action.prepare_issue_loop(JAVA_REPOSITORY, event) claims = packaged.workflow_claims( self.java_token(event_name=event_name, ref_protected="true"), - URL, PILOT_REPOSITORY_ID, allowlist, policies, + URL, PILOT_REPOSITORY_ID, allowlist, ) payload = {"request_type": "issue-loop", "metadata": envelope["metadata"]} self.assertEqual(packaged.validate_request(payload, claims), "repo-104967329-issue-12") @@ -666,36 +663,6 @@ def test_invalid_id_allowlist_is_rejected_as_a_whole(self): with self.subTest(label=label), self.assertRaises(ValueError): bridge.load_repository_allowlist(content, PILOT_REPOSITORY_ID) - def test_malformed_or_ambiguous_repository_policies_fail_closed(self): - allowlist = bridge.load_repository_allowlist(EXTENDED_ALLOWLIST, PILOT_REPOSITORY_ID) - other_id = str(OTHER_REPOSITORY_ID) - with_duplicate_id = f"{{{json.dumps(other_id)}: {json.dumps(OTHER_POLICY)}, {json.dumps(other_id)}: null}}" - invalid = { - "empty string": "", - "invalid JSON": "{", - "oversize": " " * (32 * 1024 + 1), - "array instead of object": "[]", - "duplicate ID": with_duplicate_id, - "non-canonical ID": json.dumps({"0" + other_id: OTHER_POLICY}), - "unenrolled ID": json.dumps({42: OTHER_POLICY}), - "IssueLens ID": json.dumps({PILOT_REPOSITORY_ID: OTHER_POLICY}), - "IssueLens name": json.dumps({other_id: OTHER_POLICY | {"repository": PILOT_REPOSITORY.lower()}}), - "duplicate name": json.dumps({ - JAVA_REPOSITORY_ID: JAVA_POLICY, other_id: OTHER_POLICY | {"repository": JAVA_REPOSITORY.upper()}, - }), - } - for field_override in ( - {"repo": OTHER_REPOSITORY}, {"repository": "https://github.com/example/repo"}, - {"issue_workflow": ".github/workflows/subdir/issue.yml"}, - {"issue_workflow": MEMORY_WORKFLOW}, {"issue_workflow": bridge.action.DISPATCH_WORKFLOW}, - {"issue_events": ["pull_request"]}, {"issue_events": ["issue_comment", "issue_comment"]}, - {"issue_events": []}, {"issue_events": [None]}, {"team_memory": "true"}, - ): - invalid[str(field_override)] = json.dumps({other_id: OTHER_POLICY | field_override}) - for label, content in invalid.items(): - with self.subTest(label=label), self.assertRaises(ValueError): - bridge.load_repository_policies(content, PILOT_REPOSITORY_ID, allowlist) - class BridgeActionTests(unittest.TestCase): def test_workflow_token_uses_the_bridge_audience_and_a_github_origin(self): @@ -963,20 +930,14 @@ def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): "issuelens_action.py", "stream_output.py", }) source.extractall(root) - for role, expected, policies in ( - ("ingress", "status,submit", None), ("ingress", "status,submit", POLICIES_JSON), - ("worker", "process", None), - ): - with self.subTest(role=role, policies=policies): + for role, expected in (("ingress", "status,submit"), ("worker", "process")): + with self.subTest(role=role): environment = {**os.environ, "ISSUELENS_BRIDGE_ROLE": role} environment.pop("ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST", None) environment.pop("ISSUELENS_BRIDGE_REPOSITORY_ID", None) - environment.pop("ISSUELENS_BRIDGE_REPOSITORY_POLICIES", None) if role == "ingress": - environment["ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST"] = ALLOWLIST_JSON + environment["ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST"] = EXTENDED_ALLOWLIST environment["ISSUELENS_BRIDGE_REPOSITORY_ID"] = str(PILOT_REPOSITORY_ID) - if policies is not None: - environment["ISSUELENS_BRIDGE_REPOSITORY_POLICIES"] = policies result = subprocess.run( [sys.executable, "-c", ( "from inspect import signature\n" @@ -994,16 +955,12 @@ def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout.strip(), expected) allowlist_setting = "ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST" - policy_setting = "ISSUELENS_BRIDGE_REPOSITORY_POLICIES" - for setting, value in ((allowlist_setting, None), (allowlist_setting, ""), (policy_setting, "{invalid")): + for value in (None, "", "{invalid"): environment = {**os.environ, "ISSUELENS_BRIDGE_ROLE": "ingress"} - environment[allowlist_setting] = ALLOWLIST_JSON - environment.pop(policy_setting, None) + environment.pop(allowlist_setting, None) environment["ISSUELENS_BRIDGE_REPOSITORY_ID"] = str(PILOT_REPOSITORY_ID) - if value is None: - del environment[setting] - else: - environment[setting] = value + if value is not None: + environment[allowlist_setting] = value result = subprocess.run( [sys.executable, "-c", "import function_app"], cwd=root, env=environment,