Repository navigation
Add scoped GitHub pull request operations to Code - #1081
Conversation
5217383 to
5be5637
Compare
|
@mjudeikis-bot review |
mjudeikis
left a comment
There was a problem hiding this comment.
No verified Critical findings. Two Warnings are traced through the code but not reproduced (both titled "Unverified"), plus three Notes and one unanchored Note.
Not anchored
- Note: the new verbs
githubevents/context,pullrequests/operateandrepositories/authorizehave nodataplane.ConformanceTest(AGENTS.md §606, §732).grep -rn ConformanceTest --include=*.gofinds no definition or caller anywhere in the tree, so I could not run one. The PR's own tests (server_test.go,native_routing_test.go) cover routing and the happy/refusal paths, but nothing asserts the Gate-then-act-as-provider order for these three verbs. Worth either adding the harness call or noting where it will land.
Checked
Read beyond the diff:
githubworkflow/{server,operations,task_authorization,github,ci,inline_review}.goin full;controller/pullrequest/controller.goReconcile,advance,open,fail;backend/interface.goRegistry.Get;backend/github/snapshot.goguarded push;main.gocodeDataPlaneHandler;controller_manager.gowiring;catalogentry.goroute filtering;manifest.yamlvsdeploy/chart/templates/catalogentry.yaml.- Callers of
Server.Webhook: none outside tests (the PR body says the webhook is a follow-up).
Hunt outcomes:
- Correctness:
spec.numberadoption (controller.go:189); CI summary double counting (ci.go:80);commentop on an unopened PR (task_authorization.go:692). Revocation/tombstone ordering, deadline checks,hmac.Equaluse, strict JSON decoding (DisallowUnknownFields+ trailing-data check) and the guarded push (advanceGuarded+--force-with-lease) all read correct. - Concurrency: grant/revoke/publish all write via
Updatewith the read resourceVersion, so concurrent writers conflict rather than overwrite. No new goroutines or shared maps. The reconciler is watch-driven;RequeueAfteris used only for forge observation. No finding. - Tenancy/kcp: every client call goes through
Callers.AsProvider(cluster)with the cluster from the route/request;AuthorizeTaskrequiresIsForeignProvider(cluster). The proof-key trust model is the Unverified Warning on task_authorization.go:176. No new permission claims, noserviceaccounts/clusterrolesclaims. - Provider contract: verbs are served behind
dataplane.Gate; no bearer on a verb, no/api/*route;ServedVerbsmatchesmanifest.yamland the chartcatalogentry.yaml(checked by the existing catalog/subresource tests, which pass). Missing conformance harness noted above. - API/codegen/storage:
make codegen-code-providerregenerates with a cleangit status(deepcopy,config/crds,config/kcp, chartfiles/). New fields are optional with validation markers;taskAuthorizationRevocationsis alistType=mapkeyed onsourceUID. No removed or renamed fields. - Security:
X-Remote-*identity comes fromdataplane.ProxiedIdentityFrom; GitHub client pinshttps://api.github.com, refuses redirects, bounds response size; credentials are not placed in errors or status. The unrouted Webhook handler and its pre-signature reads are the Note on server.go:173. - Portal: not applicable, no portal files in the diff.
- Tests: the controller revocation race test,
TestPublicationUsesFrozenScopeAndExpectedParent,TestCleanReviewSuppressedAtCodeBoundaryand the guarded-push test each fail without the change they cover. No test coversspec.numberadoption withcommand == nil.
Commands run (providers/code unless stated):
go vet ./githubworkflow/... ./controller/... ./apis/... ./backend/...: clean.go test -count=1 ./githubworkflow/... ./controller/... ./apis/... ./backend/... ./actions/...: all ok.go build ./.../ fullgo test ./...: not completed,assets.go:22embedsportal/dist, which is not built in this checkout. The root package tests (native_routing_test.go,subresource_test.go,actions_catalog_test.go) were therefore not run by me;make verify-provider-contractexercises the manifest/chart parity and passed.make codegen-code-provider: no diff afterwards;./hack/ensure-boilerplate.sh: all files have the boilerplate.make verify-provider-contract: 21/21 pass, 0 permission-claim violations.- Root
make build/make lintandmake verify-portalkit: not run (no root Go, portalkit or portal changes).
E2E: not run. I did not find a Code-provider e2e target in the AGENTS.md §7 table that exercises GitHub App connections, and the hosted CI / cross-repo validation the PR body marks pending would be the place for that.
| } | ||
|
|
||
| // 1. The branch: advance it to the desired head when it is not there. | ||
| if pr.Status.Number == 0 && pr.Spec.Number > 0 { |
There was a problem hiding this comment.
Warning: Unverified: tenant-set spec.number bypasses the "branch is not this PR's to move" guard
spec.number is tenant-writable with only Minimum=1. Reconcile 1: a PullRequest with spec.number=N, spec.branch=<existing feature branch> and no desiredHead takes this branch, sets next.Status.Number=N, and step 3 then writes Status.Head = observed.Commit (the foreign branch head) after the observed.Head != pr.Spec.Branch check passes. Reconcile 2: the tenant sets desiredHead with baseCommit equal to that head; advance now sees Status.Number != 0, expected == current, so the expected == "" && Status.Number == 0 && current != "" refusal at line ~393 no longer applies and PublishSnapshot force-with-leases the branch. Later title/body edits also go through UpdatePullRequest on a PR the resource never opened. I traced this but did not run it; if it holds, adoption should be limited to spec.command PRs (or the existing-branch refusal kept for adopted PRs).
if pr.Status.Number == 0 && pr.Spec.Number > 0 && pr.Spec.Command != nil {
next.Status.Number = pr.Spec.Number
textChanged = false
next.Status.PublishedTextDigest = digest
}A CEL rule on spec.number requiring has(self.command) would enforce the same at admission.
There was a problem hiding this comment.
Confirmed and fixed in 022c178. Reproduced: a PullRequest with spec.number and no command adopted a foreign open PR and recorded its head as status.head, so the next desired head would have force-pushed it. Adoption now requires spec.command, the verified-command path where CheckPublication also requires spec.number to match the event's PR. Without a command the resource fails with "spec.number adopts an existing pull request only for a verified command". TestNumberAdoptionRequiresAVerifiedCommand fails on the previous controller. I enforced this in the controller rather than with a CEL rule, because a CEL rule would bump the PullRequest schema; I can add one if you want the check at admission time too.
| // taskSigningKey derives a Code-side key from the App webhook signing secret. | ||
| // The secret is present in the App binding already used to verify signed forge | ||
| // deliveries; domain separation keeps task authority proofs distinct. | ||
| func taskSigningKey(conn *api.Connection, data map[string][]byte) ([]byte, error) { |
There was a problem hiding this comment.
Warning: Unverified: grant proofs are keyed from the tenant-held webhook secret and stored in tenant-writable spec
taskSigningKey derives the HMAC key from data["webhookSecret"], read from the Connection's Secret in the tenant workspace, and both the grant (spec.command.task, with proof) and the tombstones (spec.taskAuthorizationRevocations) live in the PullRequest spec. Anyone who can read that Secret and update PullRequests can compute a valid proof/grantRef and scopeProof, add a grant for a caller of their choosing, or delete a tombstone to undo a revocation. The comments on PullRequestTaskAuthorization say tenant-authored values are not trusted without a valid proof, which only holds if that principal cannot read the Secret. I could not confirm which principals (for example an Agents runner service account) can read the Secret or update pullrequests in a consumer workspace, so this may be acceptable under the intended trust model; it deserves an explicit statement in docs/security.md or a key that is not tenant-readable (provider-held secret, or a status/private-kind record instead of spec).
// derive from a provider-held secret, not the tenant Secret
func taskSigningKey(providerKey []byte, conn *api.Connection) ([]byte, error) {
if len(providerKey) < 32 {
return nil, errors.New("task authority signing key is unavailable")
}
// ...same domain-separated SHA-256 over conn.UID + providerKey
}There was a problem hiding this comment.
Checked; not an escalation, but the trust model is now stated (README, "Coordinator task grants", 022c178). The Connection Secret that keys the proofs also holds the GitHub App private key (installationToken reads it from the same data). A principal who can read it can already act as the App on GitHub directly, so forging a grant adds no GitHub power. Inside Railgrid, every use of a grant re-runs the SubjectAccessReview for the named caller's create pullrequests/operate (authorizeTaskCaller), so a forged grant only borrows an already-authorized caller's authority. What remains is misattribution: work can be attributed to a caller who didn't request it. The README says this and says to limit Secret read and pullrequests update to principals trusted with the App key. A provider-held key with grants in provider-owned state would close that gap; it isn't implemented here.
| } | ||
| pending += workflowPending | ||
| failed += workflowFailed | ||
| summary = fmt.Sprintf("CI observation on `%s`: %d check runs (%d pending, %d failed, %d skipped/neutral); %d commit-status contexts. This observes available CI, not a merge approval or an assertion about unseen policy.", sha, count, pending, failed, skipped, status.Total) |
There was a problem hiding this comment.
Note: CI summary counts workflow runs in the check-run totals
pending += workflowPending and failed += workflowFailed (lines 78-79) run before the summary is formatted, so the first sentence reports "N check runs (P pending, F failed ...)" with P and F that include workflow runs, and the second sentence reports the workflow counts again. A repo with 3 check runs and 1 failed workflow run is reported as "3 check runs (... 1 failed)" and "1 current workflow runs (... 1 failed)", which misleads an operator reading it. Keep separate counters for the totals that drive state.
totalPending, totalFailed := pending+workflowPending, failed+workflowFailed
// format the check-run sentence with pending/failed, the workflow sentence with workflowPending/workflowFailed,
// and switch on totalFailed/totalPendingThere was a problem hiding this comment.
Fixed in 022c178. Check runs, commit-status contexts (now reported with their combined state) and workflow runs each keep their own counts in the summary, and only the combined totals decide state. TestCISummaryKeepsSourcesSeparate covers your example of 3 green check runs plus 1 failed workflow.
| if len(in.Body) > 16384 { | ||
| return nil, errors.New("PR status comment exceeds the Code limit") | ||
| } | ||
| e := &api.GitHubEvent{Spec: api.GitHubEventSpec{Repository: repositoryName(binding{repo: b.repo, conn: b.conn}), PullRequest: effectivePullRequestNumber(fresh)}} |
There was a problem hiding this comment.
Note: comment on a task PR that is not opened yet posts to /issues/0/comments
effectivePullRequestNumber(fresh) is 0 until the PR is created (the Status.Number/Spec.Number fallback at line 812), so a grant issuer calling operate with op: comment before the first publish builds /repos/<repo>/issues/0/comments. GitHub answers 404 and the caller sees "GitHub API returned HTTP 404", which points at the forge rather than the real cause. Refuse up front, as taskPullRequest already does for review.
number := effectivePullRequestNumber(fresh)
if number <= 0 {
return nil, errors.New("PR has not been opened yet; no status comment target")
}
e := &api.GitHubEvent{Spec: api.GitHubEventSpec{Repository: repositoryName(binding{repo: b.repo, conn: b.conn}), PullRequest: number}}There was a problem hiding this comment.
Fixed in 022c178. comment now refuses with "the pull request has not been opened yet; there is no status comment target" when there is no PR number. TestTaskStatusCommentRequiresAnOpenedPullRequest fails on the previous code.
| reply(w, 503, map[string]string{"error": "workspace unavailable"}) | ||
| return | ||
| } | ||
| b, err := s.binding(ctx, dyn, name, false) |
There was a problem hiding this comment.
Note: Webhook is unrouted, and does tenant-cluster reads before the signature check
Nothing in this PR registers Server.Webhook (no caller outside tests; the PR body says the webhook is a follow-up), so the handler, duplicateReceipt and the Events create path are dead code in production until then. When it is wired up, s.binding runs first: an unauthenticated request to /{cluster}/{name} costs a Connection get, a Secret load and a Repository get, and answers 404 for unknown connections but 403 for known ones, which tells a caller which connection names exist. Consider verifying the signature against a cached secret first, or returning the same status for both cases, and rate limiting the route when it is added.
There was a problem hiding this comment.
Handled in #1082, which mounts the route. There, every failure before the signature check returns the same 404 not found, with the cause logged server-side. The body is read and size-checked before any lookup, so an oversized unsigned request can't reveal a connection either. The route is tested through serve.New. Rate limiting the route is still open.
) * Support scoped repository work and typed decisions on Agents Runs * Keep Factory PR delegates on pinned per-run checkouts * Address Agents run handoff review findings * Fix Agents run lifecycle and trace review findings * Protect Code invocation scopes and repair resumed Run lifecycle * Recover unprojected approvals and preserve repository deadlines
- Delegation: start a child Run detached from the parent's tool-call context, so a parent timeout or lost lease no longer strands the child in Running; the parent still cancels the child explicitly. - startRun: a Pending row this request recorded but could not claim is failed with the real cause (or returned as admitted when another executor claimed it), instead of being handed to an idempotent retry as Reused with nothing executing it. - Terminal writes: retry transient store failures while the lease is still held, treat only a lost lease as lease loss, and accept a retry that finds an earlier attempt already committed. - Retry handback: an owned save that returns a run to Pending clears execution_owner and execution_lease_at itself, so a failed deferred ReleaseRunLease can no longer leave an unclaimable queued run. - Postgres: pass RunLeaseDuration to every lease-validity predicate instead of a hard-coded interval '2 minutes'. - Recovery: a run admitted before agent_uid existed takes its frozen Agent UID from the Run's owner reference, verified against the live Agent, instead of being failed. - Warm environments: the five-minute retry window bounds the retries, not each Start, and a spent window returns the runner's refusal so the run-level retry still requeues the run. - Run controller: a terminal parent waiting on children to settle is re-enqueued by a watch on child Runs reaching a terminal phase, not a 30s RequeueAfter; real failures keep the backoff. - Remove duplicate helpers: AddDelegatedUsage uses ensureTransaction, terminal-phase and execution-owner checks have one implementation, and the aborted invocation record uses RunTriggerAPI. Co-Authored-By: Claude Opus 5.5 <[email protected]> (cherry picked from commit 11062a4)
- PullRequest: spec.number adopts an existing forge PR only for a verified command. Adoption without one made a foreign branch's head this resource's to move, bypassing the existing-branch refusal and letting the next desired head force-push it. - Task status comments refuse a PR that has not been opened yet instead of posting to /issues/0/comments and surfacing GitHub's 404. - CI observation reports check runs, commit statuses and workflow runs with their own counts; only the combined totals decide the state. - README: state the task-grant trust boundary. The signing key derives from the tenant-held Connection Secret, which also holds the App private key; a forged grant borrows only an authorized caller's authority because every use re-runs the SubjectAccessReview. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Re the unanchored note about This branch also now carries |
The Agents CatalogEntry named Code in spec.requires so the code_pull_request
tool could call pullrequests/{name}/operate as the Agents provider. A
requirement naming a provider is also a dependency edge, so the hub refused
to enable Agents in any workspace without Code (the agentsprovider e2e 409).
The tool now calls Code as a hub-minted identity owned by the executing Run,
with get and operate on the one admitted PullRequest only. Where Code is not
enabled the hub refuses the mint and only the Code tool fails, saying why.
Agents drops the claim, the dependency and the permission-claim-policy entry.
Code accepts that identity for task operations alongside a foreign provider:
it recomputes the ServiceAccount name the hub gives the Run's identity, now
shared as identityclient.ServiceAccountName, from invocationRun and
invocationRunUID in the operation.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Add App-backed pull request observations and scoped publication for Factory. Grants bind repository, PR, branch, caller, invocation, and deadline. Code validates the expected head before applying snapshots or posting inline review findings. CI includes workflow-level conclusions.
The external GitHub comment webhook is a follow-up. This draft is the Code dependency for the Factory ad-hoc and Agents handoff changes.
Validation