diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 514c85b..97d6cdd 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -318,11 +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 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. + 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 3f1b4e8..32e33d6 100644 --- a/automation_bridge/bridge.py +++ b/automation_bridge/bridge.py @@ -27,6 +27,13 @@ PILOT_REPOSITORY = action.COORDINATOR_REPOSITORY PILOT_BRANCH = "main" +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}") @@ -66,41 +73,46 @@ 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 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: + 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: - prefix = f"{claims['repository']}/.github/workflows/" + prefix = f"{repository}/{WORKFLOW_DIRECTORY}" 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"])) + workflow = claims["workflow_ref"] + 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) -> dict: @@ -160,11 +172,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) == { @@ -197,21 +206,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 +243,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 +254,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 +262,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" @@ -275,13 +285,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([ @@ -333,17 +343,17 @@ def receipt(job) -> dict: return value -def _verify_created_comment(metadata: dict, digest: str) -> None: +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/{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", @@ -363,11 +373,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..bed5f0a 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, ) @@ -99,7 +98,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 9b57c2d..d78d1b4 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1053,10 +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, 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 +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; @@ -1067,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 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. @@ -1076,61 +1074,70 @@ 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. 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 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; 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. +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 +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. 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 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 +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 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 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 -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 @@ -1154,12 +1161,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 f89ab50..44834a3 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 @@ -29,11 +30,15 @@ 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]) def issue_metadata(**overrides): @@ -58,6 +63,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): @@ -77,13 +97,13 @@ 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) + def workflow_claims(self, token, audience, repository_id, *, allowlist_json=ALLOWLIST_JSON): + 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): + 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_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, })) @@ -128,19 +148,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_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") - 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/nested/triage.yaml", JAVA_REPOSITORY)}, {"aud": ENDPOINT}, ): with self.subTest(overrides=overrides), self.assertRaises((ValueError, jwt.PyJWTError)): @@ -160,55 +181,257 @@ def test_java_pack_manual_dispatch_is_allowed_from_an_enrolled_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_an_allowlist_missing_its_configured_issuelens_id(self): + for settings in ( + {"pilot_id": OTHER_REPOSITORY_ID}, + {"allowlist": json.dumps([JAVA_REPOSITORY_ID])}, ): - self.assertEqual(submit(self.request()).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", + with self.subTest(settings=settings), self.assertRaises(ValueError): + self.load_ingress(**settings) + + 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, + ) + github.assert_called_with(f"/repos/{OTHER_REPOSITORY}/branches/trunk", token="", timeout=5) + with self.assertRaises(ValueError): + self.workflow_claims(self.token(**claims), URL, PILOT_REPOSITORY_ID) + + 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(MEMORY_WORKFLOW, OTHER_REPOSITORY), + "event_name": "workflow_dispatch", + } | overrides + return self.workflow_claims(self.token(**claims), URL, PILOT_REPOSITORY_ID, + 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, ) - 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") + 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(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) + 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"), + ("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( 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(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, + "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", } - self.assertEqual(bridge.validate_request({"request_type": "team-memory", "metadata": metadata}, claims), "wiki") + 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") + 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), + ("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): + def test_enrolled_repo_submit_requires_public_repo_identity_and_current_protected_default(self): ingress, submit, status = self.load_ingress() token = self.java_token() claims = self.workflow_claims(token, URL, PILOT_REPOSITORY_ID) @@ -231,6 +454,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 ( @@ -241,6 +465,17 @@ 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() + for mismatch in ( + {"full_name": OTHER_REPOSITORY}, {"id": OTHER_REPOSITORY_ID}, {"private": True}, + {"visibility": "internal"}, {"default_branch": "trunk"}, + ): + 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"} @@ -259,10 +494,65 @@ 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"]) + 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"} + job = {"repository": claims["repository"], "payload": json.dumps(payload)} + with patch.object(packaged.action, "github_read", return_value=comment) as read: + 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="") + 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(job) + 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") @@ -355,7 +645,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) @@ -367,6 +657,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]), + "non-positive ID": json.dumps(ids + [0]), } for label, content in invalid.items(): with self.subTest(label=label), self.assertRaises(ValueError): @@ -481,7 +772,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")) @@ -492,7 +783,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"}, @@ -509,6 +801,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 @@ -516,13 +830,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): @@ -622,7 +936,7 @@ def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): 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_ALLOWLIST"] = EXTENDED_ALLOWLIST environment["ISSUELENS_BRIDGE_REPOSITORY_ID"] = str(PILOT_REPOSITORY_ID) result = subprocess.run( [sys.executable, "-c", ( @@ -640,12 +954,13 @@ 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" for value in (None, "", "{invalid"): environment = {**os.environ, "ISSUELENS_BRIDGE_ROLE": "ingress"} - environment.pop("ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST", None) + environment.pop(allowlist_setting, None) environment["ISSUELENS_BRIDGE_REPOSITORY_ID"] = str(PILOT_REPOSITORY_ID) if value is not None: - environment["ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST"] = value + environment[allowlist_setting] = value result = subprocess.run( [sys.executable, "-c", "import function_app"], cwd=root, env=environment,