From 5ff81172e2301fc4c21ceec08639f78d53f15de8 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Wed, 25 Nov 2026 09:55:34 +0800 Subject: [PATCH 1/3] Add reviewed bridge repository allowlist Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/issuelens/README.md | 5 +- .github/copilot-instructions.md | 4 + automation_bridge/bridge.py | 80 ++++++--- automation_bridge/bundle.py | 1 + automation_bridge/function_app.py | 2 +- automation_bridge/repository_allowlist.json | 26 +++ docs/guide.md | 39 +++- tests/test_automation_bridge.py | 190 ++++++++++++++++++-- tests/test_team_memory_coordinator.py | 2 +- 9 files changed, 305 insertions(+), 44 deletions(-) create mode 100644 automation_bridge/repository_allowlist.json diff --git a/.github/actions/issuelens/README.md b/.github/actions/issuelens/README.md index f797a3f..60e77de 100644 --- a/.github/actions/issuelens/README.md +++ b/.github/actions/issuelens/README.md @@ -22,7 +22,8 @@ and result validation. No inline Python, pip installation, container build, or GitHub App private key is required. The [Function bridge pilot](../../../docs/guide.md#issuelens-function-bridge-pilot) -uses GitHub workflow identity for `microsoft/IssueLens` only. It submits typed +uses GitHub workflow identity for the reviewed `microsoft/IssueLens` workflows +and the manual-only `microsoft/vscode-java-pack` issue-loop pilot. It submits typed metadata after the same preflight, skips Azure login, and polls the job receipt. The worker authenticates to the existing `/invocations` endpoint using managed identity and submits the normal `{ "input": "..." }` request. @@ -375,7 +376,7 @@ identity check is not authorization for any additional repositories named by a t | `source-run-id` | For coordinated automatic `team-memory` | Positive source push run ID. | | `source-run-attempt` | With `source-run-id` | Positive originating run attempt. | | `push-before`, `push-after` | With `source-run-id` | Full nonzero requested ancestor/source-run-head SHAs. Supply all four run/range inputs, never with `pull-request-number`. Before is not an attested original event boundary. | -| `transport` | No | `foundry` (default for existing callers) or `bridge` (IssueLens pilot only). | +| `transport` | No | `foundry` (default for existing callers) or `bridge` (reviewed pilot workflows only). | | `bridge-url` | For `bridge` | Complete approved HTTPS Azure Function jobs endpoint. Pass it from the `ISSUELENS_BRIDGE_URL` Actions secret, not a configuration variable. | | `azure-client-id` | For `foundry` | Existing Azure OIDC identity's client ID. | | `azure-tenant-id` | For `foundry` | Tenant used by Azure login. | diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index a28d77f..e66203a 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -318,6 +318,10 @@ 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 `automation_bridge/repository_allowlist.json` + additionally admits only manual issue-loop dispatch from + `microsoft/vscode-java-pack` at its exact workflow on protected `main`; + it grants no Java Pack automatic events or team-memory. 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 5eae5ef..effe613 100644 --- a/automation_bridge/bridge.py +++ b/automation_bridge/bridge.py @@ -27,13 +27,6 @@ PILOT_REPOSITORY = action.COORDINATOR_REPOSITORY PILOT_BRANCH = "main" -BRANCH = f"refs/heads/{PILOT_BRANCH}" -ISSUE_WORKFLOW = ".github/workflows/issue-triage.yml" -MEMORY_WORKFLOW = action.COORDINATOR_WORKFLOW -WORKFLOWS = { - ISSUE_WORKFLOW: ("issue-loop", {"issues", "issue_comment", "workflow_dispatch"}), - MEMORY_WORKFLOW: ("team-memory", {"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}") @@ -49,7 +42,47 @@ class BusyError(Exception): """A different job still owns the target reservation.""" +def load_repository_allowlist(path: Path) -> dict: + policies = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=action.unique_object) + require(isinstance(policies, dict) and PILOT_REPOSITORY in policies, "Missing IssueLens allowlist entry") + ids = set() + names = set() + for repository, policy in policies.items(): + require(re.fullmatch(r"[A-Za-z0-9-]+/[A-Za-z0-9_.-]+", repository) + and repository.casefold() not in names + and isinstance(policy, dict) and set(policy) == {"id", "branch", "workflows"} + and type(policy["id"]) is int and policy["id"] > 0 and policy["id"] not in ids + and isinstance(policy["branch"], str) + and re.fullmatch(r"[A-Za-z0-9_-]+", policy["branch"]) + and isinstance(policy["workflows"], dict) and policy["workflows"], + "Invalid bridge repository allowlist") + require(repository != PILOT_REPOSITORY or policy["branch"] == PILOT_BRANCH, + "IssueLens must retain its existing bridge branch") + ids.add(policy["id"]) + names.add(repository.casefold()) + for path, workflow in policy["workflows"].items(): + require(re.fullmatch(r"\.github/workflows/[A-Za-z0-9_.-]+\.ya?ml", path) + and isinstance(workflow, dict) and set(workflow) == {"kind", "events"} + and workflow["kind"] in ("issue-loop", "team-memory") + and isinstance(workflow["events"], list) and workflow["events"] + and all(isinstance(event, str) for event in workflow["events"]), + "Invalid bridge workflow allowlist") + events = set(workflow["events"]) + allowed_events = {"workflow_dispatch"} + if repository == PILOT_REPOSITORY and workflow["kind"] == "issue-loop": + allowed_events.update({"issues", "issue_comment"}) + require(len(events) == len(workflow["events"]) and events <= allowed_events + and (repository == PILOT_REPOSITORY or workflow["kind"] == "issue-loop"), + "Invalid bridge workflow scope") + return policies + + +_REPOSITORY_ALLOWLIST = load_repository_allowlist(Path(__file__).with_name("repository_allowlist.json")) + + def workflow_claims(token: str, audience: str, repository_id: int) -> dict: + require(type(repository_id) is int and repository_id == _REPOSITORY_ALLOWLIST[PILOT_REPOSITORY]["id"], + "Configured IssueLens repository ID does not match the bridge allowlist") require(len(token) <= 16 * 1024, "Invalid workflow token size") key = KEYS.get_signing_key_from_jwt(token) claims = jwt.decode( @@ -59,33 +92,37 @@ def workflow_claims(token: str, audience: str, repository_id: int) -> dict: "ref", "workflow_ref", "workflow_sha", "event_name", "run_id", "run_attempt", "actor", ], "strict_aud": True}, ) - require(claims["repository"] == PILOT_REPOSITORY - and claims["repository_id"] == str(repository_id) + require(isinstance(claims["repository"], str), "Invalid workflow repository") + policy = _REPOSITORY_ALLOWLIST.get(claims["repository"]) + require(policy is not None + and claims["repository_id"] == str(policy["id"]) and claims["repository_visibility"] == "public" - and claims["ref"] == BRANCH + and claims["ref"] == f"refs/heads/{policy['branch']}" and claims.get("runner_environment") == "github-hosted", "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") - for path, (kind, events) in WORKFLOWS.items(): - if claims["workflow_ref"] == workflow_ref(path): - require(claims["event_name"] in events, "Unsupported workflow event") + for path, workflow in policy["workflows"].items(): + if claims["workflow_ref"] == workflow_ref(path, claims["repository"], policy["branch"]): + require(claims["event_name"] in workflow["events"], "Unsupported workflow event") return { - **claims, "kind": kind, "repository_id": repository_id, + **claims, "kind": workflow["kind"], "repository_id": policy["id"], "run_id": action.positive(claims["run_id"]), "run_attempt": action.positive(claims["run_attempt"]), "workflow_sha": action.full_sha(claims["workflow_sha"]), } raise ValueError("Workflow is not enabled for this bridge") -def workflow_ref(path: str) -> str: - return f"{PILOT_REPOSITORY}/{path}@{BRANCH}" +def workflow_ref(path: str, repository: str = PILOT_REPOSITORY, branch: str = PILOT_BRANCH) -> str: + return f"{repository}/{path}@refs/heads/{branch}" -def pilot_branch_protected() -> bool: - branch = action.github_read(f"/repos/{PILOT_REPOSITORY}/branches/{PILOT_BRANCH}", token="", timeout=5) - require(branch.get("name") == PILOT_BRANCH and isinstance(branch.get("protected"), bool), +def pilot_branch_protected(claims: dict) -> bool: + repository = claims["repository"] + branch_name = claims["ref"].removeprefix("refs/heads/") + branch = action.github_read(f"/repos/{repository}/branches/{branch_name}", token="", timeout=5) + require(branch.get("name") == branch_name and isinstance(branch.get("protected"), bool), "Invalid GitHub branch protection response") return branch["protected"] @@ -213,9 +250,10 @@ def _memory_job(metadata: dict, claims: dict) -> str: def validate_request(data: dict, claims: dict) -> str: require(isinstance(data, dict) and set(data) == {"request_type", "metadata"} and data["request_type"] == claims["kind"] and isinstance(data["metadata"], dict) - and data["metadata"].get("repository") == PILOT_REPOSITORY, "Invalid workflow job") + and data["metadata"].get("repository") == claims["repository"], "Invalid workflow job") validator = _issue_job if claims["kind"] == "issue-loop" else _memory_job - return validator(data["metadata"], claims) + target = validator(data["metadata"], claims) + return target if claims["repository"] == PILOT_REPOSITORY else f"repo-{claims['repository_id']}-{target}" class JobStore: diff --git a/automation_bridge/bundle.py b/automation_bridge/bundle.py index 4e10449..b99c251 100644 --- a/automation_bridge/bundle.py +++ b/automation_bridge/bundle.py @@ -12,6 +12,7 @@ def build(output: Path) -> None: files = ( source / "function_app.py", source / "bridge.py", source / "host.json", source / "requirements.txt", + source / "repository_allowlist.json", action / "issuelens_action.py", action / "stream_output.py", ) with ZipFile(output, "x", ZIP_DEFLATED) as archive: diff --git a/automation_bridge/function_app.py b/automation_bridge/function_app.py index 26faac3..b3e439b 100644 --- a/automation_bridge/function_app.py +++ b/automation_bridge/function_app.py @@ -86,7 +86,7 @@ def submit(request: func.HttpRequest) -> func.HttpResponse: return respond({"error": "invalid_job"}, 400) if "ref_protected" not in claims: try: - protected = bridge.pilot_branch_protected() + protected = bridge.pilot_branch_protected(claims) except (OSError, http.client.HTTPException, ValueError): logger.warning("GitHub branch protection unavailable") return respond({"error": "branch_protection_unavailable"}, 503) diff --git a/automation_bridge/repository_allowlist.json b/automation_bridge/repository_allowlist.json new file mode 100644 index 0000000..ed396b2 --- /dev/null +++ b/automation_bridge/repository_allowlist.json @@ -0,0 +1,26 @@ +{ + "microsoft/IssueLens": { + "id": 1303440932, + "branch": "main", + "workflows": { + ".github/workflows/issue-triage.yml": { + "kind": "issue-loop", + "events": ["issues", "issue_comment", "workflow_dispatch"] + }, + ".github/workflows/team-memory-coordinator.yml": { + "kind": "team-memory", + "events": ["workflow_dispatch"] + } + } + }, + "microsoft/vscode-java-pack": { + "id": 104967329, + "branch": "main", + "workflows": { + ".github/workflows/issueLens-run.yml": { + "kind": "issue-loop", + "events": ["workflow_dispatch"] + } + } + } +} diff --git a/docs/guide.md b/docs/guide.md index 16acf33..f9cc6b9 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1053,8 +1053,10 @@ routing and command validation; no new permanent agent contract is introduced. ### IssueLens Function bridge pilot -The pilot is **only for `microsoft/IssueLens`**. Keep the GitHub App webhook -unchanged. No Java workflow or other App installation participates. Obtain +The bridge's reviewed `automation_bridge/repository_allowlist.json` admits +`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 are admitted. 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; @@ -1064,16 +1066,17 @@ 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. Publish it through an approved release path to **two** Function apps -with distinct managed identities. Use a plan that supports a 40-minute function +two Functions roles, the repository allowlist, and the reused workflow helpers, +with a separate dependency manifest. A missing or invalid allowlist prevents +the bundle 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. | 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 enrolled numeric GitHub repository ID, and `ISSUELENS_BRIDGE_OIDC_AUDIENCE` set to the exact HTTPS `/api/issuelens/v1/jobs` URL on the approved `azurewebsites.net` endpoint. The receiver verifies signature, audience, issuer, expiry, public repository, `main` ref, and the two exact GitHub-hosted workflows and their event types. 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`), 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 match the manifest or ingress rejects requests. The Java Pack ID comes only from the reviewed manifest, not a workflow input or a replacement for this setting. The receiver verifies signature, audience, issuer, expiry, public repository, protected `main` ref, GitHub-hosted runner, and each exact workflow and event. 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 @@ -1083,6 +1086,28 @@ 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. +Java Pack enrollment requires a separately approved bridge release and caller +workflow change. The reviewed entry binds public `microsoft/vscode-java-pack` +(repository ID `104967329`), `refs/heads/main`, and +`.github/workflows/issueLens-run.yml` to `issue-loop` with +`workflow_dispatch` only. 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 +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 +`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 +and its protected-branch code, not a separately attested payload or a pinned +workflow SHA. Changes to this allowlist require code review and a bridge +release; workflow inputs cannot enroll repositories. + The worker POSTs the standard `{ "input": "..." }` payload to the existing `/invocations` API. No replacement agent, host configuration change, or Foundry redeployment is required. Authorized direct API callers and chat continue to @@ -1110,7 +1135,7 @@ 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 or the one IssueLens wiki through +success. Reservations cover one issue per repository or the one IssueLens wiki 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 4236d70..721ae30 100644 --- a/tests/test_automation_bridge.py +++ b/tests/test_automation_bridge.py @@ -22,6 +22,13 @@ PILOT_REPOSITORY = bridge.PILOT_REPOSITORY +PILOT_REPOSITORY_ID = 1303440932 +BRANCH = "refs/heads/main" +ISSUE_WORKFLOW = ".github/workflows/issue-triage.yml" +MEMORY_WORKFLOW = ".github/workflows/team-memory-coordinator.yml" +JAVA_REPOSITORY = "microsoft/vscode-java-pack" +JAVA_REPOSITORY_ID = 104967329 +JAVA_WORKFLOW = ".github/workflows/issueLens-run.yml" 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 @@ -59,9 +66,9 @@ def setUp(self): now = int(time.time()) self.claims = { "iss": bridge.GITHUB_ISSUER, "aud": URL, "iat": now, "exp": now + 60, "nbf": now, - "repository": PILOT_REPOSITORY, "repository_id": "100", "repository_visibility": "public", - "ref": bridge.BRANCH, "runner_environment": "github-hosted", - "workflow_ref": bridge.workflow_ref(bridge.ISSUE_WORKFLOW), "workflow_sha": "1" * 40, + "repository": PILOT_REPOSITORY, "repository_id": str(PILOT_REPOSITORY_ID), "repository_visibility": "public", + "ref": BRANCH, "runner_environment": "github-hosted", + "workflow_ref": bridge.workflow_ref(ISSUE_WORKFLOW), "workflow_sha": "1" * 40, "event_name": "issue_comment", "actor": "maintainer", "run_id": "20", "run_attempt": "1", } self.enterContext(patch.object(bridge.KEYS, "get_signing_key_from_jwt", return_value=Mock(key=self.key.public_key()))) @@ -71,7 +78,7 @@ def token(self, **overrides): def load_ingress(self): self.enterContext(patch.dict(os.environ, { - "ISSUELENS_BRIDGE_ROLE": "ingress", "ISSUELENS_BRIDGE_REPOSITORY_ID": "100", + "ISSUELENS_BRIDGE_ROLE": "ingress", "ISSUELENS_BRIDGE_REPOSITORY_ID": str(PILOT_REPOSITORY_ID), "ISSUELENS_BRIDGE_OIDC_AUDIENCE": URL, "ISSUELENS_BRIDGE_QUEUE": "test-jobs", })) path = pathlib.Path(bridge.__file__).with_name("function_app.py") @@ -83,14 +90,133 @@ def load_ingress(self): handlers = {handler.get_function_name(): handler.get_user_function() for handler in ingress.app.get_functions()} return ingress, handlers["submit"], handlers["status"] - def request(self, identifier=None): - headers = {"Authorization": f"Bearer {self.token()}"} + def request(self, identifier=None, token=None, payload=None): + headers = {"Authorization": f"Bearer {token or self.token()}"} if identifier is not None: return HttpRequest("GET", f"{URL}/{identifier}", route_params={"job_id": identifier}, headers=headers, body=b"") - return HttpRequest("POST", URL, headers=headers, body=json.dumps(issue_payload()).encode()) + return HttpRequest("POST", URL, headers=headers, body=json.dumps(payload or issue_payload()).encode()) + + def java_token(self, **overrides): + return self.token(**({ + "repository": JAVA_REPOSITORY, "repository_id": str(JAVA_REPOSITORY_ID), + "workflow_ref": bridge.workflow_ref(JAVA_WORKFLOW, JAVA_REPOSITORY), + "event_name": "workflow_dispatch", + } | overrides)) + + def java_payload(self, **overrides): + metadata = issue_metadata( + repository=JAVA_REPOSITORY, event_name="workflow_dispatch", event_action="workflow_dispatch", + comment_id=None, comment_author_login=None, comment_author_association=None, + comment_added=False, comment_edited=False, manual_dispatch=True, + ) + metadata.pop("comment_sha256") + return {"request_type": "issue-loop", "metadata": metadata | overrides} + + def test_java_pack_admission_is_exact_and_manual_only(self): + accepted = bridge.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 overrides in ( + {"repository": PILOT_REPOSITORY}, {"repository_id": str(PILOT_REPOSITORY_ID)}, {"repository_id": "104967330"}, + {"repository_visibility": "private"}, {"ref": "refs/heads/other"}, {"ref_protected": "false"}, + {"runner_environment": "self-hosted"}, {"event_name": "issues"}, + {"event_name": "issue_comment"}, {"workflow_ref": bridge.workflow_ref(ISSUE_WORKFLOW)}, + {"workflow_ref": bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY)}, + {"workflow_ref": bridge.workflow_ref("other.yml", JAVA_REPOSITORY)}, + {"aud": ENDPOINT}, + ): + with self.subTest(overrides=overrides), self.assertRaises((ValueError, jwt.PyJWTError)): + bridge.workflow_claims(self.java_token(**overrides), URL, PILOT_REPOSITORY_ID) + for payload in ( + self.java_payload(repository=PILOT_REPOSITORY), + self.java_payload(event_name="issues", event_action="opened", manual_dispatch=False), + self.java_payload(actor_login="other"), + self.java_payload(input="untrusted task"), + {"request_type": "team-memory", "metadata": self.java_payload()["metadata"]}, + {"request_type": "task", "metadata": self.java_payload()["metadata"]}, + ): + with self.subTest(payload=payload), self.assertRaises(ValueError): + bridge.validate_request(payload, accepted) + pilot = bridge.workflow_claims(self.token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) + self.assertEqual(bridge.validate_request(issue_payload(), pilot), "issue-12") + 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, + ): + self.assertEqual(submit(self.request()).status_code, 401) + self.assertEqual(status(self.request(JOB, token=self.java_token())).status_code, 401) + jobs.assert_not_called() + + def test_existing_team_memory_workflow_remains_enabled(self): + claims = bridge.workflow_claims(self.token( + 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") + + def test_java_pack_fallback_and_same_run_receipt_are_repository_bound(self): + ingress, submit, status = self.load_ingress() + token = self.java_token() + claims = bridge.workflow_claims(token, URL, PILOT_REPOSITORY_ID) + identifier = bridge.job_id(claims) + with ( + patch.object(bridge.action, "github_read", return_value={"name": "main", "protected": True}) as github, + patch.object(ingress, "jobs") as jobs, + patch.object(ingress, "service_bus"), + ): + jobs.return_value.reserve.return_value = {"RowKey": identifier, "state": bridge.QUEUED} + jobs.return_value.get.return_value = {"RowKey": identifier, "state": bridge.COMPLETED} + response = submit(self.request(token=token, payload=self.java_payload())) + self.assertEqual(response.status_code, 202, response.get_body()) + github.assert_called_once_with("/repos/microsoft/vscode-java-pack/branches/main", token="", timeout=5) + self.assertEqual(jobs.return_value.reserve.call_args.args[1], "repo-104967329-issue-12") + self.assertEqual(status(self.request(identifier, token=token)).status_code, 200) + self.assertEqual(status(self.request(identifier)).status_code, 404) + with ( + patch.object(bridge.action, "github_read", return_value={"name": "main", "protected": False}), + 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"} + env = { + "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": BRANCH, + "GITHUB_WORKFLOW_REF": bridge.workflow_ref(JAVA_WORKFLOW, JAVA_REPOSITORY), + "GITHUB_WORKFLOW_SHA": "1" * 40, "ISSUE_NUMBER": "12", "GITHUB_ACTOR": "maintainer", + "TRANSPORT": "bridge", + } + with ( + patch.dict(os.environ, env, clear=True), + patch.object(bridge.action, "github_read", side_effect=[project, {"number": 12}]), + ): + envelope = bridge.action.prepare_issue_loop(JAVA_REPOSITORY, {"repository": project}) + claims = bridge.workflow_claims(self.java_token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) + 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)} + ) + self.assertEqual(json.loads(request.data), envelope["request"]) def test_only_the_expected_workflow_identity_is_accepted(self): - accepted = bridge.workflow_claims(self.token(ref_protected="true"), URL, 100) + accepted = bridge.workflow_claims(self.token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) self.assertEqual(bridge.validate_request(issue_payload(), accepted), "issue-12") for alteration in ( {"repository_id": "101"}, {"ref": "refs/heads/other"}, {"ref_protected": "false"}, @@ -99,11 +225,11 @@ def test_only_the_expected_workflow_identity_is_accepted(self): {"aud": ENDPOINT}, {"exp": self.claims["iat"] - 1}, ): with self.subTest(alteration=alteration), self.assertRaises((ValueError, jwt.PyJWTError)): - bridge.workflow_claims(self.token(**alteration), URL, 100) + bridge.workflow_claims(self.token(**alteration), URL, PILOT_REPOSITORY_ID) with self.assertRaises(jwt.InvalidSignatureError): bridge.workflow_claims( jwt.encode(self.claims, rsa.generate_private_key(public_exponent=65537, key_size=2048), algorithm="RS256"), - URL, 100, + URL, PILOT_REPOSITORY_ID, ) self.assertEqual(bridge.job_id(accepted), bridge.job_id(accepted | {"run_attempt": 2})) self.assertNotEqual(bridge.job_id(accepted), bridge.job_id(accepted | {"run_id": 21})) @@ -117,7 +243,7 @@ def test_only_the_expected_workflow_identity_is_accepted(self): def test_token_without_protection_claim_can_submit_and_poll_a_protected_branch_job(self): ingress, submit, status = self.load_ingress() - identifier = bridge.job_id({"kind": "issue-loop", "run_id": 20, "repository_id": 100}) + identifier = bridge.job_id({"kind": "issue-loop", "run_id": 20, "repository_id": PILOT_REPOSITORY_ID}) with ( patch.object(bridge.urllib.request, "build_opener") as opener, patch.object(ingress, "jobs") as jobs, @@ -165,6 +291,37 @@ def test_missing_protection_claim_does_not_admit_jobs_without_confirmed_protecti bus.assert_not_called() +class BridgeManifestTests(unittest.TestCase): + def test_invalid_manifest_is_rejected_as_a_whole(self): + source = pathlib.Path(bridge.__file__).with_name("repository_allowlist.json") + original = source.read_text(encoding="utf-8") + java = json.loads(original)[JAVA_REPOSITORY] + policies = json.loads(original) + invalid = { + "duplicate key": '{"microsoft/IssueLens": {},' + original.lstrip()[1:], + "missing primary": json.dumps({JAVA_REPOSITORY: java}), + "duplicate repository ID": json.dumps(policies | {JAVA_REPOSITORY: java | {"id": PILOT_REPOSITORY_ID}}), + "non-numeric ID": json.dumps(policies | {JAVA_REPOSITORY: java | {"id": str(JAVA_REPOSITORY_ID)}}), + "wildcard branch": json.dumps(policies | {JAVA_REPOSITORY: java | {"branch": "*"}}), + "unknown field": json.dumps(policies | {JAVA_REPOSITORY: java | {"visibility": "private"}}), + } + for key, path, kind, events in ( + ("automatic event", JAVA_WORKFLOW, "issue-loop", ["workflow_dispatch", "issues"]), + ("wiki job", JAVA_WORKFLOW, "team-memory", ["workflow_dispatch"]), + ("wildcard workflow", ".github/workflows/*.yml", "issue-loop", ["workflow_dispatch"]), + ("invalid event list", JAVA_WORKFLOW, "issue-loop", "workflow_dispatch"), + ): + invalid[key] = json.dumps(policies | { + JAVA_REPOSITORY: java | {"workflows": {path: {"kind": kind, "events": events}}}, + }) + with tempfile.TemporaryDirectory() as directory: + manifest = pathlib.Path(directory) / source.name + for label, content in invalid.items(): + with self.subTest(label=label), self.assertRaises(ValueError): + manifest.write_text(content, encoding="utf-8") + bridge.load_repository_allowlist(manifest) + + class BridgeActionTests(unittest.TestCase): def test_workflow_token_uses_the_bridge_audience_and_a_github_origin(self): endpoint = "https://tokenghub.actions.githubusercontent.com/_apis/idtoken?api-version=2.0&audience=previous" @@ -405,7 +562,7 @@ def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): with ZipFile(archive) as source: self.assertEqual(set(source.namelist()), { "function_app.py", "bridge.py", "host.json", "requirements.txt", - "issuelens_action.py", "stream_output.py", + "issuelens_action.py", "stream_output.py", "repository_allowlist.json", }) source.extractall(root) for role, expected in (("ingress", "status,submit"), ("worker", "process")): @@ -426,6 +583,15 @@ 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) + (root / "repository_allowlist.json").unlink() + result = subprocess.run( + [sys.executable, "-c", "import function_app"], cwd=root, + env={**os.environ, "ISSUELENS_BRIDGE_ROLE": "ingress"}, + capture_output=True, text=True, timeout=30, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("FileNotFoundError", result.stderr) + self.assertIn("repository_allowlist.json", result.stderr) if __name__ == "__main__": diff --git a/tests/test_team_memory_coordinator.py b/tests/test_team_memory_coordinator.py index 84af10d..16c3dbd 100644 --- a/tests/test_team_memory_coordinator.py +++ b/tests/test_team_memory_coordinator.py @@ -77,7 +77,7 @@ def source_responses(self): def coordinator_claims(self): return { - "kind": "team-memory", "repository_id": self.project["id"], + "kind": "team-memory", "repository": self.repository, "repository_id": self.project["id"], "actor": self.environment["GITHUB_ACTOR"], "workflow_ref": self.environment["GITHUB_WORKFLOW_REF"], "workflow_sha": self.environment["GITHUB_WORKFLOW_SHA"], From 28388f0a8538cd9a8bc399276d5fdb38ca33fc73 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Wed, 25 Nov 2026 11:14:40 +0800 Subject: [PATCH 2/3] Simplify bridge repository allowlist configuration Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/issuelens/README.md | 7 +- .github/copilot-instructions.md | 9 +- automation_bridge/bridge.py | 121 ++++++------ automation_bridge/bundle.py | 1 - automation_bridge/function_app.py | 21 +- .../repository_allowlist.example.json | 4 + automation_bridge/repository_allowlist.json | 26 --- docs/guide.md | 52 +++-- tests/test_automation_bridge.py | 186 +++++++++++------- 9 files changed, 246 insertions(+), 181 deletions(-) create mode 100644 automation_bridge/repository_allowlist.example.json delete mode 100644 automation_bridge/repository_allowlist.json diff --git a/.github/actions/issuelens/README.md b/.github/actions/issuelens/README.md index 60e77de..3571c85 100644 --- a/.github/actions/issuelens/README.md +++ b/.github/actions/issuelens/README.md @@ -22,9 +22,10 @@ and result validation. No inline Python, pip installation, container build, or GitHub App private key is required. The [Function bridge pilot](../../../docs/guide.md#issuelens-function-bridge-pilot) -uses GitHub workflow identity for the reviewed `microsoft/IssueLens` workflows -and the manual-only `microsoft/vscode-java-pack` issue-loop pilot. It submits typed -metadata after the same preflight, skips Azure login, and polls the job receipt. +is a deployment-specific example, not a restriction on where this reusable action +can be used. Configured bridge deployments determine which workflow identities +and request types they accept. The action submits typed metadata after the same +preflight, skips Azure login, and polls the job receipt. The worker authenticates to the existing `/invocations` endpoint using managed identity and submits the normal `{ "input": "..." }` request. It has no direct fallback or free-form task path. It does not stream or store diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index e66203a..514c85b 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -318,10 +318,11 @@ 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 `automation_bridge/repository_allowlist.json` - additionally admits only manual issue-loop dispatch from - `microsoft/vscode-java-pack` at its exact workflow on protected `main`; - it grants no Java Pack automatic events or team-memory. + 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 + 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 queueing stay outside the hosted agent. The agent remains independently diff --git a/automation_bridge/bridge.py b/automation_bridge/bridge.py index effe613..00208f9 100644 --- a/automation_bridge/bridge.py +++ b/automation_bridge/bridge.py @@ -42,46 +42,20 @@ class BusyError(Exception): """A different job still owns the target reservation.""" -def load_repository_allowlist(path: Path) -> dict: - policies = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=action.unique_object) - require(isinstance(policies, dict) and PILOT_REPOSITORY in policies, "Missing IssueLens allowlist entry") - ids = set() - names = set() - for repository, policy in policies.items(): - require(re.fullmatch(r"[A-Za-z0-9-]+/[A-Za-z0-9_.-]+", repository) - and repository.casefold() not in names - and isinstance(policy, dict) and set(policy) == {"id", "branch", "workflows"} - and type(policy["id"]) is int and policy["id"] > 0 and policy["id"] not in ids - and isinstance(policy["branch"], str) - and re.fullmatch(r"[A-Za-z0-9_-]+", policy["branch"]) - and isinstance(policy["workflows"], dict) and policy["workflows"], - "Invalid bridge repository allowlist") - require(repository != PILOT_REPOSITORY or policy["branch"] == PILOT_BRANCH, - "IssueLens must retain its existing bridge branch") - ids.add(policy["id"]) - names.add(repository.casefold()) - for path, workflow in policy["workflows"].items(): - require(re.fullmatch(r"\.github/workflows/[A-Za-z0-9_.-]+\.ya?ml", path) - and isinstance(workflow, dict) and set(workflow) == {"kind", "events"} - and workflow["kind"] in ("issue-loop", "team-memory") - and isinstance(workflow["events"], list) and workflow["events"] - and all(isinstance(event, str) for event in workflow["events"]), - "Invalid bridge workflow allowlist") - events = set(workflow["events"]) - allowed_events = {"workflow_dispatch"} - if repository == PILOT_REPOSITORY and workflow["kind"] == "issue-loop": - allowed_events.update({"issues", "issue_comment"}) - require(len(events) == len(workflow["events"]) and events <= allowed_events - and (repository == PILOT_REPOSITORY or workflow["kind"] == "issue-loop"), - "Invalid bridge workflow scope") - return policies - - -_REPOSITORY_ALLOWLIST = load_repository_allowlist(Path(__file__).with_name("repository_allowlist.json")) - - -def workflow_claims(token: str, audience: str, repository_id: int) -> dict: - require(type(repository_id) is int and repository_id == _REPOSITORY_ALLOWLIST[PILOT_REPOSITORY]["id"], +def load_repository_allowlist(value: str, pilot_repository_id: int) -> frozenset[int]: + require(isinstance(value, str) and 0 < len(value.encode("utf-8")) <= 32 * 1024, + "Invalid bridge repository allowlist size") + ids = json.loads(value, object_pairs_hook=action.unique_object) + 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, + "Invalid bridge repository ID allowlist") + return frozenset(ids) + + +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") key = KEYS.get_signing_key_from_jwt(token) @@ -92,36 +66,69 @@ def workflow_claims(token: str, audience: str, repository_id: int) -> dict: "ref", "workflow_ref", "workflow_sha", "event_name", "run_id", "run_attempt", "actor", ], "strict_aud": True}, ) - require(isinstance(claims["repository"], str), "Invalid workflow repository") - policy = _REPOSITORY_ALLOWLIST.get(claims["repository"]) - require(policy is not None - and claims["repository_id"] == str(policy["id"]) + require(isinstance(claims["repository"], str) + and re.fullmatch(r"[A-Za-z0-9-]+/[A-Za-z0-9_.-]+", claims["repository"]) + and isinstance(claims["repository_id"], str) + and claims["repository_id"].isdecimal() + and int(claims["repository_id"]) in allowlist + and (claims["repository"] != PILOT_REPOSITORY + or int(claims["repository_id"]) == pilot_repository_id) and claims["repository_visibility"] == "public" - and claims["ref"] == f"refs/heads/{policy['branch']}" + 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") if "ref_protected" in claims: protected = claims["ref_protected"] require(protected is True or protected == "true", "Workflow ref was not protected") - for path, workflow in policy["workflows"].items(): - if claims["workflow_ref"] == workflow_ref(path, claims["repository"], policy["branch"]): - require(claims["event_name"] in workflow["events"], "Unsupported workflow event") - return { - **claims, "kind": workflow["kind"], "repository_id": policy["id"], - "run_id": action.positive(claims["run_id"]), "run_attempt": action.positive(claims["run_attempt"]), - "workflow_sha": action.full_sha(claims["workflow_sha"]), - } - raise ValueError("Workflow is not enabled for this bridge") + if claims["repository"] == PILOT_REPOSITORY: + if claims["workflow_ref"] == workflow_ref(".github/workflows/issue-triage.yml"): + require(claims["event_name"] in {"issues", "issue_comment", "workflow_dispatch"}, + "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"])) + 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") + return _validated_claims(claims, "issue-loop", int(claims["repository_id"])) + + +def _validated_claims(claims: dict, kind: str, repository_id: int) -> dict: + return { + **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"]), + } def workflow_ref(path: str, repository: str = PILOT_REPOSITORY, branch: str = PILOT_BRANCH) -> str: return f"{repository}/{path}@refs/heads/{branch}" -def pilot_branch_protected(claims: dict) -> bool: +def default_branch_protected(claims: dict) -> bool: repository = claims["repository"] - branch_name = claims["ref"].removeprefix("refs/heads/") - branch = action.github_read(f"/repos/{repository}/branches/{branch_name}", token="", timeout=5) + project = action.github_read(f"/repos/{repository}", token="", timeout=5) + branch_name = project.get("default_branch") + require(isinstance(project.get("full_name"), str) and type(project.get("id")) is int + and type(project.get("private")) is bool and isinstance(project.get("visibility"), str) + and isinstance(branch_name, str) and branch_name, + "Invalid GitHub repository response") + if (project["full_name"].casefold() != repository.casefold() + 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: + return True + branch_path = urllib.parse.quote(branch_name, safe="") + branch = action.github_read(f"/repos/{repository}/branches/{branch_path}", token="", timeout=5) require(branch.get("name") == branch_name and isinstance(branch.get("protected"), bool), "Invalid GitHub branch protection response") return branch["protected"] diff --git a/automation_bridge/bundle.py b/automation_bridge/bundle.py index b99c251..4e10449 100644 --- a/automation_bridge/bundle.py +++ b/automation_bridge/bundle.py @@ -12,7 +12,6 @@ def build(output: Path) -> None: files = ( source / "function_app.py", source / "bridge.py", source / "host.json", source / "requirements.txt", - source / "repository_allowlist.json", action / "issuelens_action.py", action / "stream_output.py", ) with ZipFile(output, "x", ZIP_DEFLATED) as archive: diff --git a/automation_bridge/function_app.py b/automation_bridge/function_app.py index b3e439b..8f5d910 100644 --- a/automation_bridge/function_app.py +++ b/automation_bridge/function_app.py @@ -63,11 +63,17 @@ def authorized(request): return bridge.workflow_claims( auth[len("Bearer "):], os.environ["ISSUELENS_BRIDGE_OIDC_AUDIENCE"], bridge.action.positive(os.environ["ISSUELENS_BRIDGE_REPOSITORY_ID"]), + repository_ids, ) role = os.environ.get("ISSUELENS_BRIDGE_ROLE") if role == "ingress": + pilot_repository_id = bridge.action.positive(os.environ["ISSUELENS_BRIDGE_REPOSITORY_ID"]) + repository_ids = bridge.load_repository_allowlist( + os.environ.get("ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST", ""), pilot_repository_id, + ) + @app.route(route="issuelens/v1/jobs", methods=["POST"], trigger_arg_name="request") def submit(request: func.HttpRequest) -> func.HttpResponse: try: @@ -84,14 +90,13 @@ def submit(request: func.HttpRequest) -> func.HttpResponse: target = bridge.validate_request(data, claims) except (ValueError, TypeError): return respond({"error": "invalid_job"}, 400) - if "ref_protected" not in claims: - try: - protected = bridge.pilot_branch_protected(claims) - except (OSError, http.client.HTTPException, ValueError): - logger.warning("GitHub branch protection unavailable") - return respond({"error": "branch_protection_unavailable"}, 503) - if not protected: - return respond({"error": "workflow_not_authorized"}, 401) + try: + protected = bridge.default_branch_protected(claims) + except (OSError, http.client.HTTPException, ValueError): + logger.warning("GitHub repository or branch validation unavailable") + return respond({"error": "branch_protection_unavailable"}, 503) + if not protected: + return respond({"error": "workflow_not_authorized"}, 401) identifier = bridge.job_id(claims) try: job = jobs().reserve(identifier, target, body) diff --git a/automation_bridge/repository_allowlist.example.json b/automation_bridge/repository_allowlist.example.json new file mode 100644 index 0000000..08756e2 --- /dev/null +++ b/automation_bridge/repository_allowlist.example.json @@ -0,0 +1,4 @@ +[ + 1303440932, + 104967329 +] diff --git a/automation_bridge/repository_allowlist.json b/automation_bridge/repository_allowlist.json deleted file mode 100644 index ed396b2..0000000 --- a/automation_bridge/repository_allowlist.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "microsoft/IssueLens": { - "id": 1303440932, - "branch": "main", - "workflows": { - ".github/workflows/issue-triage.yml": { - "kind": "issue-loop", - "events": ["issues", "issue_comment", "workflow_dispatch"] - }, - ".github/workflows/team-memory-coordinator.yml": { - "kind": "team-memory", - "events": ["workflow_dispatch"] - } - } - }, - "microsoft/vscode-java-pack": { - "id": 104967329, - "branch": "main", - "workflows": { - ".github/workflows/issueLens-run.yml": { - "kind": "issue-loop", - "events": ["workflow_dispatch"] - } - } - } -} diff --git a/docs/guide.md b/docs/guide.md index f9cc6b9..9b57c2d 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1053,10 +1053,10 @@ routing and command validation; no new permanent agent contract is introduced. ### IssueLens Function bridge pilot -The bridge's reviewed `automation_bridge/repository_allowlist.json` admits +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 are admitted. Keep the GitHub App webhook unchanged. Obtain +team-memory jobs should be admitted. 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,9 +1066,9 @@ 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, the repository allowlist, and the reused workflow helpers, -with a separate dependency manifest. A missing or invalid allowlist prevents -the bundle from initializing. Publish it through an approved release path to +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 **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. @@ -1076,7 +1076,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`), 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 match the manifest or ingress rejects requests. The Java Pack ID comes only from the reviewed manifest, not a workflow input or a replacement for this setting. The receiver verifies signature, audience, issuer, expiry, public repository, protected `main` ref, GitHub-hosted runner, and each exact workflow and event. 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. 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. | | 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 @@ -1086,13 +1086,37 @@ 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. +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, 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. + +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 +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 reviewed entry binds public `microsoft/vscode-java-pack` -(repository ID `104967329`), `refs/heads/main`, and -`.github/workflows/issueLens-run.yml` to `issue-loop` with -`workflow_dispatch` only. 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 +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 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 @@ -1105,8 +1129,8 @@ 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 and its protected-branch code, not a separately attested payload or a pinned -workflow SHA. Changes to this allowlist require code review and a bridge -release; workflow inputs cannot enroll repositories. +workflow SHA. Changes to this allowlist require authorized configuration +review; workflow inputs cannot enroll repositories. The worker POSTs the standard `{ "input": "..." }` payload to the existing `/invocations` API. No replacement agent, host configuration change, or Foundry diff --git a/tests/test_automation_bridge.py b/tests/test_automation_bridge.py index 721ae30..ff2d9ed 100644 --- a/tests/test_automation_bridge.py +++ b/tests/test_automation_bridge.py @@ -33,6 +33,7 @@ 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") def issue_metadata(**overrides): @@ -76,10 +77,15 @@ def setUp(self): def token(self, **overrides): return jwt.encode(self.claims | overrides, self.key, algorithm="RS256") - def load_ingress(self): + 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 load_ingress(self, allowlist=ALLOWLIST_JSON): self.enterContext(patch.dict(os.environ, { "ISSUELENS_BRIDGE_ROLE": "ingress", "ISSUELENS_BRIDGE_REPOSITORY_ID": str(PILOT_REPOSITORY_ID), "ISSUELENS_BRIDGE_OIDC_AUDIENCE": URL, "ISSUELENS_BRIDGE_QUEUE": "test-jobs", + "ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST": allowlist, })) path = pathlib.Path(bridge.__file__).with_name("function_app.py") spec = importlib.util.spec_from_file_location("test_bridge_ingress", path) @@ -112,20 +118,23 @@ def java_payload(self, **overrides): metadata.pop("comment_sha256") return {"request_type": "issue-loop", "metadata": metadata | overrides} - def test_java_pack_admission_is_exact_and_manual_only(self): - accepted = bridge.workflow_claims(self.java_token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) + def test_java_pack_manual_dispatch_is_allowed_from_an_enrolled_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 overrides in ( - {"repository": PILOT_REPOSITORY}, {"repository_id": str(PILOT_REPOSITORY_ID)}, {"repository_id": "104967330"}, - {"repository_visibility": "private"}, {"ref": "refs/heads/other"}, {"ref_protected": "false"}, + {"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)}, - {"workflow_ref": bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY)}, - {"workflow_ref": bridge.workflow_ref("other.yml", JAVA_REPOSITORY)}, {"aud": ENDPOINT}, ): with self.subTest(overrides=overrides), self.assertRaises((ValueError, jwt.PyJWTError)): - bridge.workflow_claims(self.java_token(**overrides), URL, PILOT_REPOSITORY_ID) + self.workflow_claims(self.java_token(**overrides), URL, PILOT_REPOSITORY_ID) for payload in ( self.java_payload(repository=PILOT_REPOSITORY), self.java_payload(event_name="issues", event_action="opened", manual_dispatch=False), @@ -136,7 +145,7 @@ def test_java_pack_admission_is_exact_and_manual_only(self): ): with self.subTest(payload=payload), self.assertRaises(ValueError): bridge.validate_request(payload, accepted) - pilot = bridge.workflow_claims(self.token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) + pilot = self.workflow_claims(self.token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) self.assertEqual(bridge.validate_request(issue_payload(), pilot), "issue-12") self.assertNotEqual(bridge.job_id(pilot), bridge.job_id(accepted)) self.assertEqual(bridge.job_id(accepted), bridge.job_id(accepted | {"run_attempt": 2})) @@ -148,11 +157,31 @@ def test_ingress_rejects_requests_if_configured_issuelens_id_disagrees_with_mani patch.object(ingress, "jobs") as jobs, ): self.assertEqual(submit(self.request()).status_code, 401) - self.assertEqual(status(self.request(JOB, token=self.java_token())).status_code, 401) + 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" + 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") + def test_existing_team_memory_workflow_remains_enabled(self): - claims = bridge.workflow_claims(self.token( + claims = self.workflow_claims(self.token( workflow_ref=bridge.workflow_ref(MEMORY_WORKFLOW), event_name="workflow_dispatch", ref_protected="true", ), URL, PILOT_REPOSITORY_ID) @@ -172,10 +201,14 @@ def test_existing_team_memory_workflow_remains_enabled(self): def test_java_pack_fallback_and_same_run_receipt_are_repository_bound(self): ingress, submit, status = self.load_ingress() token = self.java_token() - claims = bridge.workflow_claims(token, URL, PILOT_REPOSITORY_ID) + claims = self.workflow_claims(token, URL, PILOT_REPOSITORY_ID) identifier = bridge.job_id(claims) + repository_info = { + "id": JAVA_REPOSITORY_ID, "full_name": JAVA_REPOSITORY, "private": False, + "visibility": "public", "default_branch": "main", + } with ( - patch.object(bridge.action, "github_read", return_value={"name": "main", "protected": True}) as github, + patch.object(bridge.action, "github_read", side_effect=[repository_info, {"name": "main", "protected": True}]) as github, patch.object(ingress, "jobs") as jobs, patch.object(ingress, "service_bus"), ): @@ -183,12 +216,17 @@ def test_java_pack_fallback_and_same_run_receipt_are_repository_bound(self): jobs.return_value.get.return_value = {"RowKey": identifier, "state": bridge.COMPLETED} response = submit(self.request(token=token, payload=self.java_payload())) self.assertEqual(response.status_code, 202, response.get_body()) - github.assert_called_once_with("/repos/microsoft/vscode-java-pack/branches/main", token="", timeout=5) + self.assertEqual([call.args[0] for call in github.call_args_list], [ + "/repos/microsoft/vscode-java-pack", + "/repos/microsoft/vscode-java-pack/branches/main", + ]) self.assertEqual(jobs.return_value.reserve.call_args.args[1], "repo-104967329-issue-12") self.assertEqual(status(self.request(identifier, token=token)).status_code, 200) self.assertEqual(status(self.request(identifier)).status_code, 404) with ( - patch.object(bridge.action, "github_read", return_value={"name": "main", "protected": False}), + patch.object(bridge.action, "github_read", side_effect=[ + repository_info, {"name": "main", "protected": False}, + ]), patch.object(ingress, "jobs") as jobs, ): self.assertEqual(submit(self.request(token=token, payload=self.java_payload())).status_code, 401) @@ -207,7 +245,7 @@ def test_java_pack_action_preflight_produces_an_admissible_manual_job(self): patch.object(bridge.action, "github_read", side_effect=[project, {"number": 12}]), ): envelope = bridge.action.prepare_issue_loop(JAVA_REPOSITORY, {"repository": project}) - claims = bridge.workflow_claims(self.java_token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) + claims = self.workflow_claims(self.java_token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) 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( @@ -216,18 +254,18 @@ def test_java_pack_action_preflight_produces_an_admissible_manual_job(self): self.assertEqual(json.loads(request.data), envelope["request"]) def test_only_the_expected_workflow_identity_is_accepted(self): - accepted = bridge.workflow_claims(self.token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) + accepted = self.workflow_claims(self.token(ref_protected="true"), URL, PILOT_REPOSITORY_ID) self.assertEqual(bridge.validate_request(issue_payload(), accepted), "issue-12") for alteration in ( - {"repository_id": "101"}, {"ref": "refs/heads/other"}, {"ref_protected": "false"}, + {"repository_id": "101"}, {"ref": "refs/tags/v1"}, {"ref_protected": "false"}, {"repository_visibility": "private"}, {"runner_environment": "self-hosted"}, {"event_name": "pull_request"}, {"workflow_ref": bridge.workflow_ref("another.yml")}, {"aud": ENDPOINT}, {"exp": self.claims["iat"] - 1}, ): with self.subTest(alteration=alteration), self.assertRaises((ValueError, jwt.PyJWTError)): - bridge.workflow_claims(self.token(**alteration), URL, PILOT_REPOSITORY_ID) + self.workflow_claims(self.token(**alteration), URL, PILOT_REPOSITORY_ID) with self.assertRaises(jwt.InvalidSignatureError): - bridge.workflow_claims( + self.workflow_claims( jwt.encode(self.claims, rsa.generate_private_key(public_exponent=65537, key_size=2048), algorithm="RS256"), URL, PILOT_REPOSITORY_ID, ) @@ -244,13 +282,19 @@ def test_only_the_expected_workflow_identity_is_accepted(self): def test_token_without_protection_claim_can_submit_and_poll_a_protected_branch_job(self): ingress, submit, status = self.load_ingress() identifier = bridge.job_id({"kind": "issue-loop", "run_id": 20, "repository_id": PILOT_REPOSITORY_ID}) + repository_info = { + "id": PILOT_REPOSITORY_ID, "full_name": PILOT_REPOSITORY, "private": False, + "visibility": "public", "default_branch": "main", + } with ( patch.object(bridge.urllib.request, "build_opener") as opener, patch.object(ingress, "jobs") as jobs, patch.object(ingress, "service_bus") as bus, ): read = opener.return_value.open - read.return_value.__enter__.return_value.read.return_value = b'{"name":"main","protected":true}' + read.return_value.__enter__.return_value.read.side_effect = [ + json.dumps(repository_info).encode(), b'{"name":"main","protected":true}', + ] jobs.return_value.reserve.return_value = {"RowKey": identifier, "state": bridge.QUEUED} jobs.return_value.get.return_value = {"RowKey": identifier, "state": bridge.COMPLETED} queued = submit(self.request()) @@ -265,61 +309,58 @@ def test_token_without_protection_claim_can_submit_and_poll_a_protected_branch_j self.assertEqual(json.loads(completed.get_body()), {"job_id": identifier, "state": bridge.COMPLETED}) self.assertEqual(status(self.request("8" * 64)).status_code, 404) jobs.return_value.get.assert_called_once_with(identifier) - read.assert_called_once() - branch_request, = read.call_args.args + self.assertEqual(read.call_count, 2) + repository_request, branch_request = [call.args[0] for call in read.call_args_list] + self.assertEqual(repository_request.full_url, f"https://api.github.com/repos/{PILOT_REPOSITORY}") self.assertEqual(branch_request.full_url, f"https://api.github.com/repos/{PILOT_REPOSITORY}/branches/main") self.assertEqual(branch_request.get_header("Cache-control"), "no-cache") self.assertFalse(branch_request.has_header("Authorization")) def test_missing_protection_claim_does_not_admit_jobs_without_confirmed_protection(self): ingress, submit, _ = self.load_ingress() - for response, expected in ( - ({"name": "main", "protected": False}, (401, {"error": "workflow_not_authorized"})), - ({"name": "main"}, (503, {"error": "branch_protection_unavailable"})), - (urllib.error.URLError("offline"), (503, {"error": "branch_protection_unavailable"})), + repository_info = { + "id": PILOT_REPOSITORY_ID, "full_name": PILOT_REPOSITORY, "private": False, + "visibility": "public", "default_branch": "main", + } + for responses, expected in ( + ([repository_info, {"name": "main", "protected": False}], (401, {"error": "workflow_not_authorized"})), + ([repository_info, {"name": "main"}], (503, {"error": "branch_protection_unavailable"})), + ([repository_info, urllib.error.URLError("offline")], (503, {"error": "branch_protection_unavailable"})), + ([repository_info | {"default_branch": "trunk"}], (401, {"error": "workflow_not_authorized"})), + ([repository_info | {"id": 42}], (401, {"error": "workflow_not_authorized"})), + ([repository_info | {"private": True}], (401, {"error": "workflow_not_authorized"})), + ([repository_info | {"visibility": "internal"}], (401, {"error": "workflow_not_authorized"})), + ([repository_info | {"full_name": "example/other"}], (401, {"error": "workflow_not_authorized"})), ): with ( - self.subTest(response=response), - patch.object(bridge.action, "github_read", side_effect=[response]) as github, + self.subTest(responses=responses), + patch.object(bridge.action, "github_read", side_effect=responses) as github, patch.object(ingress, "jobs") as jobs, patch.object(ingress, "service_bus") as bus, ): result = submit(self.request()) self.assertEqual((result.status_code, json.loads(result.get_body())), expected) - github.assert_called_once() + self.assertEqual(github.call_count, len(responses)) jobs.assert_not_called() bus.assert_not_called() -class BridgeManifestTests(unittest.TestCase): - def test_invalid_manifest_is_rejected_as_a_whole(self): - source = pathlib.Path(bridge.__file__).with_name("repository_allowlist.json") - original = source.read_text(encoding="utf-8") - java = json.loads(original)[JAVA_REPOSITORY] - policies = json.loads(original) +class BridgeAllowlistTests(unittest.TestCase): + def test_invalid_id_allowlist_is_rejected_as_a_whole(self): + original = ALLOWLIST_JSON + ids = json.loads(original) invalid = { - "duplicate key": '{"microsoft/IssueLens": {},' + original.lstrip()[1:], - "missing primary": json.dumps({JAVA_REPOSITORY: java}), - "duplicate repository ID": json.dumps(policies | {JAVA_REPOSITORY: java | {"id": PILOT_REPOSITORY_ID}}), - "non-numeric ID": json.dumps(policies | {JAVA_REPOSITORY: java | {"id": str(JAVA_REPOSITORY_ID)}}), - "wildcard branch": json.dumps(policies | {JAVA_REPOSITORY: java | {"branch": "*"}}), - "unknown field": json.dumps(policies | {JAVA_REPOSITORY: java | {"visibility": "private"}}), + "duplicate ID": json.dumps(ids + [JAVA_REPOSITORY_ID]), + "non-numeric ID": json.dumps(ids + [JAVA_REPOSITORY]), + "boolean ID": json.dumps(ids + [True]), + "empty": "", + "oversize": " " * (32 * 1024 + 1), + "object instead of list": json.dumps({"repositories": ids}), + "missing IssueLens ID": json.dumps([JAVA_REPOSITORY_ID]), } - for key, path, kind, events in ( - ("automatic event", JAVA_WORKFLOW, "issue-loop", ["workflow_dispatch", "issues"]), - ("wiki job", JAVA_WORKFLOW, "team-memory", ["workflow_dispatch"]), - ("wildcard workflow", ".github/workflows/*.yml", "issue-loop", ["workflow_dispatch"]), - ("invalid event list", JAVA_WORKFLOW, "issue-loop", "workflow_dispatch"), - ): - invalid[key] = json.dumps(policies | { - JAVA_REPOSITORY: java | {"workflows": {path: {"kind": kind, "events": events}}}, - }) - with tempfile.TemporaryDirectory() as directory: - manifest = pathlib.Path(directory) / source.name - for label, content in invalid.items(): - with self.subTest(label=label), self.assertRaises(ValueError): - manifest.write_text(content, encoding="utf-8") - bridge.load_repository_allowlist(manifest) + for label, content in invalid.items(): + with self.subTest(label=label), self.assertRaises(ValueError): + bridge.load_repository_allowlist(content, PILOT_REPOSITORY_ID) class BridgeActionTests(unittest.TestCase): @@ -562,11 +603,17 @@ def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): with ZipFile(archive) as source: self.assertEqual(set(source.namelist()), { "function_app.py", "bridge.py", "host.json", "requirements.txt", - "issuelens_action.py", "stream_output.py", "repository_allowlist.json", + "issuelens_action.py", "stream_output.py", }) source.extractall(root) 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) + if role == "ingress": + environment["ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST"] = ALLOWLIST_JSON + environment["ISSUELENS_BRIDGE_REPOSITORY_ID"] = str(PILOT_REPOSITORY_ID) result = subprocess.run( [sys.executable, "-c", ( "from inspect import signature\n" @@ -578,20 +625,23 @@ def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): "(function.get_function_name(), trigger)\n" "print(','.join(sorted(x.get_function_name() for x in functions)))" )], - cwd=root, env={**os.environ, "ISSUELENS_BRIDGE_ROLE": role}, + cwd=root, env=environment, capture_output=True, text=True, timeout=30, ) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout.strip(), expected) - (root / "repository_allowlist.json").unlink() - result = subprocess.run( - [sys.executable, "-c", "import function_app"], cwd=root, - env={**os.environ, "ISSUELENS_BRIDGE_ROLE": "ingress"}, - capture_output=True, text=True, timeout=30, - ) - self.assertNotEqual(result.returncode, 0) - self.assertIn("FileNotFoundError", result.stderr) - self.assertIn("repository_allowlist.json", result.stderr) + for value in (None, "", "{invalid"): + environment = {**os.environ, "ISSUELENS_BRIDGE_ROLE": "ingress"} + environment.pop("ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST", None) + environment["ISSUELENS_BRIDGE_REPOSITORY_ID"] = str(PILOT_REPOSITORY_ID) + if value is not None: + environment["ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST"] = value + result = subprocess.run( + [sys.executable, "-c", "import function_app"], cwd=root, + env=environment, + capture_output=True, text=True, timeout=30, + ) + self.assertNotEqual(result.returncode, 0) if __name__ == "__main__": From 2a1e8754d0fee12b294be2545113b7cb8419fd81 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Wed, 25 Nov 2026 11:35:16 +0800 Subject: [PATCH 3/3] Bind pilot repository ID to canonical name Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- automation_bridge/bridge.py | 2 ++ tests/test_automation_bridge.py | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/automation_bridge/bridge.py b/automation_bridge/bridge.py index 00208f9..3f1b4e8 100644 --- a/automation_bridge/bridge.py +++ b/automation_bridge/bridge.py @@ -71,6 +71,8 @@ def workflow_claims(token: str, audience: str, pilot_repository_id: int, allowli 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_visibility"] == "public" diff --git a/tests/test_automation_bridge.py b/tests/test_automation_bridge.py index ff2d9ed..f89ab50 100644 --- a/tests/test_automation_bridge.py +++ b/tests/test_automation_bridge.py @@ -118,6 +118,16 @@ def java_payload(self, **overrides): metadata.pop("comment_sha256") return {"request_type": "issue-loop", "metadata": metadata | overrides} + def test_pilot_case_only_repository_rename_is_rejected(self): + renamed = self.token( + repository="microsoft/issuelens", + workflow_ref=bridge.workflow_ref(".github/workflows/manual.yml", "microsoft/issuelens"), + event_name="workflow_dispatch", + ref_protected="true", + ) + 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): 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")