Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions .github/actions/issuelens/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ and result validation. No inline Python, pip installation, container build, or
GitHub App private key is required.

The [Function bridge pilot](../../../docs/guide.md#issuelens-function-bridge-pilot)
uses GitHub workflow identity for `microsoft/IssueLens` only. It submits typed
metadata after the same preflight, skips Azure login, and polls the job receipt.
is a deployment-specific example, not a restriction on where this reusable action
can be used. Configured bridge deployments determine which workflow identities
and request types they accept. The action submits typed metadata after the same
preflight, skips Azure login, and polls the job receipt.
The worker authenticates to the existing `/invocations` endpoint using managed
identity and submits the normal `{ "input": "..." }` request.
It has no direct fallback or free-form task path. It does not stream or store
Expand Down Expand Up @@ -375,7 +377,7 @@ identity check is not authorization for any additional repositories named by a t
| `source-run-id` | For coordinated automatic `team-memory` | Positive source push run ID. |
| `source-run-attempt` | With `source-run-id` | Positive originating run attempt. |
| `push-before`, `push-after` | With `source-run-id` | Full nonzero requested ancestor/source-run-head SHAs. Supply all four run/range inputs, never with `pull-request-number`. Before is not an attested original event boundary. |
| `transport` | No | `foundry` (default for existing callers) or `bridge` (IssueLens pilot only). |
| `transport` | No | `foundry` (default for existing callers) or `bridge` (reviewed pilot workflows only). |
| `bridge-url` | For `bridge` | Complete approved HTTPS Azure Function jobs endpoint. Pass it from the `ISSUELENS_BRIDGE_URL` Actions secret, not a configuration variable. |
| `azure-client-id` | For `foundry` | Existing Azure OIDC identity's client ID. |
| `azure-tenant-id` | For `foundry` | Tenant used by Azure login. |
Expand Down
5 changes: 5 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,11 @@ The agent is driven by a workflow in the target repo
Azure Function bridge with a bridge-audience GitHub Actions token. The
Function verifies GitHub identity without exchanging the token for Entra
credentials. No App webhook or corporate FIC is used.
The bridge's reviewed ingress Function App allowlist setting additionally
admits `microsoft/vscode-java-pack` for manual issue-loop dispatch from any
workflow on its protected default branch; it grants no automatic events or
team-memory. `automation_bridge/repository_allowlist.example.json` documents
the initial setting value; it is not loaded from the Function ZIP.
2. The worker uses its managed identity to POST the existing `{ input }`
payload to the deployed agent's `/invocations` API. Bridge validation and
queueing stay outside the hosted agent. The agent remains independently
Expand Down
101 changes: 74 additions & 27 deletions automation_bridge/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,6 @@

PILOT_REPOSITORY = action.COORDINATOR_REPOSITORY
PILOT_BRANCH = "main"
BRANCH = f"refs/heads/{PILOT_BRANCH}"
ISSUE_WORKFLOW = ".github/workflows/issue-triage.yml"
MEMORY_WORKFLOW = action.COORDINATOR_WORKFLOW
WORKFLOWS = {
ISSUE_WORKFLOW: ("issue-loop", {"issues", "issue_comment", "workflow_dispatch"}),
MEMORY_WORKFLOW: ("team-memory", {"workflow_dispatch"}),
}
GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
KEYS = jwt.PyJWKClient(GITHUB_ISSUER + "/.well-known/jwks", timeout=5)
JOB_ID = re.compile(r"[0-9a-f]{64}")
Expand All @@ -49,7 +42,21 @@ class BusyError(Exception):
"""A different job still owns the target reservation."""


def workflow_claims(token: str, audience: str, repository_id: int) -> dict:
def load_repository_allowlist(value: str, pilot_repository_id: int) -> frozenset[int]:
require(isinstance(value, str) and 0 < len(value.encode("utf-8")) <= 32 * 1024,
"Invalid bridge repository allowlist size")
ids = json.loads(value, object_pairs_hook=action.unique_object)
require(isinstance(ids, list) and ids
and all(type(identifier) is int and identifier > 0 for identifier in ids)
and len(set(ids)) == len(ids)
and type(pilot_repository_id) is int and pilot_repository_id in ids,
"Invalid bridge repository ID allowlist")
return frozenset(ids)


def workflow_claims(token: str, audience: str, pilot_repository_id: int, allowlist: frozenset[int]) -> dict:
require(type(pilot_repository_id) is int and pilot_repository_id in allowlist,
"Configured IssueLens repository ID does not match the bridge allowlist")
require(len(token) <= 16 * 1024, "Invalid workflow token size")
key = KEYS.get_signing_key_from_jwt(token)
claims = jwt.decode(
Expand All @@ -59,33 +66,72 @@ def workflow_claims(token: str, audience: str, repository_id: int) -> dict:
"ref", "workflow_ref", "workflow_sha", "event_name", "run_id", "run_attempt", "actor",
], "strict_aud": True},
)
require(claims["repository"] == PILOT_REPOSITORY
and claims["repository_id"] == str(repository_id)
require(isinstance(claims["repository"], str)
and re.fullmatch(r"[A-Za-z0-9-]+/[A-Za-z0-9_.-]+", claims["repository"])
and isinstance(claims["repository_id"], str)
and claims["repository_id"].isdecimal()
and int(claims["repository_id"]) in allowlist
and (int(claims["repository_id"]) != pilot_repository_id
or claims["repository"] == PILOT_REPOSITORY)
and (claims["repository"] != PILOT_REPOSITORY
or int(claims["repository_id"]) == pilot_repository_id)
Comment thread
chagong marked this conversation as resolved.
Resolved
and claims["repository_visibility"] == "public"
and claims["ref"] == BRANCH
and isinstance(claims["ref"], str) and claims["ref"].startswith("refs/heads/")
and claims.get("runner_environment") == "github-hosted",
"Workflow is not in the IssueLens pilot scope")
if "ref_protected" in claims:
protected = claims["ref_protected"]
require(protected is True or protected == "true", "Workflow ref was not protected")
for path, (kind, events) in WORKFLOWS.items():
if claims["workflow_ref"] == workflow_ref(path):
require(claims["event_name"] in events, "Unsupported workflow event")
return {
**claims, "kind": kind, "repository_id": repository_id,
"run_id": action.positive(claims["run_id"]), "run_attempt": action.positive(claims["run_attempt"]),
"workflow_sha": action.full_sha(claims["workflow_sha"]),
}
raise ValueError("Workflow is not enabled for this bridge")
if claims["repository"] == PILOT_REPOSITORY:
if claims["workflow_ref"] == workflow_ref(".github/workflows/issue-triage.yml"):
require(claims["event_name"] in {"issues", "issue_comment", "workflow_dispatch"},
"Unsupported workflow event")
elif claims["workflow_ref"] == workflow_ref(action.COORDINATOR_WORKFLOW):
require(claims["event_name"] == "workflow_dispatch", "Unsupported workflow event")
return _validated_claims(claims, "team-memory", int(claims["repository_id"]))
else:
raise ValueError("Workflow is not enabled for this bridge")
else:
prefix = f"{claims['repository']}/.github/workflows/"
suffix = "@" + claims["ref"]
require(claims["event_name"] == "workflow_dispatch"
and isinstance(claims["workflow_ref"], str)
and claims["workflow_ref"].startswith(prefix)
and claims["workflow_ref"].endswith(suffix)
and re.fullmatch(r"[A-Za-z0-9_.-]+\.ya?ml", claims["workflow_ref"][len(prefix):-len(suffix)]),
Comment thread
chagong marked this conversation as resolved.
Resolved
"Only manual workflow dispatches from enrolled repositories are allowed")
return _validated_claims(claims, "issue-loop", int(claims["repository_id"]))


def _validated_claims(claims: dict, kind: str, repository_id: int) -> dict:
return {
**claims, "kind": kind, "repository_id": repository_id,
"run_id": action.positive(claims["run_id"]), "run_attempt": action.positive(claims["run_attempt"]),
"workflow_sha": action.full_sha(claims["workflow_sha"]),
}


def workflow_ref(path: str) -> str:
return f"{PILOT_REPOSITORY}/{path}@{BRANCH}"
def workflow_ref(path: str, repository: str = PILOT_REPOSITORY, branch: str = PILOT_BRANCH) -> str:
return f"{repository}/{path}@refs/heads/{branch}"


def pilot_branch_protected() -> bool:
branch = action.github_read(f"/repos/{PILOT_REPOSITORY}/branches/{PILOT_BRANCH}", token="", timeout=5)
require(branch.get("name") == PILOT_BRANCH and isinstance(branch.get("protected"), bool),
def default_branch_protected(claims: dict) -> bool:
repository = claims["repository"]
project = action.github_read(f"/repos/{repository}", token="", timeout=5)
branch_name = project.get("default_branch")
require(isinstance(project.get("full_name"), str) and type(project.get("id")) is int
and type(project.get("private")) is bool and isinstance(project.get("visibility"), str)
and isinstance(branch_name, str) and branch_name,
"Invalid GitHub repository response")
if (project["full_name"].casefold() != repository.casefold()
or project["id"] != claims["repository_id"] or project["private"]
or project["visibility"] != "public" or claims["ref"] != f"refs/heads/{branch_name}"):
return False
if "ref_protected" in claims:
return True
branch_path = urllib.parse.quote(branch_name, safe="")
branch = action.github_read(f"/repos/{repository}/branches/{branch_path}", token="", timeout=5)
require(branch.get("name") == branch_name and isinstance(branch.get("protected"), bool),
"Invalid GitHub branch protection response")
return branch["protected"]

Expand Down Expand Up @@ -213,9 +259,10 @@ def _memory_job(metadata: dict, claims: dict) -> str:
def validate_request(data: dict, claims: dict) -> str:
require(isinstance(data, dict) and set(data) == {"request_type", "metadata"}
and data["request_type"] == claims["kind"] and isinstance(data["metadata"], dict)
and data["metadata"].get("repository") == PILOT_REPOSITORY, "Invalid workflow job")
and data["metadata"].get("repository") == claims["repository"], "Invalid workflow job")
validator = _issue_job if claims["kind"] == "issue-loop" else _memory_job
return validator(data["metadata"], claims)
target = validator(data["metadata"], claims)
return target if claims["repository"] == PILOT_REPOSITORY else f"repo-{claims['repository_id']}-{target}"


class JobStore:
Expand Down
21 changes: 13 additions & 8 deletions automation_bridge/function_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,17 @@ def authorized(request):
return bridge.workflow_claims(
auth[len("Bearer "):], os.environ["ISSUELENS_BRIDGE_OIDC_AUDIENCE"],
bridge.action.positive(os.environ["ISSUELENS_BRIDGE_REPOSITORY_ID"]),
repository_ids,
)


role = os.environ.get("ISSUELENS_BRIDGE_ROLE")
if role == "ingress":
pilot_repository_id = bridge.action.positive(os.environ["ISSUELENS_BRIDGE_REPOSITORY_ID"])
repository_ids = bridge.load_repository_allowlist(
os.environ.get("ISSUELENS_BRIDGE_REPOSITORY_ALLOWLIST", ""), pilot_repository_id,
)

@app.route(route="issuelens/v1/jobs", methods=["POST"], trigger_arg_name="request")
def submit(request: func.HttpRequest) -> func.HttpResponse:
try:
Expand All @@ -84,14 +90,13 @@ def submit(request: func.HttpRequest) -> func.HttpResponse:
target = bridge.validate_request(data, claims)
except (ValueError, TypeError):
return respond({"error": "invalid_job"}, 400)
if "ref_protected" not in claims:
try:
protected = bridge.pilot_branch_protected()
except (OSError, http.client.HTTPException, ValueError):
logger.warning("GitHub branch protection unavailable")
return respond({"error": "branch_protection_unavailable"}, 503)
if not protected:
return respond({"error": "workflow_not_authorized"}, 401)
try:
protected = bridge.default_branch_protected(claims)
except (OSError, http.client.HTTPException, ValueError):
logger.warning("GitHub repository or branch validation unavailable")
return respond({"error": "branch_protection_unavailable"}, 503)
if not protected:
return respond({"error": "workflow_not_authorized"}, 401)
identifier = bridge.job_id(claims)
try:
job = jobs().reserve(identifier, target, body)
Expand Down
4 changes: 4 additions & 0 deletions automation_bridge/repository_allowlist.example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[
1303440932,
104967329
]
Loading