From 79933900a21c7fc86956d82524fbcdb8898eee9f Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Tue, 24 Nov 2026 13:04:34 +0800 Subject: [PATCH 1/2] Route IssueLens workflows through an Azure Function bridge Authenticate the opt-in issue and team-memory workflows at the bridge and invoke the existing Foundry API with managed identity. Keep the agent runtime and direct callers unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .agentignore | 1 + .dockerignore | 1 + .github/actions/issuelens/README.md | 36 +- .github/actions/issuelens/action.yml | 34 +- .github/actions/issuelens/issuelens_action.py | 168 +++++++- .github/copilot-instructions.md | 39 +- .github/workflows/ci.yml | 5 +- .github/workflows/issue-triage.yml | 26 +- .github/workflows/team-memory-coordinator.yml | 11 +- CONTRIBUTING.md | 8 +- automation_bridge/bridge.py | 381 ++++++++++++++++++ automation_bridge/bundle.py | 25 ++ automation_bridge/function_app.py | 130 ++++++ automation_bridge/host.json | 14 + automation_bridge/requirements.txt | 5 + docs/guide.md | 130 ++++-- tests/test_automation_bridge.py | 348 ++++++++++++++++ tests/test_ci_workflow.py | 7 +- tests/test_deploy_foundry_workflow.py | 3 +- tests/test_issue_triage_workflow.py | 12 +- tests/test_team_memory_coordinator.py | 25 +- tests/test_team_memory_workflow.py | 18 +- 22 files changed, 1293 insertions(+), 134 deletions(-) create mode 100644 automation_bridge/bridge.py create mode 100644 automation_bridge/bundle.py create mode 100644 automation_bridge/function_app.py create mode 100644 automation_bridge/host.json create mode 100644 automation_bridge/requirements.txt create mode 100644 tests/test_automation_bridge.py diff --git a/.agentignore b/.agentignore index c695d9f..1260f0a 100644 --- a/.agentignore +++ b/.agentignore @@ -30,5 +30,6 @@ Dockerfile # Separate transports / CI assets, not part of the agent runtime webhook_bridge/ +automation_bridge/ templates/ deck/ diff --git a/.dockerignore b/.dockerignore index d157a10..7533c38 100644 --- a/.dockerignore +++ b/.dockerignore @@ -31,3 +31,4 @@ README.md # The webhook bridge is a separate deployable (Azure Function), not part of the agent image. webhook_bridge/ +automation_bridge/ diff --git a/.github/actions/issuelens/README.md b/.github/actions/issuelens/README.md index d8128ef..50b23ca 100644 --- a/.github/actions/issuelens/README.md +++ b/.github/actions/issuelens/README.md @@ -1,9 +1,9 @@ # IssueLens Action A reusable composite action for issue-loop, team-memory, and explicit tasks. -It prepares and validates the request, authenticates to an existing IssueLens -agent with Azure OIDC, and invokes it through a shared bounded HTTP/SSE client. -It is a client of the agent, not part of the hosted agent runtime. +It prepares and validates the request. Existing external callers use the +`foundry` transport; the IssueLens repository's pilot uses the `bridge` transport. +The action is a client, not part of the hosted agent runtime. The hosted invocation profile is public-only: private/internal repository reads and private wiki destinations are rejected, even when the App has access. @@ -12,7 +12,7 @@ authenticated, read-only maintainer chat; no internal report is returned to this action. Inputs and Actions display modes must be appropriate for the workflow's audience. -The normal path prepares the request, logs in with the pinned `azure/login` +The direct path prepares the request, logs in with the pinned `azure/login` action, and submits the request. Coordinated team-memory inputs select a bounded reconciliation range; source/run validation, ancestry checks, and complete paginated commit discovery all happen inside preflight before Azure login. @@ -21,6 +21,14 @@ owns metadata validation, the caller's task text, bounded HTTP/SSE processing, 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. +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 +raw agent output; the runner's issue-loop response file is a completion notice. + ## Request Types | `request-type` | Preparation | Result | @@ -30,7 +38,7 @@ GitHub App private key is required. | `task` | Require explicit non-empty `input`, bounded to 64 KiB UTF-8. No issue-loop event metadata or maintainer-command authority is synthesized. | A completed root agent response in the requested format. | All request types validate the caller repository identity and that the caller -workflow runs from its current default branch before Azure login. Unknown request +workflow runs from its current default branch before authenticating. Unknown request types, malformed inputs, and an `input` supplied to an event adapter fail closed. Event adapters prepare context, not a role assignment: the agent owns routing, command validation, and task-specific write authorization. In particular there @@ -156,7 +164,7 @@ claimed because no artifact is used. Automatic pushes and manual PR requests share the fixed `issuelens-team-memory-wiki-microsoft-IssueLens` concurrency group, with `queue: max` and `cancel-in-progress: false`. The slot covers the complete -coordinator run, including discovery, Azure OIDC login, the one agent invocation, +coordinator run, including discovery, bridge admission, the one agent invocation, and final result validation. GitHub retains up to 100 pending runs; further runs are canceled when that queue is full. Monitor canceled/failed runs. Dispatch acknowledgement means GitHub accepted the request, not that @@ -367,19 +375,21 @@ 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. | -| `azure-client-id` | Yes | Existing Azure OIDC identity's client ID. | -| `azure-tenant-id` | Yes | Tenant used by Azure login. | -| `azure-subscription-id` | Yes | Subscription used by Azure login. | -| `agent-url` | Yes | Complete HTTPS Foundry invocations endpoint, including its API version query. | -| `agent-scope` | Yes | Entra scope for that endpoint. | +| `transport` | No | `foundry` (default for existing callers) or `bridge` (IssueLens pilot only). | +| `bridge-url` | For `bridge` | Complete approved HTTPS Azure Function jobs endpoint. | +| `azure-client-id` | For `foundry` | Existing Azure OIDC identity's client ID. | +| `azure-tenant-id` | For `foundry` | Tenant used by Azure login. | +| `azure-subscription-id` | For `foundry` | Subscription used by Azure login. | +| `agent-url` | For `foundry` | Complete HTTPS Foundry invocations endpoint, including its API version query. | +| `agent-scope` | For `foundry` | Entra scope for that endpoint. | | `output-mode` | No | `hybrid` (default): live agent text plus activity; `activity`: statuses only; `quiet`: no live event display. | | `summary-mode` | No | `full` (default): status/metrics and final answer; `status`: status/metrics only; `none`: do not write a job summary. | | Output | Meaning | | --- | --- | | `status` | `skipped` for ineligible events; `completed` for issue-loop/task streams; `updated`/`no-change` for complete maintenance. Validated push batches also expose `partial`, `needs-review`, or `failed` before failing the step. Unavailable for invalid/ambiguous results. | -| `skip-reason` | Fixed reason for an event skipped before Azure login. | -| `response-path` | Unique runner-local UTF-8 final root answer for `issue-loop`/`task`, or the complete validated push-batch JSON receipt, including incomplete batches. | +| `skip-reason` | Fixed reason for an event skipped before authentication to the invocation transport. | +| `response-path` | Unique runner-local UTF-8 final root answer for direct `issue-loop`/`task`, completion notice for a bridge issue-loop job, or the complete validated push-batch JSON receipt, including incomplete batches. | | `wiki-repository` | Reported verified wiki identity from a validated maintenance result, when available. Partial does not imply no publication. | | `wiki-sha` | Full reported tool-confirmed publication or snapshot SHA, when available in the validated maintenance result. | diff --git a/.github/actions/issuelens/action.yml b/.github/actions/issuelens/action.yml index 7fa0ae5..5b46d25 100644 --- a/.github/actions/issuelens/action.yml +++ b/.github/actions/issuelens/action.yml @@ -53,21 +53,29 @@ inputs: description: Full nonzero source run head SHA ending the requested reconciliation range. required: false default: '' + transport: + description: Use foundry for direct Azure OIDC (legacy callers) or bridge for authenticated workflow jobs. + required: false + default: foundry + bridge-url: + description: Full HTTPS Azure Function jobs endpoint for the bridge transport. + required: false + default: '' azure-client-id: - description: Client ID of the existing Azure OIDC identity. - required: true + description: Client ID of the Azure OIDC identity for the foundry transport. + required: false azure-tenant-id: - description: Azure tenant ID for the OIDC identity. - required: true + description: Azure tenant ID for the foundry transport. + required: false azure-subscription-id: - description: Azure subscription ID for the OIDC login. - required: true + description: Azure subscription ID for the foundry transport. + required: false agent-url: - description: Full HTTPS Foundry invocations endpoint. - required: true + description: Full HTTPS Foundry invocations endpoint for the foundry transport. + required: false agent-scope: - description: Entra scope used to acquire the endpoint access token. - required: true + description: Entra scope used to acquire the foundry transport's endpoint access token. + required: false output-mode: description: Live log mode (hybrid includes agent text, activity shows statuses only, quiet disables stream display). required: false @@ -120,12 +128,14 @@ runs: SOURCE_RUN_ATTEMPT: ${{ inputs.source-run-attempt }} PUSH_BEFORE: ${{ inputs.push-before }} PUSH_AFTER: ${{ inputs.push-after }} + TRANSPORT: ${{ inputs.transport }} + BRIDGE_URL: ${{ inputs.bridge-url }} OUTPUT_MODE: ${{ inputs.output-mode }} SUMMARY_MODE: ${{ inputs.summary-mode }} run: python3 -I "$GITHUB_ACTION_PATH/issuelens_action.py" preflight - name: Azure login (OIDC) for the agent endpoint - if: steps.preflight.outputs.eligible == 'true' + if: steps.preflight.outputs.eligible == 'true' && inputs.transport == 'foundry' uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3.0.2 with: client-id: ${{ inputs.azure-client-id }} @@ -139,6 +149,8 @@ runs: env: GITHUB_ACTION_PATH: ${{ github.action_path }} REQUEST_PATH: ${{ steps.preflight.outputs.request-path }} + TRANSPORT: ${{ inputs.transport }} + BRIDGE_URL: ${{ inputs.bridge-url }} AGENT_URL: ${{ inputs.agent-url }} AGENT_SCOPE: ${{ inputs.agent-scope }} OUTPUT_MODE: ${{ inputs.output-mode }} diff --git a/.github/actions/issuelens/issuelens_action.py b/.github/actions/issuelens/issuelens_action.py index c69e654..e9fdba3 100644 --- a/.github/actions/issuelens/issuelens_action.py +++ b/.github/actions/issuelens/issuelens_action.py @@ -1,6 +1,7 @@ """GitHub Actions client for IssueLens issue-loop, maintenance, and direct tasks.""" import argparse +import hashlib import importlib.util import json import os @@ -8,6 +9,7 @@ import subprocess import tempfile import time +import urllib.error import urllib.parse import urllib.request from pathlib import Path @@ -24,6 +26,9 @@ DISCOVERY_SECONDS = 180 AGENT_STREAM_INACTIVITY_TIMEOUT_SECONDS = 300 AGENT_STREAM_READ_BUDGET_SECONDS = 1800 +BRIDGE_POLL_SECONDS = 10 +BRIDGE_WAIT_SECONDS = 35 * 60 +BRIDGE_JOBS_PATH = "/api/issuelens/v1/jobs" ASSOCIATION_BATCH_SIZE = 20 COORDINATOR_REPOSITORY = "microsoft/IssueLens" DISPATCH_WORKFLOW = ".github/workflows/team-memory-post-merge.yml" @@ -67,15 +72,19 @@ def full_sha(value): def github_request(path, payload=None, *, token=None): + headers = { + "Accept": "application/vnd.github+json", + "Content-Type": "application/json", + "X-GitHub-Api-Version": "2022-11-28", + } + if token == "": + headers["Cache-Control"] = "no-cache" + else: + headers["Authorization"] = "Bearer " + (os.environ["GH_TOKEN"] if token is None else token) return urllib.request.Request( "https://api.github.com" + path, data=None if payload is None else json.dumps(payload).encode("utf-8"), - headers={ - "Authorization": "Bearer " + (os.environ["GH_TOKEN"] if token is None else token), - "Accept": "application/vnd.github+json", - "Content-Type": "application/json", - "X-GitHub-Api-Version": "2022-11-28", - }, + headers=headers, ) @@ -618,12 +627,21 @@ def prepare_issue_loop(repository, event): "comment_edited": event_name == "issue_comment" and event_action == "edited", "manual_dispatch": event_name == "workflow_dispatch", } + request = build_issue_loop_request(metadata) + if os.environ.get("TRANSPORT") == "bridge" and metadata["comment_added"]: + body = comment.get("body") + require(isinstance(body, str), "Created comment has no authoritative revision in the event") + metadata["comment_sha256"] = hashlib.sha256(body.encode("utf-8")).hexdigest() + return {"metadata": metadata, "request": request} + + +def build_issue_loop_request(metadata): task = ( - f"Process the trusted IssueLens issue-loop event for {repository}#{number} " + f"Process the trusted IssueLens issue-loop event for {metadata['repository']}#{metadata['issue_number']} " "under the global built-in command and trusted issue-loop contracts. " "Trusted event metadata: " + json.dumps(metadata, separators=(",", ":")) ) - return {"metadata": metadata, "request": {"input": task}} + return {"input": task} def prepare_task(repository, event): @@ -643,6 +661,12 @@ def preflight(): display_options() request_type = os.environ.get("REQUEST_TYPE", "") require(request_type in REQUEST_TYPES, "Choose request-type issue-loop, team-memory, or task") + if transport() == "bridge": + bridge_url() + require(request_type in {"issue-loop", "team-memory"} + and (request_type != "team-memory" or os.environ.get("GITHUB_WORKFLOW_REF", "").endswith( + "/" + COORDINATOR_WORKFLOW + "@refs/heads/main")), + "Bridge transport supports issue-loop and the IssueLens team-memory coordinator only") require(request_type == "team-memory" or not any(os.environ.get(name, "") for name in (*SOURCE_INPUTS, "SOURCE_REPOSITORY")), "Source identifiers are supported only for team-memory coordinator requests") @@ -800,8 +824,105 @@ def save_response(text): return response_path -def submit(): - output_mode, summary_mode = display_options() +def transport(): + mode = os.environ.get("TRANSPORT", "foundry") + require(mode in {"foundry", "bridge"}, "Choose transport foundry or bridge") + require(mode != "foundry" or not os.environ.get("BRIDGE_URL"), + "bridge-url requires transport: bridge") + return mode + + +def bridge_url(): + url = os.environ.get("BRIDGE_URL", "") + parsed = urllib.parse.urlsplit(url) + require(parsed.scheme == "https" + and re.fullmatch(r"[a-z0-9][a-z0-9-]*(?:\.[a-z0-9-]+)?\.azurewebsites\.net", parsed.netloc) + and parsed.path == BRIDGE_JOBS_PATH and not parsed.query and not parsed.fragment + and url == f"https://{parsed.netloc}{BRIDGE_JOBS_PATH}", + "Configure the full HTTPS Azure Function jobs endpoint for bridge-url") + return url + + +def bridge_json(url, token, body=None): + request = urllib.request.Request( + url, data=None if body is None else json.dumps(body).encode("utf-8"), + headers={"Authorization": "Bearer " + token, "Accept": "application/json", + "Content-Type": "application/json"}, + ) + with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response: + require(response.headers.get_content_type() == "application/json", "Expected a JSON bridge response") + data = response.read(128 * 1024 + 1) + require(len(data) <= 128 * 1024, "Bridge response exceeds the size limit") + try: + result = json.loads(data, object_pairs_hook=unique_object) + except (UnicodeError, ValueError): + raise ValueError("Invalid bridge JSON response") from None + require(isinstance(result, dict), "Invalid bridge JSON response") + return result + + +def workflow_token(audience): + parsed = urllib.parse.urlsplit(os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL", "")) + require(parsed.scheme == "https" and parsed.hostname is not None + and re.fullmatch(r"[a-z0-9.-]+\.actions\.githubusercontent\.com", parsed.hostname) + and parsed.username is None and parsed.password is None and parsed.port in {443, None} + and not parsed.fragment, "GitHub Actions OIDC endpoint unavailable; grant id-token: write") + credential = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "") + require(credential and not any(char.isspace() for char in credential), + "GitHub Actions OIDC credential unavailable; grant id-token: write") + query = [(key, value) for key, value in urllib.parse.parse_qsl(parsed.query) if key != "audience"] + query.append(("audience", audience)) + url = parsed._replace(query=urllib.parse.urlencode(query)).geturl() + value = bridge_json(url, credential).get("value") + require(isinstance(value, str) and 0 < len(value) <= 16 * 1024 + and re.fullmatch(r"[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+){2}", value), + "GitHub returned an invalid workflow identity token") + return value + + +def submit_bridge(envelope): + url = bridge_url() + request_type = envelope["request_type"] + require(request_type in {"issue-loop", "team-memory"}, "Unsupported bridge request type") + token = workflow_token(url) + refreshed_at = time.monotonic() + try: + receipt = bridge_json(url, token, {"request_type": request_type, "metadata": envelope["metadata"]}) + except urllib.error.HTTPError as error: + messages = { + 400: "Bridge rejected the prepared workflow job", + 401: "Bridge did not authorize this workflow identity", + 409: "Another job owns the target; reconcile its outcome before retrying", + } + raise ValueError(messages.get( + error.code, "Bridge submission was not confirmed; inspect the job before retrying", + )) from None + job = receipt.get("job_id") + require(isinstance(job, str) and re.fullmatch(r"[0-9a-f]{64}", job), "Invalid bridge job ID") + display_log(f"IssueLens bridge job: {job}") + deadline = time.monotonic() + BRIDGE_WAIT_SECONDS + while True: + require(receipt.get("job_id") == job, "Bridge receipt does not match the submitted job") + state = receipt.get("state") + if state == "completed": + if request_type == "team-memory": + require(isinstance(receipt.get("result"), dict), "Missing team-memory receipt") + return json.dumps(receipt["result"], ensure_ascii=False) + return "IssueLens completed the issue-loop session. Inspect GitHub for any changes." + if state == "failed": + raise ValueError("Bridge job was rejected before a model session started") + if state == "unknown": + raise ValueError("Bridge job outcome is unknown; inspect the target before retrying") + require(state in {"queued", "running"}, "Invalid bridge job state") + require(time.monotonic() < deadline, "Bridge wait expired; inspect the submitted job before retrying") + time.sleep(BRIDGE_POLL_SECONDS) + if time.monotonic() - refreshed_at >= 120: + token = workflow_token(url) + refreshed_at = time.monotonic() + receipt = bridge_json(f"{url}/{job}", token) + + +def foundry_request(envelope, output_mode): url = os.environ["AGENT_URL"] parsed = urllib.parse.urlsplit(url) require(parsed.scheme == "https" and parsed.hostname @@ -812,10 +933,6 @@ def submit(): "Configure a full HTTPS Foundry invocations endpoint") scope = os.environ["AGENT_SCOPE"] require(scope and not any(char.isspace() for char in scope), "Configure ISSUELENS_AGENT_SCOPE") - envelope = json.loads(Path(os.environ["REQUEST_PATH"]).read_text(encoding="utf-8")) - metadata = envelope["metadata"] - request_type = envelope.get("request_type") - require(request_type in REQUEST_TYPES, "Invalid prepared request type") token = subprocess.check_output( ["az", "account", "get-access-token", "--scope", scope, "--query", "accessToken", "-o", "tsv"], text=True, stderr=subprocess.PIPE, timeout=60, @@ -830,10 +947,27 @@ def submit(): "Content-Type": "application/json", "Accept": "text/event-stream"}, method="POST", ) + return request, renderer + + +def submit(): + output_mode, summary_mode = display_options() + envelope = json.loads(Path(os.environ["REQUEST_PATH"]).read_text(encoding="utf-8")) + metadata = envelope["metadata"] + request_type = envelope.get("request_type") + require(request_type in REQUEST_TYPES, "Invalid prepared request type") + bridge = transport() == "bridge" + if bridge: + renderer = StreamRenderer(mode="quiet", secrets=(os.environ.get("BRIDGE_URL", ""),)) + else: + request, renderer = foundry_request(envelope, output_mode) try: - with urllib.request.build_opener(NoRedirect()).open( - request, timeout=AGENT_STREAM_INACTIVITY_TIMEOUT_SECONDS) as response: - text = read_response(response, renderer) + if bridge: + text = submit_bridge(envelope) + else: + with urllib.request.build_opener(NoRedirect()).open( + request, timeout=AGENT_STREAM_INACTIVITY_TIMEOUT_SECONDS) as response: + text = read_response(response, renderer) result = None if request_type == "team-memory": result = json.loads(text, object_pairs_hook=unique_object) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 726df27..a28d77f 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -314,18 +314,25 @@ agent's role or tool restrictions to repository contributors. The agent is driven by a workflow in the target repo (`.github/workflows/issue-triage.yml`): -1. Authenticate to the Foundry agent endpoint via **Azure OIDC** (`azure/login`). -2. POST `{ input, attachments? }` to the agent's invocations endpoint. The - hosted agent owns the App credentials; target repositories do not store the - App private key or mint tokens. +1. The opted-in `microsoft/IssueLens` caller submits typed metadata to the + 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. +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 + deployable and serves authorized direct callers as before. Only the hosted + agent owns the App credentials and performs GitHub writes. Both issue-loop and team-memory workflows use `.github/actions/issuelens`. Its `request-type` selects `issue-loop`, `team-memory`, or a direct `task` with -explicit `input`. Request adapters validate before shared OIDC login and one -bounded invocation. The action does not choose sub-agents or parse commands. +explicit `input`. Request adapters validate before authenticating to either +the pilot bridge or the legacy direct transport. The action does not choose +sub-agents or parse commands. The event adapter omits issue/comment bodies; direct tasks never synthesize trusted event provenance. Generic final answers are saved in a runner-local -`response-path`: `completed` means stream completion, not successful writes. +`response-path` on the direct transport; bridge issue jobs return a completion +notice. `completed` means stream completion, not successful writes. Only team-memory results require the wiki-specific structured result contract. The action's `output-mode` selects hybrid live text/activity, activity-only, or quiet display; `summary-mode` selects full, status-only, or no job summary. @@ -336,7 +343,7 @@ Callers must choose privacy-appropriate modes for their Actions audience. Triggers: `issues` opened/reopened, `issue_comment` created/edited for issues only, and `workflow_dispatch`. The workflow does not subscribe to issue edits or pull request comments. A preflight step rejects PR-backed and bot-authored -comments before Azure login, then sends a neutral orchestration task with +comments before authenticating to the bridge, then sends neutral trusted event metadata. Per-issue concurrency allows different issues to run independently while coalescing bursts for the same issue. @@ -359,7 +366,7 @@ Target inputs and credentials grant no new access. The central coordinator owns the actual concurrency queue and only calls `.github/actions/issuelens` after trusted sparse checkout. The invocation action owns source/workflow validation, current default-branch ancestry, full paginated -range/PR discovery before OIDC login, policy/privacy, and final outcomes. +range/PR discovery before bridge admission, policy/privacy, and final outcomes. The trusted coordinator workflow may configure `source-repositories`, a bounded canonical-name-to-numeric-ID JSON map; never populate it from dispatch inputs. Cross-repository sources and coordinators must both be public. @@ -381,12 +388,12 @@ final source at pinned SHAs. Missing required evidence remains non-success; neither an optional bulk-read limit nor preflight success establishes publication. Explicit single-PR manual requests use the coordinator instead of source IDs. The shared composite action in `.github/actions/issuelens` -owns preflight, pinned Azure OIDC login, and submission through a standalone +owns preflight and both transports through a standalone Python helper. External callers pin an action commit and need no checkout; this repository's thin caller sparsely loads the local action from the trusted `github.workflow_sha`, never a PR head, with credentials not persisted. The -action checks authoritative GitHub metadata before OIDC login and submits a -bounded wiki-only job using the issue-loop secrets. For a push, it verifies the +action checks authoritative GitHub metadata before submitting a bounded +wiki-only job to the bridge. For a push, it verifies the complete fast-forward commit inventory and discovers all eligible merged PRs using bounded GitHub metadata reads before submitting one batch. It fails on incomplete discovery rather than silently omitting sources. IssueLens automatic @@ -400,9 +407,8 @@ unchanged and will need authenticated cross-repository dispatch and a separate queue for their shared `microsoft/vscode-java-pack` wiki. 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. -Verify default-branch Azure OIDC federation when migrating from a PR-scoped subject. -Enable it with the repository -variable `ISSUELENS_TEAM_MEMORY_ENABLED=true`, not an agent environment flag. +The manual pilot uses `ISSUELENS_TEAM_MEMORY_MANUAL_PILOT=true` after bridge +setup and approval. `ISSUELENS_TEAM_MEMORY_ENABLED=true` also enables pushes. The workflow explicitly requests merge revalidation, wiki-only writes, no reactions/comments, and a JSON result through its `input`. The generic agent preserves wiki policy/privacy/preconditions and the requested response format; @@ -415,7 +421,8 @@ retaining its per-PR response and any confirmed wiki publication, never implying that no write occurred. The batch schema remains caller-owned. Ambiguous agent submissions and workflow dispatches are not retried automatically. A timeout or cancellation does not prove the hosted invocation -stopped; the queue is not a distributed runtime lock. Monitor overflow +stopped. The bridge keeps its durable reservation until settlement or operator +reconciliation; the GitHub queue alone is not a distributed lock. Monitor overflow and failed/canceled runs. Git provides knowledge, history, and conflict detection, not a durable job queue or guaranteed exactly-once delivery. Local tests do not establish live OIDC federation, hosted writer dispatch, or publication. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e3a038..c7be7e4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,12 +31,13 @@ jobs: cache: pip cache-dependency-path: | requirements.txt + automation_bridge/requirements.txt requirements-ci.txt constraints-ci.txt - name: Install application and test dependencies - run: python -m pip install -r requirements.txt -r requirements-ci.txt + run: python -m pip install -r requirements.txt -r automation_bridge/requirements.txt -r requirements-ci.txt - name: Validate Python syntax - run: python -m compileall -q *.py .github/actions/issuelens .github/actions/queue-team-memory github_app_mcp/src github_app_mcp/scripts tests github_app_mcp/tests + run: python -m compileall -q *.py automation_bridge .github/actions/issuelens .github/actions/queue-team-memory github_app_mcp/src github_app_mcp/scripts tests github_app_mcp/tests - name: Run application tests run: python -m unittest discover -s tests -p 'test_*.py' -v diff --git a/.github/workflows/issue-triage.yml b/.github/workflows/issue-triage.yml index ceac31b..132110d 100644 --- a/.github/workflows/issue-triage.yml +++ b/.github/workflows/issue-triage.yml @@ -5,18 +5,10 @@ # .github/actions/issuelens/README.md. Repository policy belongs in # .github/issuelens.yml, not in this workflow. # -# One-time setup in the repository (or organization, shared to selected repos): -# Secrets (Settings -> Secrets and variables -> Actions -> Secrets): -# AZURE_CLIENT_ID Client ID of the OIDC identity (UAMI or app reg) -# AZURE_TENANT_ID -# AZURE_SUBSCRIPTION_ID -# ISSUELENS_AGENT_URL Full deployed invocations endpoint -# (.../protocols/invocations?api-version=...) -# ISSUELENS_AGENT_SCOPE Entra scope/resource for the endpoint token -# -# The hosted agent owns its Key Vault-backed GitHub App identity and mints -# repository-scoped tokens internally. Target repositories store no App private -# key. Agent endpoint access uses Azure OIDC. +# After the isolated Function bridge is approved, set the ISSUELENS_BRIDGE_URL +# repository variable and opt in with ISSUELENS_ISSUE_LOOP_ENABLED=true. +# This workflow authenticates only to the bridge. The worker's Azure identity +# invokes Foundry; the hosted agent still owns all GitHub App writes. name: IssueLens issue loop @@ -43,6 +35,9 @@ concurrency: jobs: orchestrate: if: >- + vars.ISSUELENS_ISSUE_LOOP_ENABLED == 'true' && + vars.ISSUELENS_BRIDGE_URL != '' && + github.repository == 'microsoft/IssueLens' && (github.event_name != 'issue_comment' || (github.event.issue.pull_request == null && github.event.sender.type == 'User' && github.event.comment.user.type == 'User')) && @@ -68,8 +63,5 @@ jobs: with: request-type: issue-loop issue-number: ${{ inputs.issue_number }} - azure-client-id: ${{ secrets.AZURE_CLIENT_ID }} - azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }} - azure-subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} - agent-url: ${{ secrets.ISSUELENS_AGENT_URL }} - agent-scope: ${{ secrets.ISSUELENS_AGENT_SCOPE }} \ No newline at end of file + transport: bridge + bridge-url: ${{ vars.ISSUELENS_BRIDGE_URL }} \ No newline at end of file diff --git a/.github/workflows/team-memory-coordinator.yml b/.github/workflows/team-memory-coordinator.yml index 597232b..c0c7b77 100644 --- a/.github/workflows/team-memory-coordinator.yml +++ b/.github/workflows/team-memory-coordinator.yml @@ -38,7 +38,9 @@ permissions: {} jobs: reconcile: if: >- - vars.ISSUELENS_TEAM_MEMORY_ENABLED == 'true' && + (vars.ISSUELENS_TEAM_MEMORY_ENABLED == 'true' || + (vars.ISSUELENS_TEAM_MEMORY_MANUAL_PILOT == 'true' && inputs.pull_request_number != '')) && + vars.ISSUELENS_BRIDGE_URL != '' && github.repository == 'microsoft/IssueLens' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && github.event_name == 'workflow_dispatch' @@ -68,8 +70,5 @@ jobs: push-before: ${{ inputs.push_before }} push-after: ${{ inputs.push_after }} pull-request-number: ${{ inputs.pull_request_number }} - azure-client-id: ${{ secrets.AZURE_CLIENT_ID }} - azure-tenant-id: ${{ secrets.AZURE_TENANT_ID }} - azure-subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} - agent-url: ${{ secrets.ISSUELENS_AGENT_URL }} - agent-scope: ${{ secrets.ISSUELENS_AGENT_SCOPE }} + transport: bridge + bridge-url: ${{ vars.ISSUELENS_BRIDGE_URL }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 459ff81..be819c5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,7 +24,7 @@ Run commands from the repository root. In Bash: ```bash python3.13 -m venv .venv source .venv/bin/activate -python -m pip install -r requirements.txt -r requirements-ci.txt +python -m pip install -r requirements.txt -r automation_bridge/requirements.txt -r requirements-ci.txt ``` Or in PowerShell: @@ -32,7 +32,7 @@ Or in PowerShell: ```powershell py -3.13 -m venv .venv .\.venv\Scripts\Activate.ps1 -python -m pip install -r requirements.txt -r requirements-ci.txt +python -m pip install -r requirements.txt -r automation_bridge/requirements.txt -r requirements-ci.txt ``` **You do not need a `.env` file, Azure credentials, a GitHub App, or a live model @@ -115,7 +115,7 @@ python -m unittest discover -s tests -p 'test_issue_triage_workflow.py' -v The complete application checks are: ```bash -python -m compileall -q *.py .github/actions/issuelens .github/actions/queue-team-memory github_app_mcp/src github_app_mcp/scripts tests github_app_mcp/tests +python -m compileall -q *.py automation_bridge .github/actions/issuelens .github/actions/queue-team-memory github_app_mcp/src github_app_mcp/scripts tests github_app_mcp/tests python -m unittest discover -s tests -p 'test_*.py' -v ``` @@ -124,7 +124,7 @@ Python files explicitly: ```powershell $rootModules = Get-ChildItem -File -Filter *.py | Select-Object -ExpandProperty Name -python -m compileall -q $rootModules .github\actions\issuelens .github\actions\queue-team-memory github_app_mcp\src github_app_mcp\scripts tests github_app_mcp\tests +python -m compileall -q $rootModules automation_bridge .github\actions\issuelens .github\actions\queue-team-memory github_app_mcp\src github_app_mcp\scripts tests github_app_mcp\tests ``` ### Standalone MCP tests and package checks diff --git a/automation_bridge/bridge.py b/automation_bridge/bridge.py new file mode 100644 index 0000000..9b04ebc --- /dev/null +++ b/automation_bridge/bridge.py @@ -0,0 +1,381 @@ +"""Authenticate workflow jobs and hold the target reservation through settlement.""" + +import hashlib +import http.client +import importlib.util +import json +import re +import time +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +import jwt +from azure.core import MatchConditions +from azure.core.exceptions import AzureError, ResourceModifiedError, ResourceNotFoundError +from azure.data.tables import TableClient, TableTransactionError, UpdateMode +from azure.identity import ManagedIdentityCredential + +_action_path = Path(__file__).with_name("issuelens_action.py") +if not _action_path.is_file(): + _action_path = Path(__file__).parent.parent / ".github" / "actions" / "issuelens" / _action_path.name +_spec = importlib.util.spec_from_file_location("issuelens_bridge_action", _action_path) +assert _spec is not None and _spec.loader is not None +action = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(action) + +PILOT_REPOSITORY = action.COORDINATOR_REPOSITORY +BRANCH = "refs/heads/main" +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}") +QUEUED, RUNNING, COMPLETED, FAILED, UNKNOWN = "queued", "running", "completed", "failed", "unknown" +PARTITION = "issuelens-pilot" +MAX_QUEUE_AGE_SECONDS = 600 +MAX_REQUEST = 32 * 1024 +MAX_RESULT = 60 * 1024 +require = action.require + + +class BusyError(Exception): + """A different job still owns the target reservation.""" + + +def workflow_claims(token: str, audience: str, repository_id: int) -> dict: + require(len(token) <= 16 * 1024, "Invalid workflow token size") + key = KEYS.get_signing_key_from_jwt(token) + claims = jwt.decode( + token, key.key, algorithms=["RS256"], issuer=GITHUB_ISSUER, audience=audience, + options={"require": [ + "iss", "aud", "exp", "nbf", "iat", "repository", "repository_id", "repository_visibility", + "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) + and claims["repository_visibility"] == "public" + and claims["ref"] == BRANCH + and claims.get("ref_protected") in {"true", True} + and claims.get("runner_environment") == "github-hosted", + "Workflow is not in the protected IssueLens pilot scope") + 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") + + +def workflow_ref(path: str) -> str: + return f"{PILOT_REPOSITORY}/{path}@{BRANCH}" + + +def job_id(claims: dict) -> str: + return hashlib.sha256( + f"v1:{claims['repository_id']}:{claims['kind']}:{claims['run_id']}".encode("ascii") + ).hexdigest() + + +def _login(value): + return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9-]{1,100}(?:\[bot\])?", value) + + +def _association(value): + return value is None or isinstance(value, str) and value in { + "OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR", "FIRST_TIMER", "FIRST_TIME_CONTRIBUTOR", "NONE", "MANNEQUIN", + } + + +def _positive_int(value): + require(type(value) is int, "Expected a numeric identifier") + return action.positive(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") + comment_event = event == "issue_comment" + created = comment_event and operation == "created" + require(set(metadata) == { + "repository", "issue_number", "event_name", "event_action", "actor_login", "actor_type", + "issue_author_association", "comment_id", "comment_author_login", "comment_author_association", + "comment_added", "comment_edited", "manual_dispatch", + } | ({"comment_sha256"} if created else set()), "Unexpected issue-event fields") + require(_login(metadata["actor_login"]) and metadata["actor_login"] == claims["actor"] + and metadata["actor_type"] in ("User", "Bot", "Organization", "Mannequin") + and _association(metadata["issue_author_association"]) + and _association(metadata["comment_author_association"]) + and metadata["comment_added"] is created + and metadata["comment_edited"] is (comment_event and operation == "edited") + and metadata["manual_dispatch"] is (event == "workflow_dispatch"), "Invalid issue-event metadata") + if comment_event: + require(metadata["actor_type"] == "User" and _login(metadata["comment_author_login"]), + "Only human issue-comment events are allowed") + _positive_int(metadata["comment_id"]) + else: + require(all(metadata[field] is None for field in ( + "comment_id", "comment_author_login", "comment_author_association", + )), "Unexpected comment metadata") + if created: + require(metadata["comment_author_login"] == metadata["actor_login"] + and isinstance(metadata["comment_sha256"], str) and JOB_ID.fullmatch(metadata["comment_sha256"]), + "Created comment requires its revision digest") + return f"issue-{_positive_int(metadata['issue_number'])}" + + +_MERGE_FIELDS = {"pull_number", "merge_commit_sha", "merged_at", "source_identity"} + + +def _validate_merge(merge: dict): + 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}" + 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: + require(metadata.get("repository_id") == claims["repository_id"] + and metadata.get("base_ref") == "main" + and metadata.get("coordinator_repository") == PILOT_REPOSITORY + and metadata.get("required_wiki_repository") == PILOT_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"] + and metadata.get("coordinator_run_attempt") == claims["run_attempt"], + "Team-memory coordinator identity mismatch") + fields = { + "repository", "repository_id", "base_ref", "event_name", "event_action", + "actor_login", "triggering_actor", "workflow_ref", "workflow_sha", "run_id", "run_attempt", + "coordinator_repository", "coordinator_workflow_ref", "coordinator_workflow_sha", + "coordinator_run_id", "coordinator_run_attempt", "required_wiki_repository", + } + require(_login(metadata.get("actor_login")) and _login(metadata.get("triggering_actor")), + "Invalid team-memory actor metadata") + if metadata.get("event_name") == "push": + require(set(metadata) == fields | { + "range_origin", "push_before", "push_after", "source_tip_sha", "commit_count", + "pull_requests", "source_identity", + }, "Unexpected team-memory range fields") + 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["event_action"] == "push" and metadata["workflow_sha"] == after + and metadata["workflow_ref"] == workflow_ref(action.DISPATCH_WORKFLOW) + and _positive_int(metadata["commit_count"]) <= action.MAX_PUSH_COMMITS, + "Invalid reconciliation range metadata") + _positive_int(metadata["run_id"]) + _positive_int(metadata["run_attempt"]) + pulls = metadata["pull_requests"] + 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") + else: + require(set(metadata) == fields | _MERGE_FIELDS and metadata.get("event_name") == "workflow_dispatch" + and metadata.get("event_action") == "workflow_dispatch" + and metadata.get("actor_login") == claims["actor"] + 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) + 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") == PILOT_REPOSITORY, "Invalid workflow job") + validator = _issue_job if claims["kind"] == "issue-loop" else _memory_job + return validator(data["metadata"], claims) + + +class JobStore: + def __init__(self, table: TableClient): + self.table = table + + def get(self, identifier: str): + try: + return self.table.get_entity(PARTITION, identifier) + except ResourceNotFoundError: + return None + + def reserve(self, identifier: str, target: str, payload: bytes): + 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, + } + try: + self.table.submit_transaction([ + ("create", {"PartitionKey": PARTITION, "RowKey": f"lock-{target}", "job_id": identifier}), + ("create", job), + ]) + except TableTransactionError as error: + if error.status_code != 409: + raise + existing = self.get(identifier) + if existing is not None: + return existing + raise BusyError("The target has a pending or unresolved job") from None + return job + + @staticmethod + def _etag(job): + return {"etag": job.metadata["etag"], "match_condition": MatchConditions.IfNotModified, "mode": UpdateMode.REPLACE} + + def claim(self, job) -> bool: + try: + self.table.update_entity({**job, "state": RUNNING}, **self._etag(job)) + except ResourceModifiedError: + return False + return True + + def settle(self, job, state: str, result: bytes | None = None): + settled = {key: value for key, value in job.items() if key != "payload"} + settled["state"] = state + if result is not None: + settled["result"] = result + update = ("update", settled, self._etag(job)) + if state == UNKNOWN: + self.table.submit_transaction([update]) + else: + reservation = self.table.get_entity(PARTITION, f"lock-{job['target']}") + require(reservation["job_id"] == job["RowKey"], "Bridge job does not own its target reservation") + self.table.submit_transaction([ + update, ("delete", reservation, { + "etag": reservation.metadata["etag"], "match_condition": MatchConditions.IfNotModified, + }), + ]) + + +def receipt(job) -> dict: + value = {"job_id": job["RowKey"], "state": job["state"]} + if "result" in job: + value["result"] = json.loads(job["result"]) + return value + + +def _verify_created_comment(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="") + 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 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", + ) + + +class FoundryWorker: + def __init__(self, url: str, credential: ManagedIdentityCredential): + parsed = urllib.parse.urlsplit(url) + require(parsed.scheme == "https" + and re.fullmatch(r"[a-z0-9-]+\.services\.ai\.azure\.com", parsed.netloc) + and parsed.path.endswith("/protocols/invocations") and not parsed.fragment, + "Invalid bridge Foundry endpoint") + self.url = url + self.credential = credential + + def prepare(self, job) -> urllib.request.Request: + payload = json.loads(job["payload"]) + kind, metadata = payload["request_type"], payload["metadata"] + 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) + invocation = action.build_issue_loop_request(metadata) + elif kind == "team-memory": + invocation = action.build_team_memory_request(metadata) + else: + raise ValueError("Unsupported bridge job type") + token = self.credential.get_token("https://ai.azure.com/.default").token + return urllib.request.Request( + self.url, data=json.dumps(invocation).encode("utf-8"), + headers={"Authorization": "Bearer " + token, "Content-Type": "application/json", + "Accept": "text/event-stream"}, + method="POST", + ) + + def run(self, store: JobStore, identifier: str) -> str | None: + job = store.get(identifier) + if job is None or job["state"] != QUEUED or not store.claim(job): + return None + job = store.get(identifier) + if job is None or job["state"] != RUNNING: + raise RuntimeError("Bridge job claim was lost") + try: + require(time.time() - job["created"] <= MAX_QUEUE_AGE_SECONDS, "Bridge queue deadline expired") + request = self.prepare(job) + except (AzureError, OSError, http.client.HTTPException, ValueError): + store.settle(job, FAILED) + return FAILED + try: + with urllib.request.build_opener(action.NoRedirect()).open( + request, timeout=action.AGENT_STREAM_INACTIVITY_TIMEOUT_SECONDS, + ) as response: + text = action.read_response(response) + payload = json.loads(job["payload"]) + result = None + if payload["request_type"] == "team-memory": + result = _memory_receipt(text, payload["metadata"]) + except urllib.error.HTTPError as error: + if error.code in {400, 401, 403, 404, 422}: + store.settle(job, FAILED) + return FAILED + store.settle(job, UNKNOWN) + return UNKNOWN + except (OSError, http.client.HTTPException, TypeError, ValueError): + store.settle(job, UNKNOWN) + return UNKNOWN + store.settle(job, COMPLETED, result) + return COMPLETED + + +def _memory_receipt(text: str, metadata: dict) -> bytes: + parsed = json.loads(text, object_pairs_hook=action.unique_object) + require(isinstance(parsed, dict), "Invalid maintenance receipt") + action.validate_team_memory_result(parsed, metadata) + result = {key: parsed[key] for key in ("source_repository", "status", "wiki_repository", "wiki_sha")} + # Keep identifiers and status, not arbitrary model prose, in the durable store. + result["reason"] = f"Team-memory outcome: {parsed['status']}." + if metadata["event_name"] == "push": + result.update( + push_before=parsed["push_before"], push_after=parsed["push_after"], + results=[{ + "pull_number": item["pull_number"], "merge_commit_sha": item["merge_commit_sha"], + "status": item["status"], "reason": f"PR outcome: {item['status']}.", + } for item in parsed["results"]], + ) + else: + result.update(pull_number=parsed["pull_number"], merge_commit_sha=parsed["merge_commit_sha"]) + encoded = json.dumps(result, separators=(",", ":")).encode("ascii") + require(len(encoded) <= MAX_RESULT, "Maintenance receipt exceeds the storage budget") + return encoded diff --git a/automation_bridge/bundle.py b/automation_bridge/bundle.py new file mode 100644 index 0000000..4e10449 --- /dev/null +++ b/automation_bridge/bundle.py @@ -0,0 +1,25 @@ +"""Build a Functions source ZIP without copying host code, config, or secrets.""" + +import argparse +from pathlib import Path +from zipfile import ZIP_DEFLATED, ZipFile + + +def build(output: Path) -> None: + source = Path(__file__).resolve().parent + root = source.parent + action = root / ".github" / "actions" / "issuelens" + files = ( + source / "function_app.py", source / "bridge.py", + source / "host.json", source / "requirements.txt", + action / "issuelens_action.py", action / "stream_output.py", + ) + with ZipFile(output, "x", ZIP_DEFLATED) as archive: + for path in files: + archive.write(path, path.name) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path, help="New ZIP file to create") + build(parser.parse_args().output) diff --git a/automation_bridge/function_app.py b/automation_bridge/function_app.py new file mode 100644 index 0000000..f7ad7ce --- /dev/null +++ b/automation_bridge/function_app.py @@ -0,0 +1,130 @@ +"""Azure Functions entry point. Deploy the same bundle as ingress and worker.""" + +import json +import logging +import os +import re +from functools import lru_cache + +import azure.functions as func +import jwt +from azure.core.exceptions import AzureError +from azure.data.tables import TableClient +from azure.identity import ManagedIdentityCredential +from azure.servicebus import ServiceBusClient, ServiceBusMessage +from azure.servicebus.exceptions import ServiceBusError + +import bridge + +app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS) +logger = logging.getLogger(__name__) + + +@lru_cache(maxsize=1) +def identity(): + return ManagedIdentityCredential() + + +@lru_cache(maxsize=1) +def jobs(): + storage = os.environ["ISSUELENS_BRIDGE_TABLE_ACCOUNT"] + bridge.require(re.fullmatch(r"[a-z0-9]{3,24}", storage), "Invalid job storage account") + client = TableClient( + endpoint=f"https://{storage}.table.core.windows.net", + table_name="IssueLensBridgeJobs", credential=identity(), + ) + return bridge.JobStore(client) + + +@lru_cache(maxsize=1) +def service_bus(): + namespace = os.environ["ISSUELENS_BRIDGE_SERVICE_BUS__fullyQualifiedNamespace"] + bridge.require(re.fullmatch(r"[a-z0-9-]+\.servicebus\.windows\.net", namespace), "Invalid job queue namespace") + return ServiceBusClient(namespace, identity(), retry_total=0) + + +@lru_cache(maxsize=1) +def worker(): + return bridge.FoundryWorker(os.environ["ISSUELENS_BRIDGE_FOUNDRY_URL"], identity()) + + +def respond(value, status=200): + return func.HttpResponse( + json.dumps(value, separators=(",", ":")), status_code=status, mimetype="application/json", + headers={"Cache-Control": "no-store"}, + ) + + +def authorized(request): + auth = request.headers.get("Authorization", "") + bridge.require(auth.startswith("Bearer ") and len(auth) > len("Bearer "), + "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"]), + ) + + +role = os.environ.get("ISSUELENS_BRIDGE_ROLE") +if role == "ingress": + @app.route(route="issuelens/v1/jobs", methods=["POST"]) + def submit(request: func.HttpRequest) -> func.HttpResponse: + try: + claims = authorized(request) + except jwt.PyJWKClientConnectionError: + logger.warning("GitHub workflow signing keys unavailable") + return respond({"error": "identity_provider_unavailable"}, 503) + except (jwt.PyJWTError, ValueError): + return respond({"error": "workflow_not_authorized"}, 401) + try: + body = request.get_body() + bridge.require(0 < len(body) <= bridge.MAX_REQUEST, "Invalid job size") + data = json.loads(body, object_pairs_hook=bridge.action.unique_object) + target = bridge.validate_request(data, claims) + except (ValueError, TypeError): + return respond({"error": "invalid_job"}, 400) + identifier = bridge.job_id(claims) + try: + job = jobs().reserve(identifier, target, body) + 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: + sender.send_messages(ServiceBusMessage(identifier, message_id=identifier), timeout=10) + return respond(bridge.receipt(job), 202) + except bridge.BusyError: + return respond({"error": "target_has_unresolved_job"}, 409) + except (AzureError, ServiceBusError): + logger.warning("Bridge job admission not confirmed: %s", identifier) + return respond({"error": "job_admission_not_confirmed", "job_id": identifier}, 503) + + @app.route(route="issuelens/v1/jobs/{job_id}", methods=["GET"]) + def status(request: func.HttpRequest) -> func.HttpResponse: + try: + claims = authorized(request) + except jwt.PyJWKClientConnectionError: + logger.warning("GitHub workflow signing keys unavailable") + return respond({"error": "identity_provider_unavailable"}, 503) + except (jwt.PyJWTError, ValueError): + return respond({"error": "workflow_not_authorized"}, 401) + identifier = bridge.job_id(claims) + if request.route_params.get("job_id") != identifier: + return respond({"error": "job_not_found"}, 404) + try: + job = jobs().get(identifier) + except AzureError: + logger.warning("Bridge job status unavailable: %s", identifier) + return respond({"error": "job_status_unavailable"}, 503) + return respond(bridge.receipt(job)) if job is not None else respond({"error": "job_not_found"}, 404) +elif role == "worker": + @app.service_bus_queue_trigger( + arg_name="message", queue_name="%ISSUELENS_BRIDGE_QUEUE%", connection="ISSUELENS_BRIDGE_SERVICE_BUS", + ) + def process(message: func.ServiceBusMessage) -> None: + identifier = message.get_body().decode("ascii") + if not bridge.JOB_ID.fullmatch(identifier): + raise ValueError("Invalid queued bridge job ID") + state = worker().run(jobs(), identifier) + if state in {bridge.FAILED, bridge.UNKNOWN}: + logger.warning("Bridge job %s: %s", identifier, state) +else: + raise ValueError("Set ISSUELENS_BRIDGE_ROLE to ingress or worker") diff --git a/automation_bridge/host.json b/automation_bridge/host.json new file mode 100644 index 0000000..a0a6385 --- /dev/null +++ b/automation_bridge/host.json @@ -0,0 +1,14 @@ +{ + "version": "2.0", + "functionTimeout": "00:40:00", + "extensionBundle": { + "id": "Microsoft.Azure.Functions.ExtensionBundle", + "version": "[4.0.0, 5.0.0)" + }, + "extensions": { + "serviceBus": { + "maxAutoLockRenewalDuration": "00:40:00", + "maxConcurrentCalls": 4 + } + } +} diff --git a/automation_bridge/requirements.txt b/automation_bridge/requirements.txt new file mode 100644 index 0000000..1a3fecb --- /dev/null +++ b/automation_bridge/requirements.txt @@ -0,0 +1,5 @@ +azure-functions>=1.21.3,<2 +azure-identity>=1.17.0,<2 +azure-data-tables>=12.6.0,<13 +azure-servicebus>=7.14.2,<8 +PyJWT[crypto]>=2.9.0,<3 diff --git a/docs/guide.md b/docs/guide.md index cbb1afa..0fa89f3 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -204,36 +204,25 @@ contracts do not establish live hosted sub-agent dispatch or deployment. The coordinator loads and calls only `issuelens`, using `github.workflow_sha` with credentials not persisted. Neither path executes PR-head code. Protect workflow and action changes as privileged code. -2. Reuse the issue-loop Actions secrets: `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, - `AZURE_SUBSCRIPTION_ID`, `ISSUELENS_AGENT_URL` (the complete Foundry - invocations endpoint), and `ISSUELENS_AGENT_SCOPE`. The old skeleton's - `ISSUELENS_AGENT_ENDPOINT` is not used. Configure Azure OIDC federation for - this repository and the actual workflow event/ref subject, including manual - dispatch if used. In IssueLens's two-workflow pilot, only the coordinator uses - Azure OIDC, under its default-branch `workflow_dispatch` identity; also verify - any workflow-specific federation conditions. The dispatcher needs only - repository-scoped `GITHUB_TOKEN` Actions write access. No new cross-repository - credential is required for this same-repository pilot. - Migrating from `pull_request_target` can change the OIDC - subject; verify the actual default-branch subject, including immutable - repository/owner IDs where enabled. Do not assume the old PR-scoped credential - covers `push`, or broaden federation to untrusted refs. - The identity needs permission to invoke the existing Foundry agent, not - deployment or GitHub wiki-write credentials. No App private key is stored here. +2. The IssueLens coordinator uses the [Function bridge](#issuelens-function-bridge-pilot). + Its dispatcher needs only repository-scoped `GITHUB_TOKEN` Actions write access + and does not send a token to the bridge. External callers pinned to an earlier + revision still use direct Azure OIDC and need their own approved identity. + Do not restore the retired IssueLens federated identity credentials (FICs). 3. Use a deployed agent with wiki-maintenance support and source-independent request handling, configure optional `instructions.team_memory` policy, initialize the chosen wiki, and confirm destination App Contents read/write access. The workflow neither initializes the wiki nor changes permissions or agent deployments. 4. Set the repository Actions variable `ISSUELENS_TEAM_MEMORY_ENABLED=true` - when ready. This opts into automatic maintenance; it is not an agent - environment flag or a wiki-destination allowlist. Without it, the job skips - before acquiring Azure credentials. + only after the manual pilot succeeds. This opts into automatic maintenance; it + is not an agent environment flag or a wiki-destination allowlist. For a + manual-only pilot, leave it unset and use `ISSUELENS_TEAM_MEMORY_MANUAL_PILOT`. Each eligible push produces one invocation containing its verified merged PRs, not one invocation per PR. The preflight checks the complete fast-forward commit inventory and discovers associated PRs through bounded metadata-only GitHub queries. It does not send raw combined diffs to the model. Direct pushes -without newly merged PRs skip before Azure login. Missing/truncated inventories, +without newly merged PRs skip before authentication to the invocation transport. Missing/truncated inventories, force pushes, and ambiguous discovery fail without submitting a partial source list; use manual PR dispatch to recover. This batches PRs within one push, not across separate pushes, so an ordinary one-PR merge still usually produces one run. @@ -252,7 +241,7 @@ to dispatch the No source code, commit messages, issue/PR bodies, agent output, or credentials are included. The coordinator keeps the queue but only invokes the shared `issuelens` action -after trusted sparse checkout. Before Azure login, that action authenticates +after trusted sparse checkout. Before submitting to the bridge, that action authenticates the allowed source and exact default-branch push workflow/run/attempt, matches `push_after` to its head, verifies current default-branch ancestry, and retrieves the full fast-forward requested range in pages of 100 commits (at most 1,000). @@ -314,7 +303,7 @@ Only PRs merged into the current default branch are accepted. Manual **Run workflow** now uses the coordinator, with a positive `pull_request_number` instead of source identifiers, and the default branch; it revalidates the same merged PR instead of inventing a merge event. GitHub -repository and PR metadata are re-read before Azure login. PR titles, bodies, +repository and PR metadata are re-read before submitting the job. PR titles, bodies, comments, and fork source are not embedded in the trusted task. The authenticated request authorizes only minimal wiki maintenance; the agent independently rechecks the merge and treats retrieved content as untrusted evidence. Endpoint @@ -323,11 +312,11 @@ authentication alone does not cryptographically attest the JSON metadata. Issue-loop and the team-memory coordinator use one composite action with three request adapters: `issue-loop`, `team-memory`, and `task`. The selected adapter prepares and -validates the request before shared Azure OIDC login and invocation. The helper is -a normal, directly testable Python module; no Python is embedded in the YAML. -The action is one client of the same agent used by chat and other callers. -It supplies its origin, merge evidence, validation constraints, no-reaction -instruction, and requested response format in `input`. Its JSON result schema +validates the request before authenticating to the pilot bridge or the legacy +direct endpoint. The helper is a normal, directly testable Python module; no +Python is embedded in the YAML. The invocation prompt supplies its origin, +merge evidence, validation constraints, no-reaction instruction, and requested +response format in `input`. Its JSON result schema belongs to this caller, not to the shared agent prompts or knowledge policy. Other callers may request different formats or updates unrelated to a merge; the same authorization, evidence, and wiki preconditions still apply. Shared @@ -1008,8 +997,9 @@ data: {"invocation_id": "...", "session_id": "..."} ## Triggering with GitHub Actions The recommended trigger is a **GitHub Actions workflow in the target -repository**. It authenticates only to the Foundry endpoint through Azure OIDC -and sends the task. The hosted agent owns its Key Vault-backed App identity, so +repository**. In `microsoft/IssueLens`, the workflow sends a bounded job to the +[Function bridge](#issuelens-function-bridge-pilot) instead of logging into Azure +from GitHub. The hosted agent owns its Key Vault-backed App identity, so target repositories store no App private key and transmit no GitHub token. - **Event-driven:** issue opened/reopened and human-authored issue-comment @@ -1022,7 +1012,7 @@ target repositories store no App private key and transmit no GitHub token. The workflow does not currently trigger on issue title/body edits or pull request comments. Its preflight step rejects PR-backed comments and comments whose sender or author is a bot, records the accepted/skipped reason before -Azure login, and passes only trusted event metadata to the agent. It never +bridge authentication, and passes only trusted event metadata to the agent. It never copies issue or comment body text into the workflow-generated control prompt. Runs are grouped by repository and issue. Different issues run independently; @@ -1050,8 +1040,9 @@ workflow filename intentionally differs from the policy filename. For explicit triage, planning, or other supported requests, use `request-type: task` with trusted `input` text. This does not synthesize issue-loop event or -maintainer-command authority. Both generic adapters accept a completed final -answer in the format chosen by the caller. `status=completed` confirms invocation +maintainer-command authority. On the direct transport, both generic adapters +accept a completed final answer in the format chosen by the caller. +`status=completed` confirms invocation completion, not a successful requested write; the original answer is available through a runner-local `response-path`. The default hybrid view streams readable text and tool activity, and the full job summary renders the final answer. Use @@ -1060,6 +1051,81 @@ for sensitive requests. Raw protocol events and tool payloads are not logged. On `team-memory` enforces the wiki-specific result schema. The agent retains role 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 +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; +there is no Entra token exchange or FIC on the Actions side. The token +authenticates the workflow run, not the event JSON independently. The approved +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 +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, protected `main`, 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. | +| Worker | `ISSUELENS_BRIDGE_ROLE=worker`, `ISSUELENS_BRIDGE_FOUNDRY_URL` set to the existing deployed agent's full invocations URL (including API version). Grant queue **Data Receiver** and the narrowest applicable Foundry invocation access to the worker managed identity. It requests an Entra token for `https://ai.azure.com/.default`. No repository write, deployment, signing key, or GitHub App key access is needed. | + +The 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 +use the same agent. The bridge scopes jobs accepted through its own endpoint; +it does not change Foundry RBAC or add per-job tool restrictions to the host. +Keep direct endpoint access limited to approved callers. The GitHub workflow +for deploying the agent is separate from this migration and still requires +an approved replacement for its retired identity. + +Set the repository variable `ISSUELENS_BRIDGE_URL` to the approved ingress +jobs URL only when the bridge and worker RBAC are ready. Verify that +out-of-scope workflows and jobs are rejected before enabling the workflows. +The existing deployed agent can write, so treat a live invocation as a +write-capable test, not a dry run. After approval, set +`ISSUELENS_ISSUE_LOOP_ENABLED=true` for issue events. Enable +`ISSUELENS_TEAM_MEMORY_MANUAL_PILOT=true` for a manual `pull_request_number` +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 +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 +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 +job but cannot replace its payload or resubmit a running or terminal job. +Issue-loop `completed` means the session ended, not that any write succeeded. +Team memory still validates the wiki and source receipt, retaining partial +per-PR outcomes and failing the workflow on incomplete maintenance. + +Monitor old reservations, `unknown` outcomes, and the Service Bus dead-letter +queue. A failed send may leave a `queued` reservation without a message. While +it is still queued and less than 10 minutes old, a rerun of the **same workflow +run** can resend the original job, not replace it. The ingress and worker log +the job ID; receipts and logs never include credentials. Dead-lettered or +expired jobs need reconciliation, not automatic replay. + +To roll back, remove the opt-in variables and pause the worker before +reconciling in-flight jobs. For an unresolved reservation, verify no invocation +can still write and inspect the issue or wiki state. Record the operator +resolution without deleting the original job record, and release only the lock +owned by that job. Transition the job out of `queued` or `running` and remove +its reservation in one conditional Table transaction using both current ETags; +do not reopen unresolved jobs for dispatch. Restarting a Function or restoring +old FICs does not recover an ambiguous write. + ## Using Your Own Foundry Model To use your own Azure AI Foundry model instead of the Copilot model, set the Foundry variables (no `GITHUB_TOKEN` needed): diff --git a/tests/test_automation_bridge.py b/tests/test_automation_bridge.py new file mode 100644 index 0000000..523a8fb --- /dev/null +++ b/tests/test_automation_bridge.py @@ -0,0 +1,348 @@ +import hashlib +import json +import os +import pathlib +import subprocess +import sys +import tempfile +import time +import unittest +import urllib.error +import urllib.parse +from unittest.mock import Mock, patch +from zipfile import ZipFile + +import jwt +from azure.data.tables import TableTransactionError +from cryptography.hazmat.primitives.asymmetric import rsa + +from automation_bridge import bridge, bundle + + +PILOT_REPOSITORY = bridge.PILOT_REPOSITORY +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" + + +def issue_metadata(**overrides): + return { + "event_name": "issue_comment", "event_action": "created", "repository": PILOT_REPOSITORY, + "issue_number": 12, "actor_login": "maintainer", "actor_type": "User", + "issue_author_association": "NONE", "comment_id": 41, "comment_author_login": "maintainer", + "comment_author_association": "MEMBER", "comment_added": True, "comment_edited": False, + "manual_dispatch": False, "comment_sha256": hashlib.sha256(b"test comment").hexdigest(), + **overrides, + } + + +def issue_payload(**overrides): + return {"request_type": "issue-loop", "metadata": issue_metadata(**overrides)} + + +def current_comment(): + return { + "id": 41, "issue_url": f"https://api.github.com/repos/{PILOT_REPOSITORY}/issues/12", + "body": "test comment", "created_at": "2026-11-24T00:00:00Z", "updated_at": "2026-11-24T00:00:00Z", + } + + +class BridgeIdentityTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + + def test_only_the_protected_pilot_workflow_can_submit_or_read_its_job(self): + now = int(time.time()) + 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, "ref_protected": "true", "runner_environment": "github-hosted", + "workflow_ref": bridge.workflow_ref(bridge.ISSUE_WORKFLOW), "workflow_sha": "1" * 40, + "event_name": "issue_comment", "actor": "maintainer", "run_id": "20", "run_attempt": "1", + } + with patch.object(bridge.KEYS, "get_signing_key_from_jwt", return_value=Mock(key=self.key.public_key())): + accepted = bridge.workflow_claims(jwt.encode(claims, self.key, algorithm="RS256"), URL, 100) + self.assertEqual(bridge.validate_request(issue_payload(), accepted), "issue-12") + for alteration in ( + {"repository_id": "101"}, {"ref_protected": "false"}, {"repository_visibility": "private"}, + {"event_name": "pull_request"}, {"workflow_ref": bridge.workflow_ref("another.yml")}, + {"aud": ENDPOINT}, {"exp": now - 1}, + ): + with self.subTest(alteration=alteration), self.assertRaises((ValueError, jwt.PyJWTError)): + bridge.workflow_claims(jwt.encode(claims | alteration, self.key, algorithm="RS256"), URL, 100) + with self.assertRaises(jwt.InvalidSignatureError): + bridge.workflow_claims( + jwt.encode(claims, rsa.generate_private_key(public_exponent=65537, key_size=2048), algorithm="RS256"), + URL, 100, + ) + 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})) + for invalid in ( + issue_payload(repository="example/unrelated"), issue_payload(comment_added=False), + issue_payload(body="caller-supplied context"), issue_payload(comment_author_login="other"), + {"request_type": "team-memory", "metadata": issue_metadata()}, + ): + with self.subTest(invalid=invalid), self.assertRaises(ValueError): + bridge.validate_request(invalid, accepted) + +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" + env = {"ACTIONS_ID_TOKEN_REQUEST_URL": endpoint, "ACTIONS_ID_TOKEN_REQUEST_TOKEN": "runner-secret"} + with patch.dict(os.environ, env, clear=True), patch.object(bridge.action, "bridge_json") as request: + request.return_value = {"value": "header.payload.signature"} + self.assertEqual(bridge.action.workflow_token(URL), "header.payload.signature") + request_url, credential = request.call_args.args + self.assertEqual(credential, "runner-secret") + self.assertEqual(urllib.parse.parse_qs(urllib.parse.urlsplit(request_url).query), + {"api-version": ["2.0"], "audience": [URL]}) + os.environ["ACTIONS_ID_TOKEN_REQUEST_URL"] = "https://tokenghub.actions.githubusercontent.com.example.test/" + with self.assertRaisesRegex(ValueError, "OIDC endpoint unavailable"): + bridge.action.workflow_token(URL) + request.assert_called_once() + + def test_issue_preflight_uses_a_digest_without_relaying_the_comment(self): + event = { + "action": "created", "issue": {"number": 12, "body": "private event content"}, + "comment": { + "id": 41, "user": {"login": "maintainer", "type": "User"}, "body": "test comment", + "author_association": "MEMBER", + }, + "sender": {"login": "maintainer", "type": "User"}, + } + with ( + patch.dict(os.environ, {"GITHUB_EVENT_NAME": "issue_comment", "TRANSPORT": "bridge"}, clear=True), + patch.object(bridge.action, "validate_workflow"), + ): + envelope = bridge.action.prepare_issue_loop(PILOT_REPOSITORY, event) + self.assertEqual(envelope["metadata"]["comment_sha256"], issue_metadata()["comment_sha256"]) + self.assertNotIn("comment_sha256", envelope["request"]["input"]) + self.assertNotIn("test comment", json.dumps(envelope)) + self.assertNotIn("private event content", json.dumps(envelope)) + + def test_action_submits_once_and_waits_for_terminal_result(self): + env = { + "TRANSPORT": "bridge", "BRIDGE_URL": URL, "GH_TOKEN": "unforwarded-github-token", + } + envelope = {**issue_payload(), "request": {"input": "unforwarded legacy prompt"}} + with ( + patch.dict(os.environ, env, clear=True), + patch.object(bridge.action, "workflow_token", return_value="function-audience-jwt"), + patch.object(bridge.action, "bridge_json", side_effect=[ + {"job_id": JOB, "state": "queued"}, {"job_id": JOB, "state": "running"}, + {"job_id": JOB, "state": "completed"}, + ]) as request, + patch.object(bridge.action.time, "sleep"), + patch.object(bridge.action, "display_log"), + patch.object(bridge.action.subprocess, "check_output") as az, + ): + self.assertIn("Inspect GitHub", bridge.action.submit_bridge(envelope)) + self.assertEqual( + [call.args for call in request.call_args_list], + [(URL, "function-audience-jwt", issue_payload()), + (f"{URL}/{JOB}", "function-audience-jwt"), (f"{URL}/{JOB}", "function-audience-jwt")], + ) + az.assert_not_called() + + def test_unknown_submission_is_not_replayed(self): + with ( + patch.dict(os.environ, {"BRIDGE_URL": URL}), + patch.object(bridge.action, "workflow_token", return_value="workflow-token"), + patch.object(bridge.action, "bridge_json", side_effect=[ + {"job_id": JOB, "state": "unknown"}, + ]) as request, + patch.object(bridge.action, "display_log"), + ): + with self.assertRaisesRegex(ValueError, "outcome is unknown"): + bridge.action.submit_bridge(issue_payload()) + request.assert_called_once() + + +class BridgeExecutionTests(unittest.TestCase): + def setUp(self): + self.credential = Mock() + self.credential.get_token.return_value.token = "managed-identity-token" + self.worker = bridge.FoundryWorker(ENDPOINT, self.credential) + + def test_worker_uses_the_existing_foundry_api_for_issue_and_wiki_jobs(self): + issue = issue_metadata(event_name="issues", event_action="opened", comment_id=None, comment_added=False, + comment_author_login=None, comment_author_association=None) + issue.pop("comment_sha256") + memory = { + "repository": PILOT_REPOSITORY, "event_name": "workflow_dispatch", + "pull_number": 12, "merge_commit_sha": "a" * 40, "required_wiki_repository": PILOT_REPOSITORY, + } + with patch.object(bridge.action, "github_read") as github: + for kind, metadata, expected in ( + ("issue-loop", issue, bridge.action.build_issue_loop_request(issue)), + ("team-memory", memory, bridge.action.build_team_memory_request(memory)), + ): + with self.subTest(kind=kind): + payload = {"request_type": kind, "metadata": metadata} + request = self.worker.prepare({"payload": json.dumps(payload)}) + self.assertEqual((request.full_url, request.method), (ENDPOINT, "POST")) + self.assertEqual(request.get_header("Authorization"), "Bearer managed-identity-token") + self.assertEqual(request.get_header("Accept"), "text/event-stream") + self.assertEqual(json.loads(request.data), expected) + github.assert_not_called() + self.credential.get_token.assert_called_with("https://ai.azure.com/.default") + + 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"}), \ + 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)}) + 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")) + self.assertEqual(github_request.get_header("Cache-control"), "no-cache") + original_metadata = dict(payload["metadata"]) + original_metadata.pop("comment_sha256") + self.assertEqual(json.loads(request.data), bridge.action.build_issue_loop_request(original_metadata)) + 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())} + for comment in ( + {**current_comment(), "body": "Edited within the same second"}, + {**current_comment(), "updated_at": "2026-11-24T00:00:01Z"}, + {**current_comment(), "issue_url": current_comment()["issue_url"] + "3"}, + urllib.error.URLError("GitHub unavailable"), + ): + with self.subTest(comment=comment), \ + patch.object(bridge.action, "github_read", side_effect=[comment]), \ + patch.object(bridge.urllib.request, "build_opener") as opener: + store = Mock(spec=bridge.JobStore) + store.get.side_effect = [job | {"state": bridge.QUEUED}, job] + self.assertEqual(self.worker.run(store, JOB), bridge.FAILED) + store.settle.assert_called_once_with(job, bridge.FAILED) + opener.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 + store = bridge.JobStore(Mock()) + 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") + + 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) + store.table.submit_transaction.assert_not_called() + + def test_settlement_does_not_release_a_different_jobs_reservation(self): + class Entity(dict): + metadata = {"etag": "current"} + + store = bridge.JobStore(Mock()) + job = Entity(PartitionKey=bridge.PARTITION, RowKey=JOB, target="wiki", state="running", payload=b"metadata") + lock = Entity(PartitionKey=bridge.PARTITION, RowKey="lock-wiki", job_id="8" * 64) + store.table.get_entity.return_value = lock + with self.assertRaisesRegex(ValueError, "does not own"): + store.settle(job, bridge.COMPLETED) + store.table.submit_transaction.assert_not_called() + lock["job_id"] = JOB + store.settle(job, bridge.COMPLETED) + operations, = store.table.submit_transaction.call_args.args + self.assertEqual([entry[0] for entry in operations], ["update", "delete"]) + self.assertEqual(operations[0][1]["state"], "completed") + self.assertEqual(operations[1][2], {"etag": "current", "match_condition": bridge.MatchConditions.IfNotModified}) + + def test_duplicate_queue_delivery_cannot_restart_a_running_or_unknown_job(self): + store = Mock(spec=bridge.JobStore) + for state in ("running", "unknown", "completed"): + with self.subTest(state=state): + store.get.return_value = {"RowKey": JOB, "state": state} + self.assertIsNone(self.worker.run(store, JOB)) + store.claim.assert_not_called() + + def test_interrupted_foundry_response_holds_the_reservation(self): + job = Mock(metadata={"etag": "1"}) + claimed = { + "PartitionKey": bridge.PARTITION, "RowKey": JOB, "target": "wiki", "state": "running", + "created": int(time.time()), "payload": b"metadata", + } + + class Entity(dict): + metadata = job.metadata + + table = Mock() + table.get_entity.side_effect = [Entity(claimed | {"state": "queued"}), Entity(claimed)] + store = bridge.JobStore(table) + with ( + patch.object(self.worker, "prepare", return_value=Mock()), + patch.object(bridge.urllib.request, "build_opener") as opener, + ): + opener.return_value.open.side_effect = urllib.error.URLError("connection lost after send") + self.assertEqual(self.worker.run(store, JOB), "unknown") + opener.return_value.open.assert_called_once() + operations, = table.submit_transaction.call_args.args + self.assertEqual([entry[0] for entry in operations], ["update"]) + self.assertEqual(operations[0][1]["state"], "unknown") + self.assertNotIn("payload", operations[0][1]) + + def test_partial_wiki_receipt_keeps_every_pr_without_persisting_agent_prose(self): + repository = PILOT_REPOSITORY + first, second = "a" * 40, "b" * 40 + metadata = { + "event_name": "push", "repository": repository, "required_wiki_repository": repository, + "push_before": "1" * 40, "push_after": "2" * 40, + "pull_requests": [{"pull_number": 12, "merge_commit_sha": first}, + {"pull_number": 13, "merge_commit_sha": second}], + } + parsed = { + "source_repository": repository, "status": "partial", "reason": "unforwarded model prose", + "wiki_repository": repository, "wiki_sha": "f" * 40, + "push_before": metadata["push_before"], "push_after": metadata["push_after"], + "results": [ + {"pull_number": 12, "merge_commit_sha": first, "status": "updated", "reason": "publication reason"}, + {"pull_number": 13, "merge_commit_sha": second, "status": "needs-review", "reason": "unfinished evidence"}, + ], + } + durable = bridge._memory_receipt(json.dumps(parsed), metadata) + value = json.loads(durable) + bridge.action.validate_team_memory_result(value, metadata) + self.assertEqual(value["status"], "partial") + self.assertEqual([(pr["pull_number"], pr["status"]) for pr in value["results"]], + [(12, "updated"), (13, "needs-review")]) + for prose in (b"unforwarded model prose", b"unfinished evidence"): + self.assertNotIn(prose, durable) + with self.assertRaises(ValueError): + bridge._memory_receipt(json.dumps(parsed | {"wiki_repository": "example/wiki"}), metadata) + + def test_bundle_indexes_only_the_expected_trigger_for_each_identity(self): + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + archive = root / "bridge.zip" + bundle.build(archive) + with ZipFile(archive) as source: + self.assertEqual(set(source.namelist()), { + "function_app.py", "bridge.py", "host.json", "requirements.txt", + "issuelens_action.py", "stream_output.py", + }) + source.extractall(root) + for role, expected in (("ingress", "status,submit"), ("worker", "process")): + with self.subTest(role=role): + result = subprocess.run( + [sys.executable, "-c", ( + "from function_app import app; " + "print(','.join(sorted(x.get_function_name() for x in app.get_functions())))" + )], + cwd=root, env={**os.environ, "ISSUELENS_BRIDGE_ROLE": role}, + capture_output=True, text=True, timeout=30, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_ci_workflow.py b/tests/test_ci_workflow.py index c484d22..928465d 100644 --- a/tests/test_ci_workflow.py +++ b/tests/test_ci_workflow.py @@ -100,7 +100,8 @@ def test_pip_caches_include_all_installed_manifests(self): self.assertEqual(setup["cache"], "pip") self.assertEqual( set(setup["cache-dependency-path"].split()), - {manifest, "requirements-ci.txt", "constraints-ci.txt"}, + {manifest, "requirements-ci.txt", "constraints-ci.txt"} + | ({"automation_bridge/requirements.txt"} if job_id == "application-tests" else set()), ) if job_id != "application-tests": self.assertEqual(setup["python-version"], "${{ matrix.python-version }}") @@ -133,7 +134,7 @@ def test_both_suites_run_directly_so_failures_fail_the_job(self): ): self.assertIn(command, [step.get("run") for step in self.jobs[job_id]["steps"]]) self.assertIn( - "python -m pip install -r requirements.txt -r requirements-ci.txt", + "python -m pip install -r requirements.txt -r automation_bridge/requirements.txt -r requirements-ci.txt", self.commands("application-tests"), ) self.assertIn( @@ -159,7 +160,7 @@ def test_package_build_and_install_are_isolated_from_source_imports(self): def test_validation_tools_and_commands_are_documented(self): contributing = (ROOT / "CONTRIBUTING.md").read_text(encoding="utf-8") - syntax = "python -m compileall -q *.py .github/actions/issuelens .github/actions/queue-team-memory github_app_mcp/src github_app_mcp/scripts tests github_app_mcp/tests" + syntax = "python -m compileall -q *.py automation_bridge .github/actions/issuelens .github/actions/queue-team-memory github_app_mcp/src github_app_mcp/scripts tests github_app_mcp/tests" self.assertIn(syntax, self.commands("application-tests")) self.assertIn(syntax, contributing) lint = self.commands("workflow-validation") diff --git a/tests/test_deploy_foundry_workflow.py b/tests/test_deploy_foundry_workflow.py index f346ad0..da9652b 100644 --- a/tests/test_deploy_foundry_workflow.py +++ b/tests/test_deploy_foundry_workflow.py @@ -469,7 +469,8 @@ def test_official_oidc_and_azd_configuration_pattern(self): for filename in ("issue-triage.yml", "team-memory-coordinator.yml"): caller = (ROOT / ".github/workflows" / filename).read_text(encoding="utf-8") for reference in login["with"].values(): - self.assertIn(reference, caller) + self.assertNotIn(reference, caller) + self.assertIn("transport: bridge", caller) configure = next(step for step in self.steps if "azd config set" in step.get("run", "")) self.assertIn("azd config set auth.useAzCliAuth true", configure["run"]) self.assertIn('azd env new "$AZD_ENV_NAME"', configure["run"]) diff --git a/tests/test_issue_triage_workflow.py b/tests/test_issue_triage_workflow.py index 0557881..28b847c 100644 --- a/tests/test_issue_triage_workflow.py +++ b/tests/test_issue_triage_workflow.py @@ -31,8 +31,8 @@ def test_preflight_rejects_pr_and_bot_comments_before_login(self): metadata = yaml.load((action_tests.ACTION_DIR / "action.yml").read_text(encoding="utf-8"), Loader=yaml.BaseLoader) preflight, login, submit = metadata["runs"]["steps"] self.assertEqual(preflight["id"], "preflight") - for step in (login, submit): - self.assertEqual(step["if"], "steps.preflight.outputs.eligible == 'true'") + self.assertEqual(login["if"], "steps.preflight.outputs.eligible == 'true' && inputs.transport == 'foundry'") + self.assertEqual(submit["if"], "steps.preflight.outputs.eligible == 'true'") def test_caller_is_thin_and_loads_trusted_action(self): checkout, invoke = self.job["steps"] @@ -41,7 +41,13 @@ def test_caller_is_thin_and_loads_trusted_action(self): self.assertEqual(checkout["with"]["sparse-checkout"], "/.github/actions/issuelens/") self.assertEqual(invoke["uses"], "./.github/actions/issuelens") self.assertEqual(invoke["with"]["request-type"], "issue-loop") + self.assertEqual(invoke["with"]["transport"], "bridge") + self.assertEqual(invoke["with"]["bridge-url"], "${{ vars.ISSUELENS_BRIDGE_URL }}") self.assertEqual(invoke["with"]["issue-number"], "${{ inputs.issue_number }}") + self.assertIn("vars.ISSUELENS_ISSUE_LOOP_ENABLED == 'true'", self.job["if"]) + self.assertIn("vars.ISSUELENS_BRIDGE_URL != ''", self.job["if"]) + self.assertIn("github.repository == 'microsoft/IssueLens'", self.job["if"]) + self.assertNotIn("secrets.AZURE_", self.source) self.assertEqual(self.workflow["permissions"], {}) self.assertEqual(self.job["permissions"], {"contents": "read", "issues": "read", "id-token": "write"}) self.assertEqual(self.job["timeout-minutes"], "45") @@ -75,8 +81,6 @@ def test_trusted_metadata_excludes_issue_and_comment_text(self): "manual_dispatch", ): self.assertIn(field, helper) - self.assertNotIn('.get("body")', helper) - self.assertNotIn('["body"]', helper) def test_optional_metadata_uses_null_when_unknown(self): helper = action_tests.HELPER.read_text(encoding="utf-8") diff --git a/tests/test_team_memory_coordinator.py b/tests/test_team_memory_coordinator.py index 82fef8e..84af10d 100644 --- a/tests/test_team_memory_coordinator.py +++ b/tests/test_team_memory_coordinator.py @@ -7,6 +7,7 @@ from unittest.mock import patch import test_team_memory_workflow as memory_tests +from automation_bridge import bridge action = memory_tests.action @@ -74,6 +75,16 @@ def source_responses(self): values.append(self.source_project) return self.responses(*values, self.source_run, self.branch, self.ancestry) + def coordinator_claims(self): + return { + "kind": "team-memory", "repository_id": self.project["id"], + "actor": self.environment["GITHUB_ACTOR"], + "workflow_ref": self.environment["GITHUB_WORKFLOW_REF"], + "workflow_sha": self.environment["GITHUB_WORKFLOW_SHA"], + "run_id": int(self.environment["GITHUB_RUN_ID"]), + "run_attempt": int(self.environment["GITHUB_RUN_ATTEMPT"]), + } + def preflight_responses(self): return self.source_responses() + self.responses(self.comparison, self.associations) @@ -104,6 +115,10 @@ def test_queued_range_preserves_source_identity_not_coordinator_head(self): self.assertEqual(metadata["pull_requests"][0]["merge_commit_sha"], self.merge_sha) self.assertEqual(len(metadata["pull_requests"]), 1) self.assertEqual(metadata["range_origin"], "authorized-reconciliation") + self.assertEqual(bridge.validate_request( + {"request_type": "team-memory", "metadata": metadata}, + self.coordinator_claims(), + ), "wiki") self.assertIn("not an attestation of the original push boundary", envelope["request"]["input"]) self.assertIn("Preflight already verified the complete fast-forward commit inventory", envelope["request"]["input"]) self.assertIn("Do not repeat that range validation with compare_commits", envelope["request"]["input"]) @@ -444,12 +459,20 @@ def test_queued_request_preserves_the_existing_batch_receipt_contract(self): self.token.assert_called_once() def test_manual_pr_selection_uses_the_same_coordinator_without_range_inputs(self): - self.environment.update({name: "" for name in action.SOURCE_INPUTS}, DISPATCH_PR="27") + self.environment.update( + {name: "" for name in action.SOURCE_INPUTS}, DISPATCH_PR="27", + TRANSPORT="bridge", BRIDGE_URL="https://issuelens.azurewebsites.net/api/issuelens/v1/jobs", + ) self.execute("preflight", self.responses(self.project, self.pull)) metadata = self.prepared_envelope()["metadata"] self.assertEqual(metadata["pull_number"], 27) self.assertEqual(metadata["required_wiki_repository"], self.repository) self.assertEqual(metadata["coordinator_run_id"], 999) + job = {"request_type": "team-memory", "metadata": metadata} + claims = self.coordinator_claims() + self.assertEqual(bridge.validate_request(job, claims), "wiki") + with self.assertRaisesRegex(ValueError, "coordinator identity mismatch"): + bridge.validate_request(job, {**claims, "run_attempt": claims["run_attempt"] + 1}) self.assertEqual(self.opener.open.call_count, 2) self.token.assert_not_called() diff --git a/tests/test_team_memory_workflow.py b/tests/test_team_memory_workflow.py index 5c11824..54eb508 100644 --- a/tests/test_team_memory_workflow.py +++ b/tests/test_team_memory_workflow.py @@ -68,8 +68,8 @@ def test_preflight_precedes_pinned_login_and_submission(self): preflight, login, submit = self.action_metadata["runs"]["steps"] self.assertEqual(preflight["id"], "preflight") self.assertRegex(login["uses"], r"^azure/login@[0-9a-f]{40}\Z") - for step in (login, submit): - self.assertEqual(step["if"], "steps.preflight.outputs.eligible == 'true'") + self.assertEqual(login["if"], "steps.preflight.outputs.eligible == 'true' && inputs.transport == 'foundry'") + self.assertEqual(submit["if"], "steps.preflight.outputs.eligible == 'true'") self.assertEqual(submit["env"]["AGENT_URL"], "${{ inputs.agent-url }}") self.assertEqual(submit["env"]["AGENT_SCOPE"], "${{ inputs.agent-scope }}") self.assertEqual(submit["env"]["REQUEST_PATH"], "${{ steps.preflight.outputs.request-path }}") @@ -180,7 +180,7 @@ def test_invocation_action_owns_preflight_and_has_no_artifact_path(self): self.assertNotIn("source-artifact-id", self.action_metadata["inputs"]) self.assertNotIn("artifact", json.dumps(self.action_metadata)) self.assertNotIn("source-repositories", invoke["with"]) - self.assertEqual(login["if"], "steps.preflight.outputs.eligible == 'true'") + self.assertEqual(login["if"], "steps.preflight.outputs.eligible == 'true' && inputs.transport == 'foundry'") self.assertTrue(all("${{" not in step["run"] for step in self.action_metadata["runs"]["steps"] if "run" in step)) def test_job_timeout_has_setup_and_receipt_headroom(self): @@ -203,8 +203,11 @@ def test_local_caller_loads_only_trusted_action_revision(self): invoke = self.steps[-1] self.assertEqual(invoke["uses"], "./.github/actions/issuelens") self.assertEqual(invoke["with"]["request-type"], "team-memory") - self.assertEqual(invoke["with"]["agent-url"], "${{ secrets.ISSUELENS_AGENT_URL }}") - self.assertEqual(invoke["with"]["agent-scope"], "${{ secrets.ISSUELENS_AGENT_SCOPE }}") + self.assertEqual(invoke["with"]["transport"], "bridge") + self.assertEqual(invoke["with"]["bridge-url"], "${{ vars.ISSUELENS_BRIDGE_URL }}") + self.assertIn("vars.ISSUELENS_BRIDGE_URL != ''", self.job["if"]) + self.assertIn("vars.ISSUELENS_TEAM_MEMORY_MANUAL_PILOT == 'true' && inputs.pull_request_number != ''", self.job["if"]) + self.assertNotIn("secrets.AZURE_", self.source) self.assertTrue(set(invoke["with"]).issubset(self.action_metadata["inputs"])) self.assertNotIn("pull_request.head", self.source) self.assertNotIn("actions/checkout", json.dumps(self.action_metadata)) @@ -298,7 +301,7 @@ def test_multiple_source_guidance_preserves_partial_authorization_and_full_hando self.assertIn(requirement, orchestrator) def test_workflow_owns_its_request_and_setup_contract(self): - guide = (ROOT / "docs" / "guide.md").read_text(encoding="utf-8") + guide = " ".join((ROOT / "docs" / "guide.md").read_text(encoding="utf-8").split()) request = action.build_team_memory_request({})["input"] for field in ("source_repository", "pull_number", "merge_commit_sha", "wiki_repository", "wiki_sha", "reason"): self.assertIn(field, request) @@ -307,7 +310,8 @@ def test_workflow_owns_its_request_and_setup_contract(self): self.assertIn("requested response format", guide) self.assertIn("ISSUELENS_TEAM_MEMORY_ENABLED=true", guide) self.assertIn("default-branch pushes", guide) - self.assertIn("OIDC federation", guide) + self.assertIn("ISSUELENS_TEAM_MEMORY_MANUAL_PILOT=true", guide) + self.assertIn("no Entra token exchange or FIC on the Actions side", guide) self.assertIn("inspect the mapped wiki/history", guide) for path in ("agents/issuelens.md", "agents/team-memory.md", "README.md", "docs/guide.md", "github_app_mcp/README.md", ".github/copilot-instructions.md", ".github/issuelens/team-memory.md", "examples/team-memory.md"): From 8b07665c2d63b7d483e4ebceef9d22660206c3f0 Mon Sep 17 00:00:00 2001 From: Changyong Gong Date: Tue, 24 Nov 2026 13:39:54 +0800 Subject: [PATCH 2/2] Verify branch protection when the OIDC claim is absent Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/issuelens/issuelens_action.py | 4 +- automation_bridge/bridge.py | 18 ++- automation_bridge/function_app.py | 9 ++ docs/guide.md | 9 +- tests/test_automation_bridge.py | 114 +++++++++++++++--- 5 files changed, 129 insertions(+), 25 deletions(-) diff --git a/.github/actions/issuelens/issuelens_action.py b/.github/actions/issuelens/issuelens_action.py index e9fdba3..4b8ae92 100644 --- a/.github/actions/issuelens/issuelens_action.py +++ b/.github/actions/issuelens/issuelens_action.py @@ -88,9 +88,9 @@ def github_request(path, payload=None, *, token=None): ) -def github_read(path, payload=None, *, token=None): +def github_read(path, payload=None, *, token=None, timeout=30): request = github_request(path, payload, token=token) - with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response: + with urllib.request.build_opener(NoRedirect()).open(request, timeout=timeout) as response: data = response.read(4 * 1024 * 1024 + 1) require(len(data) <= 4 * 1024 * 1024, "GitHub response exceeds the preflight limit") result = json.loads(data) diff --git a/automation_bridge/bridge.py b/automation_bridge/bridge.py index 9b04ebc..5eae5ef 100644 --- a/automation_bridge/bridge.py +++ b/automation_bridge/bridge.py @@ -26,7 +26,8 @@ _spec.loader.exec_module(action) PILOT_REPOSITORY = action.COORDINATOR_REPOSITORY -BRANCH = "refs/heads/main" +PILOT_BRANCH = "main" +BRANCH = f"refs/heads/{PILOT_BRANCH}" ISSUE_WORKFLOW = ".github/workflows/issue-triage.yml" MEMORY_WORKFLOW = action.COORDINATOR_WORKFLOW WORKFLOWS = { @@ -62,9 +63,11 @@ def workflow_claims(token: str, audience: str, repository_id: int) -> dict: and claims["repository_id"] == str(repository_id) and claims["repository_visibility"] == "public" and claims["ref"] == BRANCH - and claims.get("ref_protected") in {"true", True} and claims.get("runner_environment") == "github-hosted", - "Workflow is not in the protected IssueLens pilot scope") + "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") @@ -80,6 +83,13 @@ def workflow_ref(path: str) -> str: return f"{PILOT_REPOSITORY}/{path}@{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), + "Invalid GitHub branch protection response") + return branch["protected"] + + def job_id(claims: dict) -> str: return hashlib.sha256( f"v1:{claims['repository_id']}:{claims['kind']}:{claims['run_id']}".encode("ascii") @@ -153,7 +163,7 @@ def _validate_merge(merge: dict): def _memory_job(metadata: dict, claims: dict) -> str: require(metadata.get("repository_id") == claims["repository_id"] - and metadata.get("base_ref") == "main" + 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_workflow_ref") == claims["workflow_ref"] diff --git a/automation_bridge/function_app.py b/automation_bridge/function_app.py index f7ad7ce..c7569e6 100644 --- a/automation_bridge/function_app.py +++ b/automation_bridge/function_app.py @@ -1,5 +1,6 @@ """Azure Functions entry point. Deploy the same bundle as ingress and worker.""" +import http.client import json import logging import os @@ -83,6 +84,14 @@ 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) identifier = bridge.job_id(claims) try: job = jobs().reserve(identifier, target, body) diff --git a/docs/guide.md b/docs/guide.md index 0fa89f3..8007e60 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1073,9 +1073,16 @@ 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, protected `main`, 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 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. | | 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 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 diff --git a/tests/test_automation_bridge.py b/tests/test_automation_bridge.py index 523a8fb..303e984 100644 --- a/tests/test_automation_bridge.py +++ b/tests/test_automation_bridge.py @@ -1,4 +1,5 @@ import hashlib +import importlib.util import json import os import pathlib @@ -14,6 +15,7 @@ import jwt from azure.data.tables import TableTransactionError +from azure.functions import HttpRequest from cryptography.hazmat.primitives.asymmetric import rsa from automation_bridge import bridge, bundle @@ -53,30 +55,56 @@ class BridgeIdentityTests(unittest.TestCase): def setUpClass(cls): cls.key = rsa.generate_private_key(public_exponent=65537, key_size=2048) - def test_only_the_protected_pilot_workflow_can_submit_or_read_its_job(self): + def setUp(self): now = int(time.time()) - claims = { + 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, "ref_protected": "true", "runner_environment": "github-hosted", + "ref": bridge.BRANCH, "runner_environment": "github-hosted", "workflow_ref": bridge.workflow_ref(bridge.ISSUE_WORKFLOW), "workflow_sha": "1" * 40, "event_name": "issue_comment", "actor": "maintainer", "run_id": "20", "run_attempt": "1", } - with patch.object(bridge.KEYS, "get_signing_key_from_jwt", return_value=Mock(key=self.key.public_key())): - accepted = bridge.workflow_claims(jwt.encode(claims, self.key, algorithm="RS256"), URL, 100) - self.assertEqual(bridge.validate_request(issue_payload(), accepted), "issue-12") - for alteration in ( - {"repository_id": "101"}, {"ref_protected": "false"}, {"repository_visibility": "private"}, - {"event_name": "pull_request"}, {"workflow_ref": bridge.workflow_ref("another.yml")}, - {"aud": ENDPOINT}, {"exp": now - 1}, - ): - with self.subTest(alteration=alteration), self.assertRaises((ValueError, jwt.PyJWTError)): - bridge.workflow_claims(jwt.encode(claims | alteration, self.key, algorithm="RS256"), URL, 100) - with self.assertRaises(jwt.InvalidSignatureError): - bridge.workflow_claims( - jwt.encode(claims, rsa.generate_private_key(public_exponent=65537, key_size=2048), algorithm="RS256"), - URL, 100, - ) + self.enterContext(patch.object(bridge.KEYS, "get_signing_key_from_jwt", return_value=Mock(key=self.key.public_key()))) + + def token(self, **overrides): + return jwt.encode(self.claims | overrides, self.key, algorithm="RS256") + + def load_ingress(self): + self.enterContext(patch.dict(os.environ, { + "ISSUELENS_BRIDGE_ROLE": "ingress", "ISSUELENS_BRIDGE_REPOSITORY_ID": "100", + "ISSUELENS_BRIDGE_OIDC_AUDIENCE": URL, "ISSUELENS_BRIDGE_QUEUE": "test-jobs", + })) + path = pathlib.Path(bridge.__file__).with_name("function_app.py") + spec = importlib.util.spec_from_file_location("test_bridge_ingress", path) + assert spec is not None and spec.loader is not None + ingress = importlib.util.module_from_spec(spec) + with patch.dict(sys.modules, {"bridge": bridge}): + spec.loader.exec_module(ingress) + 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()}"} + 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()) + + def test_only_the_expected_workflow_identity_is_accepted(self): + accepted = bridge.workflow_claims(self.token(ref_protected="true"), URL, 100) + self.assertEqual(bridge.validate_request(issue_payload(), accepted), "issue-12") + for alteration in ( + {"repository_id": "101"}, {"ref": "refs/heads/other"}, {"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) + with self.assertRaises(jwt.InvalidSignatureError): + bridge.workflow_claims( + jwt.encode(self.claims, rsa.generate_private_key(public_exponent=65537, key_size=2048), algorithm="RS256"), + URL, 100, + ) 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})) for invalid in ( @@ -87,6 +115,56 @@ def test_only_the_protected_pilot_workflow_can_submit_or_read_its_job(self): with self.subTest(invalid=invalid), self.assertRaises(ValueError): bridge.validate_request(invalid, accepted) + 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}) + 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}' + 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()) + self.assertEqual(queued.status_code, 202, queued.get_body()) + self.assertEqual(json.loads(queued.get_body()), {"job_id": identifier, "state": bridge.QUEUED}) + jobs.return_value.reserve.assert_called_once() + sender = bus.return_value.get_queue_sender.return_value.__enter__.return_value + sender.send_messages.assert_called_once() + + completed = status(self.request(identifier)) + self.assertEqual(completed.status_code, 200, completed.get_body()) + 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(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"})), + ): + with ( + self.subTest(response=response), + patch.object(bridge.action, "github_read", side_effect=[response]) 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() + jobs.assert_not_called() + bus.assert_not_called() + + 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"