Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
2 changes: 2 additions & 0 deletions PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ Actions visibility and runner evaluation.
- `docs/bugs/fixed/runner-self-delete-leaves-jobs-pointing-at-it.md`
- `docs/bugs/fixed/app-logs-silenced-after-the-startup-migration.md`
- `docs/bugs/fixed/runners-registering-together-lose-their-tokens.md`
- `docs/bugs/fixed/github-context-identity-values-are-empty.md`
- `docs/bugs/fixed/rendered-github-context-differs-from-github.md`

## Decisions

Expand Down
44 changes: 44 additions & 0 deletions docs/bugs/fixed/github-context-identity-values-are-empty.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Bug: the github context's identity values are empty

Status: fixed 2026-11-18.

## Summary

Compared with the same workflow run on GitHub, these `github` context values
were empty in expressions the emulator rendered (a step's `env:`, `run:` and
`with:`): `actor`, `actor_id`, `triggering_actor`, `api_url`, `graphql_url`,
`repository_id`, `repository_owner_id`, `run_attempt` and `workflow_ref`.

The job message's github context, which the runner exports as `GITHUB_*`
variables, lacked `actor`, `actor_id`, `triggering_actor` and `workflow_ref`, so
`GITHUB_ACTOR`, `GITHUB_ACTOR_ID`, `GITHUB_TRIGGERING_ACTOR` and
`GITHUB_WORKFLOW_REF` were unset in every step. The other five were already
there.

The REST run and job objects also lacked fields GitHub fills: runs had no
`run_started_at` or `display_title`, and jobs had no `created_at`, `head_sha`
or `head_branch`.

## Fix

- Server-side rendering and the job message's github context carry the nine
values. Ids and `run_attempt` are strings, as GitHub gives them.
- Runs report `run_started_at` and `display_title`: the head commit's first
line (a push payload now carries `head_commit`), the pull request's or issue's title, or the workflow name.
- Jobs report `created_at`, `head_sha` and `head_branch`.
- A re-run renders its own `github.run_attempt`: the attempt is set before the
steps render, and the re-run's jobs report it too.

## Known gaps

- A re-run is a new run whose actor is the user who asked for it, so
`actor` and `triggering_actor` are both that user. On GitHub `actor` stays
the user who started the first attempt.
- `display_title` does not use the workflow's `run-name:`.

Tests: `tests/actions/test_github_identity_context.py`
(`test_step_env_renders_the_identity_values`,
`test_the_job_message_carries_them_for_the_runner`,
`test_run_and_job_fields_github_fills`,
`test_a_rerun_renders_its_own_attempt`,
`test_a_push_run_is_titled_by_its_commit_and_knows_branch_protection`).
77 changes: 77 additions & 0 deletions docs/bugs/fixed/rendered-github-context-differs-from-github.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Bug: the rendered github context differs from GitHub's

Status: fixed 2026-11-18.

## Summary

Compared with the same workflow on GitHub, the emulator's server-side
rendering of a step's `run:`, `with:` and `env:` differed:

| Expression | GitHub | Emulator |
| --- | --- | --- |
| a `false` value, e.g. `${{ inputs.flag }}` | `false` | `False` |
| a `false` comparison, e.g. `${{ github.event_name == 'x' }}` | `false` | empty |
| `${{ a \|\| b }}` with `a` empty and `b` false | `false` | `False` |
| `github.ref_name`, `ref_type`, `ref_protected`, `workflow_sha`, `repository_visibility`, `repositoryUrl`, `retention_days` | set | empty |
| `github.token`, `github.workspace`, `github.job`, `github.event_path`, `github.action`, `job.status` ... | the runner's value | empty |
| `${{ github.token != '' }}` | `true` | empty |

The runner exports `GITHUB_REF_NAME`, `GITHUB_REF_TYPE`,
`GITHUB_REF_PROTECTED` and `GITHUB_WORKFLOW_SHA` from the job message's github
context, and those keys were missing there, so the variables were unset.
`RUNNER_ENVIRONMENT` was unset too.

Two authentication answers differed as well:

- A job's `GITHUB_TOKEN` on `GET /installation/repositories` got 403
"Resource not accessible by personal access token". On GitHub
`GITHUB_TOKEN` is an installation token, and the route lists the run's
repository. Clients that probe this route to tell an installation token
from a personal access token took a job token for a PAT.
- A refused credential (unknown, revoked or expired) got 401 "Requires
authentication". GitHub answers "Bad credentials" and keeps "Requires
authentication" for a request that sent none.

## Fix

- A false result renders `false`, a null one stays empty, and `a || b` is the
first truthy alternative, else the last.
- The ref, sha and repository facts are filled (`ref_protected` as a boolean: whether the branch is protected) for rendering and in the job
message's github context. `RUNNER_ENVIRONMENT` is `github-hosted`.
- An expression that reads a value only the runner knows is left for the
runner, with the server's own contexts bound in, in `run:`, `with:` and
`env:`. Elsewhere (a concurrency group, say) nothing evaluates it again, so
it still renders empty. `job.workflow_*` stay the server's: the runner has
no job context for them.
- A server value bound into an expression left for the runner quotes a quote
the Actions way (`''`), not with a backslash, which the runner rejects. An
object or array is bound whole (`fromJSON('...')`), so a function or
`a && b` gets the value; the runner applies truthiness itself. A bound string that holds a brace is bound as JSON
too, with its braces escaped, so event data such as an issue title can
never end the expression it is bound into.
- `working-directory` and `shell` are left for the runner the same way as
`run`.
- In `run:`, `with:`, `env:`, `working-directory` and `shell`, which the runner
renders again, a value the server resolved that holds `$`, `{` or `}` (an
issue title, say) is sent as an expression that yields the text itself, so
the runner never evaluates it, even where two values or a value and the
text beside it would together spell `${{`.
- Index notation (`github['workspace']`) is recognised like dot notation and
sent to the runner in dot form.
- A `'...'` literal's only escape is a doubled quote, as in Actions, in the
server's and the emulator runner's tokenizers and decoders alike; a
backslash is an ordinary character, so bound JSON keeps its escapes and a
value may end in a backslash.
- The emulator's own runner finishes what the server leaves: it reads `''`
inside a string, writes a false result as `false`, knows `job.status`, has
`fromJSON`, `toJSON` and `join`, the `<`, `>`, `<=` and `>=` operators, a
leading `!`, `.name` and `[index]` after a call, and compares with `==` as
Actions does (strings case-insensitively), and gives `github.env`, `github.output`,
`github.path` and `github.event_path` their file paths.
- `GET /installation/repositories` with a job token lists the run's
repository with `repository_selection: selected`. A personal access token
still gets 403.
- A 401 says "Bad credentials" when an `Authorization` header was sent.

Tests: `tests/actions/test_render_github_parity.py`,
`tests/actions/test_job_token_installation_routes.py`.
48 changes: 35 additions & 13 deletions src/app/api/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,27 @@

from fastapi import APIRouter, HTTPException, Query, Request
from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse, Response, StreamingResponse
from sqlalchemy import select, func, or_
from sqlalchemy import func, or_, select

from app.api.deps import AuthUser, CurrentUser, DbSession, get_repo_or_404
from app.api.pagination import pagination_links
from app.services import artifact_storage, repository_access
from app.config import settings
from app.models.actions import Workflow, WorkflowRun, WorkflowJob, Secret, Variable
from app.models.actions import Secret, Variable, Workflow, WorkflowJob, WorkflowRun
from app.models.artifact import WorkflowArtifact
from app.services.secret_crypto import (
SecretDecryptError,
open_sealed_secret,
repo_public_key,
)
from app.schemas.user import SimpleUser, _fmt_dt, _make_node_id
from app.schemas.actions import (
WorkflowJobListResponse,
WorkflowJobResponse,
WorkflowListResponse,
WorkflowRunListResponse,
WorkflowRunResponse,
)
from app.schemas.user import SimpleUser, _fmt_dt, _make_node_id
from app.services import artifact_storage, repository_access
from app.services.secret_crypto import (
SecretDecryptError,
open_sealed_secret,
repo_public_key,
)

router = APIRouter(tags=["actions"])

Expand All @@ -48,6 +48,21 @@ def _workflow_json(w: Workflow, owner: str, repo: str) -> dict:
}


def _display_title(r: WorkflowRun) -> str:
"""GitHub's event-specific run title: the head commit's first line for a
push, the pull request's or issue's title for those events, and the
workflow's name otherwise (a dispatch, for one)."""
payload = r.trigger_payload or {}
for key in ("pull_request", "issue"):
title = (payload.get(key) or {}).get("title")
if title:
return str(title)
message = (payload.get("head_commit") or {}).get("message")
if message:
return str(message).splitlines()[0]
return r.workflow.name if r.workflow else ""
Comment thread
waynesun09 marked this conversation as resolved.
Resolved


def _run_json(
r: WorkflowRun, owner: str, repo: str, referenced_workflows: list[dict] | None = None,
) -> dict:
Expand All @@ -73,6 +88,9 @@ def _run_json(
"html_url": f"{BASE}/{owner}/{repo}/actions/runs/{r.id}",
"created_at": _fmt_dt(r.created_at),
"updated_at": _fmt_dt(r.updated_at),
# This emulator starts an attempt when it creates it.
"run_started_at": _fmt_dt(r.created_at),
"display_title": _display_title(r),
"actor": actor,
}

Expand All @@ -84,8 +102,11 @@ def _job_json(j: WorkflowJob, owner: str, repo: str) -> dict:
"run_id": j.run_id,
"name": j.name,
"workflow_name": j.workflow_name,
"head_sha": j.run.head_sha if j.run else None,
"head_branch": j.run.head_branch if j.run else None,
"status": j.status,
"conclusion": j.conclusion,
"created_at": _fmt_dt(j.created_at),
"started_at": _fmt_dt(j.started_at),
"completed_at": _fmt_dt(j.completed_at),
"steps": j.steps or [],
Expand Down Expand Up @@ -417,7 +438,7 @@ async def list_workflows(
"""List workflows."""
repository = await get_repo_or_404(owner, repo, db)
await _check_read_access(db, repository, current_user)
from app.services.workflow_service import materialize_reusable_workflows, sync_workflows_to_db
from app.services.workflow_service import sync_workflows_to_db

await sync_workflows_to_db(db, repository, "HEAD")
await db.commit()
Expand Down Expand Up @@ -626,7 +647,9 @@ async def rerun_workflow(
rerun sat with every dependent waiting forever (2026-09-27, run 1589).
"""
from app.services.workflow_service import (
create_workflow_run, detect_workflows, materialize_reusable_workflows,
create_workflow_run,
detect_workflows,
materialize_reusable_workflows,
)
repository = await get_repo_or_404(owner, repo, db)
await _require_repository_role(request, db, repository, user, "push")
Expand Down Expand Up @@ -659,9 +682,8 @@ async def rerun_workflow(
)
new_run = await create_workflow_run(
db, workflow, workflow_yaml, run.event, payload, user,
run.head_sha, run.head_branch,
run.head_sha, run.head_branch, run_attempt=run.run_attempt + 1,
)
new_run.run_attempt = run.run_attempt + 1
await db.commit()
await db.refresh(new_run)
from app.services.workflow_service import dispatch_ready_jobs
Expand Down
46 changes: 38 additions & 8 deletions src/app/api/actions_distributed_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,12 @@
)
from app.services.auth_service import hash_token
from app.services.job_token_service import validate_job_token
from app.services.workflow_service import check_run_completion, dispatch_ready_jobs
from app.services.workflow_service import (
_branch_protected,
check_run_completion,
dispatch_ready_jobs,
static_github_facts,
)

router = APIRouter(tags=["actions-distributed-task"])
# Under github_emulator, which app.main sends to the server log: job
Expand Down Expand Up @@ -569,11 +574,22 @@ async def dt_delete_pool_agent(
return {"status": "removed"}


def _message_ref(run: WorkflowRun | None) -> str:
"""The full ref the job message names: the event's, else the run's branch."""
ref = (
(run.trigger_payload or {}).get("ref")
if run and isinstance(run.trigger_payload, dict)
else None
)
return ref or f"refs/heads/{run.head_branch if run else 'main'}"


def _job_request_message(
job: WorkflowJob,
run: WorkflowRun | None,
repo: Repository | None = None,
base_url: str | None = None,
ref_protected: bool = False,
) -> dict:
timeline_id = _workflow_guid("timeline", job.id)
job_guid = _workflow_guid("job", job.id)
Expand All @@ -582,12 +598,7 @@ def _job_request_message(
access_token = _job_access_token(job)
repo_full_name = repo.full_name if repo else "unknown/unknown"
repo_owner = repo_full_name.split("/", 1)[0]
ref = (
(run.trigger_payload or {}).get("ref")
if run and isinstance(run.trigger_payload, dict)
else None
)
ref = ref or f"refs/heads/{run.head_branch if run else 'main'}"
ref = _message_ref(run)
sha = run.head_sha if run else "0" * 40
workflow_name = job.workflow_name or job.name
# Actions OIDC, as the upstream runner sees it. The runner's own plumbing
Expand Down Expand Up @@ -651,6 +662,9 @@ def _job_request_message(
# documents notice as a workflow command beside warning and
# error, rendered as `##[notice]` in the job log.
"DistributedTask.EnhancedAnnotations": _variable("true"),
# runner.environment and RUNNER_ENVIRONMENT. The jobs stand in for
# GitHub-hosted ones, which is what workflows here are written for.
"system.runnerEnvironment": _variable("github-hosted"),
},
"contextData": {
# The runner expands an expression only when every context the
Expand All @@ -671,6 +685,8 @@ def _job_request_message(
}),
"matrix": None,
"github": _context_dictionary({
"actor": run.actor.login if run and run.actor else "",
"actor_id": str(run.actor_id) if run and run.actor_id else "",
"api_url": f"{runner_base_url}/api/v3",
"base_ref": "",
"event_name": run.event if run else "workflow_dispatch",
Expand All @@ -691,8 +707,18 @@ def _job_request_message(
"server_url": runner_base_url,
"sha": sha,
"token": access_token,
"triggering_actor": run.actor.login if run and run.actor else "",
"workflow": workflow_name,
"workflow_ref": (
f"{repo_full_name}/{run.workflow.path}@{ref}"
if run and run.workflow and run.workflow.path else ""
),
"workspace": "",
# ref_name, ref_type, ref_protected, workflow_sha and the
# rest: the runner exports the first four as GITHUB_* env.
**static_github_facts(
ref, sha, repo_full_name, repo.private if repo else None, ref_protected,
),
}),
},
"resources": {
Expand Down Expand Up @@ -916,7 +942,11 @@ async def _claim_next_job(
repo_result = await db.execute(select(Repository).where(Repository.id == run.repo_id))
repo = repo_result.scalar_one_or_none()

return _job_request_message(job, run, repo, base_url)
# Looked up here, on the async session, rather than through
# repo.branches: the message builder is synchronous and must not load a
# relationship.
ref_protected = await _branch_protected(db, run.repo_id if run else None, _message_ref(run))
return _job_request_message(job, run, repo, base_url, ref_protected)


async def _update_timeline_for_job(job: WorkflowJob, body: dict, db) -> None:
Expand Down
25 changes: 25 additions & 0 deletions src/app/api/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,31 @@ async def list_token_installation_repositories(
personal access token must be refused with 403 rather than a missing route.
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
"""
installation_token = getattr(request.state, "installation_token", None)
workflow_run = getattr(request.state, "workflow_run", None)
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
if current_user is None:
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
# A revoked or unknown token, as on GitHub; a missing one is the
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
# usual "Requires authentication".
raise HTTPException(
status_code=401,
detail="Bad credentials" if request.headers.get("authorization") else "Requires authentication",
)
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
Comment thread
waynesun09 marked this conversation as resolved.
Resolved
if installation_token is None and workflow_run is not None:
# A job's GITHUB_TOKEN is an installation token for the run's one
# repository. Answering 403 made clients that probe this route
# (fullsend's IsInstallationToken) take a job token for a PAT.
# Columns only: the entity eagerly loads issues, labels, branches ...
repos = (await db.execute(
select(Repository.id, Repository.full_name, Repository.name, Repository.private)
.where(Repository.id == workflow_run.repo_id)
)).all()
return {
"total_count": len(repos),
"repository_selection": "selected",
"repositories": [
{"id": r.id, "full_name": r.full_name, "name": r.name, "private": r.private}
for r in repos
],
}
if installation_token is None:
raise HTTPException(
status_code=403,
Expand Down
Loading
Loading