diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 97d6cdd..93ffe5c 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -320,8 +320,11 @@ The agent is driven by a workflow in the target repo credentials. No App webhook or corporate FIC is used. 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. + team-memory via the fixed coordinator on protected default `main` + (same-repository only for `microsoft/IssueLens`; same-repository or enrolled + non-pilot public cross-repository sources on their verified protected + default branch for non-pilot coordinators, where coordinator and validated + wiki destination match and share `repo--wiki`). 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. @@ -407,11 +410,13 @@ incomplete discovery rather than silently omitting sources. IssueLens automatic and manual requests share `issuelens-team-memory-wiki-microsoft-IssueLens` with `queue: max` and no in-progress cancellation: one complete coordinator run and at most 100 pending runs. Queue admission and dispatch acknowledgement -are not maintenance success. Only `microsoft/IssueLens` sources and its validated -`microsoft/IssueLens` wiki destination are accepted in this first rollout; -policy is never overridden to force a destination. Java tooling callers remain -unchanged and will need authenticated cross-repository dispatch and a separate -queue for their shared `microsoft/vscode-java-pack` wiki. Direct external action +are not maintenance success. In this repository's workflow, only +`microsoft/IssueLens` sources and its validated `microsoft/IssueLens` wiki +destination are accepted; policy is never overridden to force a destination. +Enrolled non-pilot coordinators such as `microsoft/vscode-java-pack` serialize +same-repository and enrolled Java tooling cross-repository sources under their +shared coordinator queue and durable `repo-104967329-wiki` bridge reservation. +Direct external action callers retain their existing event behavior and per-push concurrency. The pilot does not serialize chat, issue-loop work, or external direct requests. The manual pilot uses `ISSUELENS_TEAM_MEMORY_MANUAL_PILOT=true` after bridge diff --git a/automation_bridge/bridge.py b/automation_bridge/bridge.py index 32e33d6..2e7b448 100644 --- a/automation_bridge/bridge.py +++ b/automation_bridge/bridge.py @@ -95,7 +95,7 @@ def workflow_claims(token: str, audience: str, pilot_repository_id: int, allowli 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", repository_id) + return _validated_claims(claims, "team-memory", repository_id, pilot_repository_id, allowlist) else: raise ValueError("Workflow is not enabled for this bridge") else: @@ -110,14 +110,18 @@ def workflow_claims(token: str, audience: str, pilot_repository_id: int, allowli 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) + return _validated_claims(claims, "team-memory", repository_id, pilot_repository_id, allowlist) require(claims["event_name"] in ISSUE_EVENT_ACTIONS, "Unsupported workflow event") - return _validated_claims(claims, "issue-loop", repository_id) + return _validated_claims(claims, "issue-loop", repository_id, pilot_repository_id, allowlist) -def _validated_claims(claims: dict, kind: str, repository_id: int) -> dict: +def _validated_claims( + claims: dict, kind: str, repository_id: int, + pilot_repository_id: int, allowlist: frozenset[int], +) -> dict: return { **claims, "kind": kind, "repository_id": repository_id, + "pilot_repository_id": pilot_repository_id, "allowlist": allowlist, "run_id": action.positive(claims["run_id"]), "run_attempt": action.positive(claims["run_attempt"]), "workflow_sha": action.full_sha(claims["workflow_sha"]), } @@ -127,27 +131,59 @@ def workflow_ref(path: str, repository: str = PILOT_REPOSITORY, branch: str = PI return f"{repository}/{path}@refs/heads/{branch}" -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") +def _github_public_read(path: str) -> dict | None: + try: + return action.github_read(path, token="", timeout=5) + except urllib.error.HTTPError as error: + if error.code == 404: + return None + raise + + +def _branch_protected( + repository: str, repository_id: int, branch_name: str, *, skip_branch_read: bool = False, +) -> bool: + project = _github_public_read(f"/repos/{repository}") + if project is None: + return False + default_branch = 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, + and isinstance(default_branch, str) and default_branch, "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}"): + or project["id"] != repository_id or project["private"] + or project["visibility"] != "public" or default_branch != branch_name): return False - if "ref_protected" in claims: + if skip_branch_read: 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), + branch_path = urllib.parse.quote(default_branch, safe="") + branch = _github_public_read(f"/repos/{repository}/branches/{branch_path}") + if branch is None: + return False + require(branch.get("name") == default_branch and isinstance(branch.get("protected"), bool), "Invalid GitHub branch protection response") return branch["protected"] +def default_branch_protected(claims: dict, data: dict | None = None) -> bool: + ref = claims.get("ref", "") + if not isinstance(ref, str) or not ref.startswith("refs/heads/"): + return False + if not _branch_protected( + claims["repository"], claims["repository_id"], ref[len("refs/heads/"):], + skip_branch_read="ref_protected" in claims, + ): + return False + if data is not None and claims.get("kind") == "team-memory": + metadata = data["metadata"] + if metadata["repository_id"] != claims["repository_id"]: + return _branch_protected( + metadata["repository"], metadata["repository_id"], metadata["base_ref"], + ) + return True + + def job_id(claims: dict) -> str: return hashlib.sha256( f"v1:{claims['repository_id']}:{claims['kind']}:{claims['run_id']}".encode("ascii") @@ -169,7 +205,20 @@ def _positive_int(value): return action.positive(value) +def _valid_branch_name(value) -> bool: + return ( + isinstance(value, str) + and bool(re.fullmatch(r"[A-Za-z0-9._/-]{1,255}", value)) + and not value.startswith(("/", ".")) + and not value.endswith(("/", ".", ".lock")) + and ".." not in value + and "//" not in value + and "/." not in value + ) + + def _issue_job(metadata: dict, claims: dict) -> str: + require(metadata.get("repository") == claims["repository"], "Invalid workflow job") event = claims["event_name"] operation = metadata.get("event_action") require(metadata.get("event_name") == event and operation in ISSUE_EVENT_ACTIONS[event], @@ -217,16 +266,46 @@ def _validate_merge(merge: dict, repository: str): 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") == repository - and metadata.get("required_wiki_repository") == repository + coordinator = claims["repository"] + coordinator_id = _positive_int(claims["repository_id"]) + source_repository = metadata.get("repository") + source_repository_id = metadata.get("repository_id") + base_ref = metadata.get("base_ref") + require(metadata.get("coordinator_repository") == coordinator + and metadata.get("required_wiki_repository") == coordinator 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"] and metadata.get("coordinator_run_attempt") == claims["run_attempt"], "Team-memory coordinator identity mismatch") + require(isinstance(source_repository, str) + and re.fullmatch(action.SOURCE_REPOSITORY_PATTERN, source_repository) + and ".." not in source_repository + and type(source_repository_id) is int and source_repository_id > 0 + and _valid_branch_name(base_ref), + "Invalid team-memory source repository") + pilot_id = claims.get("pilot_repository_id") + if coordinator == PILOT_REPOSITORY or (type(pilot_id) is int and coordinator_id == pilot_id): + require(coordinator == PILOT_REPOSITORY + and source_repository == PILOT_REPOSITORY + and source_repository_id == coordinator_id + and base_ref == PILOT_BRANCH + and claims.get("ref", f"refs/heads/{PILOT_BRANCH}") == f"refs/heads/{PILOT_BRANCH}", + "Team-memory coordinator identity mismatch") + elif source_repository_id == coordinator_id: + require(source_repository == coordinator + and source_repository.casefold() != PILOT_REPOSITORY.casefold() + and claims.get("ref") == f"refs/heads/{base_ref}", + "Team-memory coordinator identity mismatch") + else: + allowlist = claims.get("allowlist") + require(isinstance(allowlist, frozenset) + and type(pilot_id) is int and pilot_id in allowlist + and coordinator_id in allowlist and coordinator_id != pilot_id + and source_repository_id in allowlist and source_repository_id != pilot_id + and source_repository.casefold() != PILOT_REPOSITORY.casefold() + and source_repository.casefold() != coordinator.casefold(), + "Team-memory source repository is not enrolled") fields = { "repository", "repository_id", "base_ref", "event_name", "event_action", "actor_login", "triggering_actor", "workflow_ref", "workflow_sha", "run_id", "run_attempt", @@ -243,9 +322,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"{repository}@{before}..{after}" + and metadata["source_identity"] == f"{source_repository}@{before}..{after}" and metadata["event_action"] == "push" and metadata["workflow_sha"] == after - and metadata["workflow_ref"] == workflow_ref(action.DISPATCH_WORKFLOW, repository) + and metadata["workflow_ref"] == workflow_ref(action.DISPATCH_WORKFLOW, source_repository, base_ref) and _positive_int(metadata["commit_count"]) <= action.MAX_PUSH_COMMITS, "Invalid reconciliation range metadata") _positive_int(metadata["run_id"]) @@ -254,7 +333,8 @@ 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, repository) for pull in pulls}) == len(pulls), "Duplicate merged PRs") + require(len({_validate_merge(pull, source_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" @@ -262,14 +342,14 @@ 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, repository) + _validate_merge(metadata, source_repository) return "wiki" 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") == claims["repository"], "Invalid workflow job") + and data["request_type"] == claims["kind"] and isinstance(data["metadata"], dict), + "Invalid workflow job") validator = _issue_job if claims["kind"] == "issue-loop" else _memory_job target = validator(data["metadata"], claims) return target if claims["repository"] == PILOT_REPOSITORY else f"repo-{claims['repository_id']}-{target}" @@ -374,9 +454,10 @@ 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": + if "repository" in job: + require(isinstance(repository, str) and repository == metadata.get("repository"), + "Bridge job repository mismatch") 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") @@ -389,6 +470,23 @@ def prepare(self, job) -> urllib.request.Request: _verify_created_comment(repository, metadata, digest) invocation = action.build_issue_loop_request(metadata) elif kind == "team-memory": + if "repository" in job: + if "coordinator_repository" in metadata: + require(isinstance(repository, str) + and repository == metadata.get("coordinator_repository") + and repository == metadata.get("required_wiki_repository"), + "Bridge job repository mismatch") + else: + require(isinstance(repository, str) + and repository == metadata.get("repository") + and repository == metadata.get("required_wiki_repository", repository), + "Bridge job repository mismatch") + if repository == PILOT_REPOSITORY: + require(metadata.get("repository") == PILOT_REPOSITORY, "Bridge job repository mismatch") + else: + require(isinstance(metadata.get("repository"), str) + and metadata["repository"].casefold() != PILOT_REPOSITORY.casefold(), + "Bridge job repository mismatch") invocation = action.build_team_memory_request(metadata) else: raise ValueError("Unsupported bridge job type") diff --git a/automation_bridge/function_app.py b/automation_bridge/function_app.py index bed5f0a..4af5dee 100644 --- a/automation_bridge/function_app.py +++ b/automation_bridge/function_app.py @@ -90,7 +90,7 @@ def submit(request: func.HttpRequest) -> func.HttpResponse: except (ValueError, TypeError): return respond({"error": "invalid_job"}, 400) try: - protected = bridge.default_branch_protected(claims) + protected = bridge.default_branch_protected(claims, data) except (OSError, http.client.HTTPException, ValueError): logger.warning("GitHub repository or branch validation unavailable") return respond({"error": "branch_protection_unavailable"}, 503) diff --git a/automation_bridge/repository_allowlist.example.json b/automation_bridge/repository_allowlist.example.json index 08756e2..f937430 100644 --- a/automation_bridge/repository_allowlist.example.json +++ b/automation_bridge/repository_allowlist.example.json @@ -1,4 +1,11 @@ [ 1303440932, - 104967329 + 104967329, + 102584737, + 102583752, + 110522074, + 216314492, + 626812412, + 129053101, + 116921700 ] diff --git a/docs/guide.md b/docs/guide.md index d78d1b4..da00984 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1087,11 +1087,15 @@ 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 +repository IDs (`microsoft/IssueLens`, `microsoft/vscode-java-pack`, and the +seven enrolled Java tooling repositories). The existing +`ISSUELENS_BRIDGE_REPOSITORY_ID` setting must remain in that array and continues to identify IssueLens. The setting is limited to 32 KiB; IDs must be positive, unique integers. **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. +repository grants bridge admission for issue-loop jobs on its protected default +branch and allows enrolled non-pilot team-memory coordinators to reconcile that +repository into the coordinator's shared wiki.** 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 @@ -1100,11 +1104,20 @@ 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. +`main`. For `microsoft/IssueLens`, coordinator, source, and validated wiki +destination must all match `microsoft/IssueLens` on `main`, and external +coordinators may never claim `microsoft/IssueLens` as a team-memory source. +For an enrolled non-pilot coordinator such as `microsoft/vscode-java-pack`, +`coordinator_repository` and `required_wiki_repository` must match the +authenticated coordinator repository, while `repository` and `repository_id` +may identify either the coordinator itself or another non-pilot repository in +`ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST`. Coordinated push ranges must identify +`.github/workflows/team-memory-post-merge.yml` on the source repository's +protected default branch (`base_ref`, such as `main` or `develop`), and ingress +independently verifies the cross-repository source's public GitHub identity, +default branch, and branch protection before admission. Same-repository and +cross-repository requests on that coordinator share one durable +`repo--wiki` reservation, separate from other coordinators. 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 @@ -1119,9 +1132,10 @@ 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 +For Java Pack and the enrolled Java tooling repositories, update +`ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST` to match +`automation_bridge/repository_allowlist.example.json` (`[1303440932,104967329,102584737,102583752,110522074,216314492,626812412,129053101,116921700]`). +Keep the Java 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 diff --git a/tests/test_automation_bridge.py b/tests/test_automation_bridge.py index 6113428..434622d 100644 --- a/tests/test_automation_bridge.py +++ b/tests/test_automation_bridge.py @@ -30,6 +30,23 @@ JAVA_REPOSITORY = "microsoft/vscode-java-pack" JAVA_REPOSITORY_ID = 104967329 JAVA_WORKFLOW = ".github/workflows/issueLens-run.yml" +JAVA_DEBUG_REPOSITORY = "microsoft/vscode-java-debug" +JAVA_DEBUG_REPOSITORY_ID = 102584737 +GRADLE_REPOSITORY = "microsoft/vscode-gradle" +GRADLE_REPOSITORY_ID = 216314492 +GRADLE_SERVER_REPOSITORY = "microsoft/build-server-for-gradle" +GRADLE_SERVER_REPOSITORY_ID = 626812412 +ENROLLED_REPOSITORY_IDS = [ + 1303440932, + 104967329, + 102584737, + 102583752, + 110522074, + 216314492, + 626812412, + 129053101, + 116921700, +] OTHER_REPOSITORY = "example/Project-Two" OTHER_REPOSITORY_ID = 24681012 OTHER_WORKFLOW = ".github/workflows/route-issues.yaml" @@ -431,6 +448,243 @@ def test_java_memory_receipt_is_owned_by_the_coordinator_run(self): ) self.assertEqual(status(self.request(identifier, token=different_run)).status_code, 404) + def test_cross_repo_java_coordinator_admits_enrolled_main_and_develop_sources_under_shared_wiki_lock(self): + ingress, submit, _ = self.load_ingress() + coordinator_project = { + "full_name": JAVA_REPOSITORY, "id": JAVA_REPOSITORY_ID, "private": False, + "default_branch": "main", "visibility": "public", + } + coordinator_ref = bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY) + token = self.java_token(workflow_ref=coordinator_ref, ref_protected="true") + claims = self.workflow_claims(token, URL, PILOT_REPOSITORY_ID) + worker = bridge.FoundryWorker(ENDPOINT, Mock(get_token=Mock(return_value=Mock(token="token")))) + before, after = "d" * 40, "e" * 40 + merged_at = "2026-11-24T00:00:00Z" + source_map = json.dumps({ + JAVA_REPOSITORY: JAVA_REPOSITORY_ID, + JAVA_DEBUG_REPOSITORY: JAVA_DEBUG_REPOSITORY_ID, + GRADLE_REPOSITORY: GRADLE_REPOSITORY_ID, + GRADLE_SERVER_REPOSITORY: GRADLE_SERVER_REPOSITORY_ID, + }) + for source_repo, source_id, base_ref in ( + (JAVA_DEBUG_REPOSITORY, JAVA_DEBUG_REPOSITORY_ID, "main"), + (GRADLE_REPOSITORY, GRADLE_REPOSITORY_ID, "develop"), + (GRADLE_SERVER_REPOSITORY, GRADLE_SERVER_REPOSITORY_ID, "develop"), + ): + source_project = { + "full_name": source_repo, "id": source_id, "private": False, + "default_branch": base_ref, "visibility": "public", + } + pull = { + "number": 18, "merged": True, "state": "closed", "merged_at": merged_at, + "merge_commit_sha": after, "base": {"ref": base_ref, "repo": source_project}, + } + source_run = { + "id": 31, "run_attempt": 2, "event": "push", + "path": bridge.action.DISPATCH_WORKFLOW, "head_branch": base_ref, "head_sha": after, + "repository": source_project, "head_repository": source_project, + "actor": {"login": "source-dev"}, "triggering_actor": {"login": "source-dev"}, + } + 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": 18, "state": "MERGED", "merged": True, "mergedAt": merged_at, + "baseRefName": base_ref, + "baseRepository": {"databaseId": source_id, "nameWithOwner": source_repo}, + "mergeCommit": {"oid": after}, + } + associations = {"data": {"repository": { + "databaseId": source_id, "nameWithOwner": source_repo, + "defaultBranchRef": {"name": base_ref, "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": source_repo, + "SOURCE_REPOSITORIES": source_map, "SOURCE_GH_TOKEN": "source-read-token", + } + for mode in ("manual", "push"): + variables = ({"DISPATCH_PR": "18"} if mode == "manual" else { + "SOURCE_RUN_ID": "31", "SOURCE_RUN_ATTEMPT": "2", + "PUSH_BEFORE": before, "PUSH_AFTER": after, + }) + preflight_reads = ( + [coordinator_project, source_project, pull] + if mode == "manual" + else [ + coordinator_project, source_project, source_run, + {"name": base_ref, "commit": {"sha": after}}, comparison, associations, + ] + ) + with ( + self.subTest(source=source_repo, mode=mode), + patch.dict(os.environ, environment | variables, clear=True), + patch.object(bridge.action, "github_read", side_effect=preflight_reads), + ): + envelope = bridge.action.prepare_team_memory(JAVA_REPOSITORY, {"repository": coordinator_project}) + metadata = envelope["metadata"] + payload = {"request_type": "team-memory", "metadata": metadata} + self.assertEqual(metadata["repository"], source_repo) + self.assertEqual(metadata["repository_id"], source_id) + self.assertEqual(metadata["base_ref"], base_ref) + self.assertEqual(metadata["coordinator_repository"], JAVA_REPOSITORY) + self.assertEqual(metadata["required_wiki_repository"], JAVA_REPOSITORY) + self.assertEqual(bridge.validate_request(payload, claims), "repo-104967329-wiki") + with ( + patch.object(bridge.action, "github_read", side_effect=[ + coordinator_project, source_project, {"name": base_ref, "protected": True}, + ]) as github, + patch.object(ingress, "jobs") as jobs, + patch.object(ingress, "service_bus"), + ): + identifier = bridge.job_id(claims) + jobs.return_value.reserve.return_value = {"RowKey": identifier, "state": bridge.QUEUED} + req = self.request(token=token, payload=payload) + response = submit(req) + self.assertEqual(response.status_code, 202, response.get_body()) + self.assertEqual( + [call.args[0] for call in github.call_args_list], + [ + f"/repos/{JAVA_REPOSITORY}", + f"/repos/{source_repo}", + f"/repos/{source_repo}/branches/{base_ref}", + ], + ) + jobs.return_value.reserve.assert_called_once_with( + identifier, "repo-104967329-wiki", req.get_body(), repository=JAVA_REPOSITORY, + ) + job = {"repository": JAVA_REPOSITORY, "payload": json.dumps(payload)} + self.assertEqual(json.loads(worker.prepare(job).data), envelope["request"]) + result = { + "source_repository": source_repo, "status": "updated", "reason": "Verified", + "wiki_repository": JAVA_REPOSITORY, "wiki_sha": "f" * 40, + } + if mode == "manual": + result.update(pull_number=18, merge_commit_sha=after) + else: + result.update(push_before=before, push_after=after, results=[{ + "pull_number": 18, "merge_commit_sha": after, "status": "updated", "reason": "Verified", + }]) + receipt = json.loads(bridge._memory_receipt(json.dumps(result), metadata)) + self.assertEqual(receipt["source_repository"], source_repo) + self.assertEqual(receipt["wiki_repository"], JAVA_REPOSITORY) + with self.assertRaises(ValueError): + bridge._memory_receipt(json.dumps(result | {"wiki_repository": source_repo}), metadata) + + def test_cross_repo_team_memory_enforces_pilot_isolation_allowlist_and_protected_source_branch(self): + ingress, submit, _ = self.load_ingress() + coordinator_ref = bridge.workflow_ref(MEMORY_WORKFLOW, JAVA_REPOSITORY) + java_token = self.java_token(workflow_ref=coordinator_ref, ref_protected="true") + java_claims = self.workflow_claims(java_token, URL, PILOT_REPOSITORY_ID) + pilot_claims = self.workflow_claims(self.token( + workflow_ref=bridge.workflow_ref(MEMORY_WORKFLOW), event_name="workflow_dispatch", ref_protected="true", + ), URL, PILOT_REPOSITORY_ID) + after = "a" * 40 + + # Pilot coordinator remains strictly same-repo and main-only even for enrolled Java IDs. + pilot_cross = manual_memory_payload(pilot_claims) + pilot_cross["metadata"].update( + repository=JAVA_REPOSITORY, repository_id=JAVA_REPOSITORY_ID, + source_identity=f"{JAVA_REPOSITORY}#12:{after}", + ) + with self.assertRaisesRegex(ValueError, "Team-memory coordinator identity mismatch"): + bridge.validate_request(pilot_cross, pilot_claims) + pilot_develop = manual_memory_payload(pilot_claims) + pilot_develop["metadata"]["base_ref"] = "develop" + with self.assertRaisesRegex(ValueError, "Team-memory coordinator identity mismatch"): + bridge.validate_request(pilot_develop, pilot_claims) + + # External coordinator can never claim IssueLens or an unallowlisted repo as a team-memory source. + for bad_repo, bad_id, base_ref in ( + (PILOT_REPOSITORY, PILOT_REPOSITORY_ID, "main"), + ("microsoft/issuelens", PILOT_REPOSITORY_ID, "main"), + (PILOT_REPOSITORY, GRADLE_REPOSITORY_ID, "main"), + ("microsoft/issuelens", GRADLE_REPOSITORY_ID, "main"), + (GRADLE_REPOSITORY, PILOT_REPOSITORY_ID, "develop"), + (OTHER_REPOSITORY, OTHER_REPOSITORY_ID, "main"), + (JAVA_REPOSITORY, GRADLE_REPOSITORY_ID, "main"), + ): + rejected = manual_memory_payload(java_claims) + rejected["metadata"].update( + repository=bad_repo, repository_id=bad_id, base_ref=base_ref, + source_identity=f"{bad_repo}#12:{after}", + ) + with self.subTest(repo=bad_repo, repo_id=bad_id), self.assertRaises(ValueError): + bridge.validate_request(rejected, java_claims) + + for bad_branch in ("", "/develop", "develop/", "release..1", "release//1", "develop.lock", "refs/heads/ main"): + rejected = manual_memory_payload(java_claims) + rejected["metadata"].update( + repository=GRADLE_REPOSITORY, repository_id=GRADLE_REPOSITORY_ID, base_ref=bad_branch, + source_identity=f"{GRADLE_REPOSITORY}#12:{after}", + ) + with self.subTest(base_ref=bad_branch), self.assertRaises(ValueError): + bridge.validate_request(rejected, java_claims) + + # Ingress checks cross-repo source visibility, ID, default branch, and branch protection. + gradle_payload = manual_memory_payload(java_claims) + gradle_payload["metadata"].update( + repository=GRADLE_REPOSITORY, repository_id=GRADLE_REPOSITORY_ID, base_ref="develop", + source_identity=f"{GRADLE_REPOSITORY}#12:{after}", + ) + coordinator_info = { + "id": JAVA_REPOSITORY_ID, "full_name": JAVA_REPOSITORY, "private": False, + "visibility": "public", "default_branch": "main", + } + gradle_info = { + "id": GRADLE_REPOSITORY_ID, "full_name": GRADLE_REPOSITORY, "private": False, + "visibility": "public", "default_branch": "develop", + } + not_found = urllib.error.HTTPError("https://api.github.com/repos/test", 404, "Not Found", hdrs=None, fp=None) + unavailable = urllib.error.HTTPError("https://api.github.com/repos/test", 503, "Unavailable", hdrs=None, fp=None) + for responses, expected in ( + ([coordinator_info, gradle_info, {"name": "develop", "protected": False}], (401, {"error": "workflow_not_authorized"})), + ([coordinator_info, gradle_info | {"default_branch": "main"}], (401, {"error": "workflow_not_authorized"})), + ([coordinator_info, gradle_info | {"private": True}], (401, {"error": "workflow_not_authorized"})), + ([coordinator_info, gradle_info | {"visibility": "internal"}], (401, {"error": "workflow_not_authorized"})), + ([coordinator_info, gradle_info | {"id": JAVA_DEBUG_REPOSITORY_ID}], (401, {"error": "workflow_not_authorized"})), + ([coordinator_info, gradle_info | {"full_name": JAVA_DEBUG_REPOSITORY}], (401, {"error": "workflow_not_authorized"})), + ([coordinator_info, not_found], (401, {"error": "workflow_not_authorized"})), + ([coordinator_info, gradle_info, not_found], (401, {"error": "workflow_not_authorized"})), + ([coordinator_info, unavailable], (503, {"error": "branch_protection_unavailable"})), + ([coordinator_info, gradle_info, urllib.error.URLError("offline")], (503, {"error": "branch_protection_unavailable"})), + ([coordinator_info, gradle_info, {"name": "develop"}], (503, {"error": "branch_protection_unavailable"})), + ): + with ( + self.subTest(responses=responses), + patch.object(bridge.action, "github_read", side_effect=responses), + patch.object(ingress, "jobs") as jobs, + patch.object(ingress, "service_bus") as bus, + ): + response = submit(self.request(token=java_token, payload=gradle_payload)) + self.assertEqual((response.status_code, json.loads(response.get_body())), expected) + jobs.assert_not_called() + bus.assert_not_called() + + # Release branch names with slashes are URL-encoded in the branch-protection read. + slash_payload = copy.deepcopy(gradle_payload) + slash_payload["metadata"]["base_ref"] = "release/1.0" + with ( + patch.object(bridge.action, "github_read", side_effect=[ + coordinator_info, + gradle_info | {"default_branch": "release/1.0"}, + {"name": "release/1.0", "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} + response = submit(self.request(token=java_token, payload=slash_payload)) + self.assertEqual(response.status_code, 202, response.get_body()) + self.assertEqual(github.call_args_list[-1].args[0], f"/repos/{GRADLE_REPOSITORY}/branches/release%2F1.0") + def test_enrolled_repo_submit_requires_public_repo_identity_and_current_protected_default(self): ingress, submit, status = self.load_ingress() token = self.java_token() @@ -646,6 +900,13 @@ def test_missing_protection_claim_does_not_admit_jobs_without_confirmed_protecti class BridgeConfigurationTests(unittest.TestCase): + def test_example_allowlist_enrolls_issuelens_and_all_java_tooling_repositories(self): + self.assertEqual(json.loads(ALLOWLIST_JSON), ENROLLED_REPOSITORY_IDS) + self.assertEqual( + bridge.load_repository_allowlist(ALLOWLIST_JSON, PILOT_REPOSITORY_ID), + frozenset(ENROLLED_REPOSITORY_IDS), + ) + def test_invalid_id_allowlist_is_rejected_as_a_whole(self): original = ALLOWLIST_JSON ids = json.loads(original) @@ -951,6 +1212,49 @@ def test_worker_uses_the_existing_foundry_api_for_issue_and_wiki_jobs(self): github.assert_not_called() self.credential.get_token.assert_called_with("https://ai.azure.com/.default") + def test_worker_validates_coordinator_and_wiki_repository_for_cross_repo_team_memory_jobs(self): + cross_repo_metadata = { + "repository": GRADLE_REPOSITORY, "repository_id": GRADLE_REPOSITORY_ID, "base_ref": "develop", + "event_name": "workflow_dispatch", "pull_number": 18, "merge_commit_sha": "a" * 40, + "coordinator_repository": JAVA_REPOSITORY, "required_wiki_repository": JAVA_REPOSITORY, + } + cross_job = { + "repository": JAVA_REPOSITORY, + "payload": json.dumps({"request_type": "team-memory", "metadata": cross_repo_metadata}), + } + request = self.worker.prepare(cross_job) + self.assertEqual(json.loads(request.data), bridge.action.build_team_memory_request(cross_repo_metadata)) + for invalid_job in ( + cross_job | {"repository": GRADLE_REPOSITORY}, + cross_job | {"repository": PILOT_REPOSITORY}, + { + "repository": JAVA_REPOSITORY, + "payload": json.dumps({ + "request_type": "team-memory", + "metadata": cross_repo_metadata | {"required_wiki_repository": GRADLE_REPOSITORY}, + }), + }, + { + "repository": JAVA_REPOSITORY, + "payload": json.dumps({ + "request_type": "team-memory", + "metadata": cross_repo_metadata | {"repository": PILOT_REPOSITORY}, + }), + }, + { + "repository": PILOT_REPOSITORY, + "payload": json.dumps({ + "request_type": "team-memory", + "metadata": cross_repo_metadata | { + "coordinator_repository": PILOT_REPOSITORY, + "required_wiki_repository": PILOT_REPOSITORY, + }, + }), + }, + ): + with self.subTest(job=invalid_job), self.assertRaisesRegex(ValueError, "Bridge job repository mismatch"): + self.worker.prepare(invalid_job) + def test_worker_verifies_created_comment_without_forwarding_body_or_digest(self): payload = issue_payload() with patch.dict(os.environ, {"GH_TOKEN": "do-not-forward"}), \