diff --git a/.github/actions/issuelens/README.md b/.github/actions/issuelens/README.md index f797a3f..3571c85 100644 --- a/.github/actions/issuelens/README.md +++ b/.github/actions/issuelens/README.md @@ -22,8 +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 `microsoft/IssueLens` only. 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 @@ -375,7 +377,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..514c85b 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -318,6 +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 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 5eae5ef..3f1b4e8 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,21 @@ class BusyError(Exception): """A different job still owns the target reservation.""" -def workflow_claims(token: str, audience: str, repository_id: int) -> dict: +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) claims = jwt.decode( @@ -59,33 +66,72 @@ 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) + 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 (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" - and claims["ref"] == 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, (kind, events) in WORKFLOWS.items(): - if claims["workflow_ref"] == workflow_ref(path): - require(claims["event_name"] in events, "Unsupported workflow event") - 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"]), - } - 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) -> 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 default_branch_protected(claims: dict) -> bool: + repository = claims["repository"] + 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"] @@ -213,9 +259,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/function_app.py b/automation_bridge/function_app.py index 26faac3..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() - 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/docs/guide.md b/docs/guide.md index 16acf33..9b57c2d 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 +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 approval for the GitHub-facing endpoint, direct trust of the GitHub Actions issuer, network access, and the Azure release path before provisioning or enabling anything. The Function validates a GitHub token addressed to itself; @@ -1065,15 +1067,16 @@ 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 +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. | 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`), `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 @@ -1083,6 +1086,52 @@ 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 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 +`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 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 +1159,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..f89ab50 100644 --- a/tests/test_automation_bridge.py +++ b/tests/test_automation_bridge.py @@ -22,10 +22,18 @@ 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 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): @@ -59,9 +67,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()))) @@ -69,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": "100", + "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) @@ -83,27 +96,188 @@ 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_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") + 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": "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)}, + {"aud": ENDPOINT}, + ): + with self.subTest(overrides=overrides), self.assertRaises((ValueError, jwt.PyJWTError)): + 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), + 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 = 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})) + + 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)).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 = 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({"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 = 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", side_effect=[repository_info, {"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()) + 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", 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) + 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 = 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( + {"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 = 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, 100) + 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, 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,14 +291,20 @@ 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}) + 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()) @@ -139,32 +319,60 @@ 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 BridgeAllowlistTests(unittest.TestCase): + def test_invalid_id_allowlist_is_rejected_as_a_whole(self): + original = ALLOWLIST_JSON + ids = json.loads(original) + invalid = { + "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 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): 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" @@ -410,6 +618,12 @@ def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): 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" @@ -421,11 +635,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) + 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__": 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"],