Add owner-managed GitHub App connections behind the instance flag
Co-Authored-By: Codex GPT-6-Astra <noreply@openai.com>
43 files changed,
+4,286
−11
.rastrillo/budgets.txt+4 −4docs/superpowers/plans/2026-11-23-github-connect-copy.md+5 −2docs/superpowers/plans/CONTROLLER-REPORT-github-connect-app.md+290 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+31 −0docs/superpowers/specs/2026-11-22-equipo-github-connector-probe.md+153 −0go.mod+1 −1internal/equipo/app.go+12 −0internal/equipo/config.go+5 −0internal/equipo/copy.go+32 −0internal/equipo/github/budget_test.go+9 −0internal/equipo/github/callback.go+127 −0internal/equipo/github/check.go+185 −0internal/equipo/github/client.go+416 −0internal/equipo/github/client_test.go+132 −0internal/equipo/github/guards_test.go+291 −0internal/equipo/github/inventory_cache.go+61 −0internal/equipo/github/lifecycle_guards_test.go+387 −0internal/equipo/github/models.go+61 −0internal/equipo/github/seal.go+53 −0internal/equipo/github/seal_test.go+60 −0internal/equipo/github/store.go+244 −0internal/equipo/github/store_test.go+405 −0internal/equipo/github_config_test.go+16 −0internal/equipo/github_http.go+191 −0internal/equipo/github_store.go+20 −0internal/equipo/github_view.go+122 −0internal/equipo/github_view_test.go+84 −0internal/equipo/handlers.go+1 −0internal/equipo/migrations/0102_forge_connections.sql+12 −0internal/equipo/migrations/schema.sql+13 −0internal/equipo/models.go+2 −0internal/equipo/render.go+1 −1internal/equipo/settings_hub.go+4 −0internal/equipo/store.go+2 −0internal/equipo/templates/github.html+33 −0internal/equipotest/github_app_test.go+334 −0internal/equipotest/github_browser_test.go+117 −0internal/plan3test/plan3_release_test.go+2 −1internal/runner/forge/forgetest/github.go+262 −0internal/runner/thin/github_scan_test.go+41 −0internal/runner/thin/preview_security.go+11 −1internal/runnerproto/event_io.go+4 −1internal/runnerproto/github_redaction_test.go+50 −0
CI failed — run details
CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/github__connect-app: Type Size Avail | ext4 96G 85G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type Size Avail | ext4 96G 85G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: claude: fetched and verified in 2.0s
ci-box: codex: fetched and verified in 4.5s
ci-box: codex-code-mode-host: fetched and verified in 1.5s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.3s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 9.8s
ci-box: pi: installed and verified in 7.4s
ci-box: opencode: installed and verified in 2.2s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 9.0s
ci-box: clone deepened in 3.3s
ci-box: file times set from content: 2983 files, 193 directories
ci-box: ready in 17.8s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
ok amadan.net/oficina/equipo/internal/equipotest 0.142s
=== compile ===
go build ./...
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py compile
+ go build -tags testbuild ./...
5.3s
+ go list -export -test -tags testbuild -f ./...
5.1s
+ go list -export -test -tags browser,testbuild -f ./internal/equipo ./internal/equipotest ./internal/headless ./internal/idtest ./internal/plan3test ./internal/thintest
3.3s
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -version
staticcheck 2026.1 (v0.7.0)
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 -version
Go: go1.26.11
Scanner: govulncheck@v1.8.0
DB: https://vuln.go.dev
DB updated: 2026-11-11 02:51:11 +0000 UTC
go run github.com/zricethezav/gitleaks/v8@v8.30.1 version
version is set by build process
=== check ===
--- shard 0 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-work: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$' ./internal/headless
receipt: test step 1m17.593s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m15.437s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m15.44s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 61.69, cpu waiting 40.86%, memory waiting 0.00%, io waiting 0.47%
--- shard 1 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-review: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadless$/^4_review$|^TestHeadless$/^2b_access$|^TestHeadless$/^runner_crash$|^TestHeadless$/^2b_first_message$|^TestHeadless$/^4_checks_honest$|^TestHeadless$/^7_stream_resume$|^TestHeadless$/^2b_notebook$|^TestHeadless$/^2b_move_in$|^TestHeadless$/^2b_desk_failure$|^TestHeadless$/^cancel$' ./internal/headless
receipt: test step 1m17.374s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m15.454s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m15.45s amadan.net/oficina/equipo/internal/headless TestHeadless
machine: 32 CPUs, load 60.75, cpu waiting 41.06%, memory waiting 0.00%, io waiting 0.46%
--- shard 2 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-connections: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessConnections$|^TestHeadlessTokenPasteEndToEnd$|^TestHeadlessTokenConnection$' ./internal/headless
receipt: test step 1m18.123s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m16.154s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m6.81s amadan.net/oficina/equipo/internal/headless TestHeadlessConnections
receipt: slow test 5.24s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenPasteEndToEnd
receipt: slow test 4.1s amadan.net/oficina/equipo/internal/headless TestHeadlessTokenConnection
machine: 32 CPUs, load 60.75, cpu waiting 41.06%, memory waiting 0.00%, io waiting 0.46%
--- shard 3 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-mac: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestMacWorker$|^TestHeadlessAttachments$|^TestHeadlessPrewarm$|^TestHeadless$/^1_first_token$|^TestHeadless$/^6_quick_messages$|^TestHeadless$/^8_instance_restart$|^TestHeadless$/^3_runner_offline$' ./internal/headless
receipt: test step 1m14.957s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m12.741s amadan.net/oficina/equipo/internal/headless
receipt: slow test 36.4s amadan.net/oficina/equipo/internal/headless TestMacWorker
receipt: slow test 18.95s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 8.86s amadan.net/oficina/equipo/internal/headless TestHeadlessPrewarm
receipt: slow test 8.53s amadan.net/oficina/equipo/internal/headless TestHeadlessAttachments
machine: 32 CPUs, load 61.69, cpu waiting 40.69%, memory waiting 0.00%, io waiting 0.49%
--- shard 4 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-guards: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestHeadlessCopyRotation$|^TestHeadlessPolicyGuards$|^TestHeadlessRunnerKillLeavesNoCopies$|^TestHeadlessNewHouseRuleStartsFresh$|^TestHeadless$/^3_engineering$|^TestHeadless$/^3_step_cancel$|^TestHeadless$/^3_step_contained$|^TestHeadless$/^3_step_refused$|^TestHeadless$/^3_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless
receipt: test step 1m32.807s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m30.437s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m1.91s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 8.98s amadan.net/oficina/equipo/internal/headless TestHeadlessRunnerKillLeavesNoCopies
receipt: slow test 7.96s amadan.net/oficina/equipo/internal/headless TestHeadlessCopyRotation
receipt: slow test 6.92s amadan.net/oficina/equipo/internal/headless TestHeadlessPolicyGuards
receipt: slow test 4.66s amadan.net/oficina/equipo/internal/headless TestHeadlessNewHouseRuleStartsFresh
machine: 32 CPUs, load 58.95, cpu waiting 39.44%, memory waiting 0.00%, io waiting 0.36%
--- shard 5 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane headless-rest: ./internal/headless
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^TestHeadless$/^4c_rebase$|^TestHeadless$/^4b_ask$|^TestHeadless$/^4c_checks_card$|^TestHeadless$/^4_step_crash$|^TestHeadless$/^4_review$|^TestHeadless$/^2b_access$|^TestHeadless$/^runner_crash$|^TestHeadless$/^2b_first_message$|^TestHeadless$/^4_checks_honest$|^TestHeadless$/^7_stream_resume$|^TestHeadless$/^2b_notebook$|^TestHeadless$/^2b_move_in$|^TestHeadless$/^2b_desk_failure$|^TestHeadless$/^cancel$|^TestHeadlessConnections$|^TestHeadlessTokenPasteEndToEnd$|^TestHeadlessTokenConnection$|^TestMacWorker$|^TestHeadlessAttachments$|^TestHeadlessPrewarm$|^TestHeadless$/^1_first_token$|^TestHeadless$/^6_quick_messages$|^TestHeadless$/^8_instance_restart$|^TestHeadless$/^3_runner_offline$|^TestHeadlessCopyRotation$|^TestHeadlessPolicyGuards$|^TestHeadlessRunnerKillLeavesNoCopies$|^TestHeadlessNewHouseRuleStartsFresh$|^TestHeadless$/^3_engineering$|^TestHeadless$/^3_step_cancel$|^TestHeadless$/^3_step_contained$|^TestHeadless$/^3_step_refused$|^TestHeadless$/^3_empty_repo$|^TestHeadless$/^3_empty_engineering$|^TestHeadless$/^3_empty_merge$|^TestHeadless$/^3_empty_merge_rebuilt$|^TestHeadless$/^3_empty_fix_round$' ./internal/headless
receipt: test step 2m44.622s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 2m41.893s amadan.net/oficina/equipo/internal/headless
receipt: slow test 1m36.57s amadan.net/oficina/equipo/internal/headless TestHeadlessAssistant
receipt: slow test 18.32s amadan.net/oficina/equipo/internal/headless TestHeadless
receipt: slow test 8.7s amadan.net/oficina/equipo/internal/headless TestHeadlessResearchHandoff
receipt: slow test 6.52s amadan.net/oficina/equipo/internal/headless TestHeadlessTurnBatching
receipt: slow test 6.41s amadan.net/oficina/equipo/internal/headless TestHeadlessBatchAfterRefusedReply
machine: 32 CPUs, load 23.48, cpu waiting 12.82%, memory waiting 0.00%, io waiting 0.10%
--- shard 6 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane thintest: ./internal/thintest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test([^C]|C[^o]|Co[^n]|Con[^t])|^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)' ./internal/thintest
receipt: test step 2m4.951s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 2m3.108s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 8.15s amadan.net/oficina/equipo/internal/thintest TestContractTeamJobSettledStates
receipt: slow test 6.74s amadan.net/oficina/equipo/internal/thintest TestExplorePreviewsOff
receipt: slow test 3.71s amadan.net/oficina/equipo/internal/thintest TestContractPreviewHeldUntilPublishAnswer
receipt: slow test 3.68s amadan.net/oficina/equipo/internal/thintest TestContractTeamNudgePersonNeeds
receipt: slow test 2.47s amadan.net/oficina/equipo/internal/thintest TestResearchDoneFallsBack
machine: 32 CPUs, load 41.67, cpu waiting 24.56%, memory waiting 0.00%, io waiting 0.21%
--- shard 7 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane thintest-contract: ./internal/thintest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^Test([^C]|C[^o]|Co[^n]|Con[^t])|^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)' ./internal/thintest
rastrillo: budget test: go test failed
--- FAIL amadan.net/oficina/equipo/internal/thintest TestContractRetryAccountActions
=== RUN TestContractRetryAccountActions
retry_contract_test.go:296: sign in again
--- FAIL: TestContractRetryAccountActions (0.20s)
--- FAIL amadan.net/oficina/equipo/internal/thintest (package output)
FAIL
rastrillo-budget/v1 ran 1m28.134s
FAIL amadan.net/oficina/equipo/internal/thintest 88.380s
receipt: test step 1m30.54s against a 60s target (the gate's other steps are not in this figure)
receipt: 0 packages ran, 0 cached, 0 without tests, 1 failed
receipt: slow package 1m28.134s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 9.05s amadan.net/oficina/equipo/internal/thintest TestContractPreviewNotScheduled
receipt: slow test 5.06s amadan.net/oficina/equipo/internal/thintest TestContractPublishNotOffered
receipt: slow test 4.59s amadan.net/oficina/equipo/internal/thintest TestContractMacRecheckMergeAuthority
receipt: slow test 2.36s amadan.net/oficina/equipo/internal/thintest TestContractPreview
receipt: slow test 2.35s amadan.net/oficina/equipo/internal/thintest TestContractPublishNameTaken
exit status 1
+ go test -tags testbuild -timeout 15m -skip '^Test([^C]|C[^o]|Co[^n]|Con[^t])|^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)' -v -run '^TestContractRetryAccountActions$' -count=1 ./internal/thintest (retry, once)
##############################################################################
FLAKE ./internal/thintest:TestContractRetryAccountActions thintest-contract 8d53e9e7167da97850152d2830864a58dbc7a9e0 0.20s 58.95
##############################################################################
failed, then passed on its one retry: the step stays green and the flake is on record
machine: 32 CPUs, load 57.35, cpu waiting 39.44%, memory waiting 0.00%, io waiting 0.36%
--- shard 8 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-thin: ./internal/runner/thin
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./internal/runner/thin
budget note: internal/runner/thin took 4m46.138s, over the 45s its record on line 44 allows; reported only, timing fails on CI
receipt: test step 4m51.758s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 4m46.138s amadan.net/oficina/equipo/internal/runner/thin
receipt: slow test 36.98s amadan.net/oficina/equipo/internal/runner/thin TestModelsEngineeringProbesThenRunsTheStrongest
receipt: slow test 36.96s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeAnsweredByAnotherModel
receipt: slow test 36.79s amadan.net/oficina/equipo/internal/runner/thin TestModelsUnhealthyRetriedOnDemand
receipt: slow test 18.48s amadan.net/oficina/equipo/internal/runner/thin TestModelsProbeRunsInsideTheAdmission
receipt: slow test 7.05s amadan.net/oficina/equipo/internal/runner/thin TestOpenCodeStepsRealOpenCode
machine: 32 CPUs, load 3.64, cpu waiting 1.57%, memory waiting 0.00%, io waiting 0.00%
--- shard 9 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-bug: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestDirectBugWorkflow$|^TestEnrolKeepsTheRole$' ./internal/runner
receipt: test step 51.365s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 50.296s amadan.net/oficina/equipo/internal/runner
receipt: slow test 30.26s amadan.net/oficina/equipo/internal/runner TestDirectBugWorkflow
receipt: slow test 20.03s amadan.net/oficina/equipo/internal/runner TestEnrolKeepsTheRole
machine: 32 CPUs, load 55.26, cpu waiting 33.37%, memory waiting 0.00%, io waiting 0.74%
--- shard 10 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-plans: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestPlanWorkflowCandidateOrder$|^TestPlanWorkflowFeature$|^TestCoordinatorRecoveryCallRefusalKeepsServing$|^TestCoordinatorRefusalMatrix$' ./internal/runner
receipt: test step 1m2.512s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m1.285s amadan.net/oficina/equipo/internal/runner
receipt: slow test 51.24s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowCandidateOrder
receipt: slow test 46.78s amadan.net/oficina/equipo/internal/runner TestPlanWorkflowFeature
receipt: slow test 8.37s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryCallRefusalKeepsServing
receipt: slow test 1.65s amadan.net/oficina/equipo/internal/runner TestCoordinatorRefusalMatrix
machine: 32 CPUs, load 62.08, cpu waiting 39.47%, memory waiting 0.00%, io waiting 0.60%
--- shard 11 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
test lane runner-rest: ./internal/runner
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^TestDirectBugWorkflow$|^TestEnrolKeepsTheRole$|^TestPlanWorkflowCandidateOrder$|^TestPlanWorkflowFeature$|^TestCoordinatorRecoveryCallRefusalKeepsServing$|^TestCoordinatorRefusalMatrix$' ./internal/runner
receipt: test step 36.067s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 35.154s amadan.net/oficina/equipo/internal/runner
receipt: slow test 5.14s amadan.net/oficina/equipo/internal/runner TestDirectFaultIsolation
receipt: slow test 3.36s amadan.net/oficina/equipo/internal/runner TestClaimRefusalsBackOff
receipt: slow test 3.14s amadan.net/oficina/equipo/internal/runner TestCoordinatorRecoveryRefusedKeepsServing
receipt: slow test 2.59s amadan.net/oficina/equipo/internal/runner TestToolVerbUnderFakeHarness
receipt: slow test 1.62s amadan.net/oficina/equipo/internal/runner TestCoordinatorTransientRefusalKeepsServing
machine: 32 CPUs, load 38.19, cpu waiting 22.20%, memory waiting 0.00%, io waiting 0.94%
--- shard 12 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-a started 30s late; cpu waiting 39.5%, load 25.32
test lane equipotest-a: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test[A-D]|^TestQ' ./internal/equipotest
receipt: test step 1m7.999s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m6.15s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 27.2s amadan.net/oficina/equipo/internal/equipotest TestBootstrapNamesOwnersSetting
receipt: slow test 27.19s amadan.net/oficina/equipo/internal/equipotest TestAuthorityCoreIntegration
receipt: slow test 25.02s amadan.net/oficina/equipo/internal/equipotest TestAccountLabelMigration
receipt: slow test 22.51s amadan.net/oficina/equipo/internal/equipotest TestBudgetConfigurationFailuresAreAtomic
receipt: slow test 22.35s amadan.net/oficina/equipo/internal/equipotest TestAuthorityProjectOwnershipIsLocal
machine: 32 CPUs, load 54.28, cpu waiting 36.85%, memory waiting 0.00%, io waiting 0.32%
--- shard 13 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-e started 30s late; cpu waiting 39.5%, load 25.32
test lane equipotest-e: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^Test[E-P]' ./internal/equipotest
receipt: test step 1m47.438s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m45.821s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 19.66s amadan.net/oficina/equipo/internal/equipotest TestProjectsFailuresRollBack
receipt: slow test 19.64s amadan.net/oficina/equipo/internal/equipotest TestProjectsAccountRevisionAndValidation
receipt: slow test 19.63s amadan.net/oficina/equipo/internal/equipotest TestProjectWritesRequireCurrentOwner
receipt: slow test 19.58s amadan.net/oficina/equipo/internal/equipotest TestProjectRetryAndRevision
receipt: slow test 19.55s amadan.net/oficina/equipo/internal/equipotest TestProjectsSharedAndGrouped
machine: 32 CPUs, load 36.93, cpu waiting 20.26%, memory waiting 0.00%, io waiting 0.17%
--- shard 14 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-r started 30s late; cpu waiting 39.5%, load 25.32
test lane equipotest-r: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -run '^TestR' ./internal/equipotest
receipt: test step 1m14.267s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m9.247s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 15.47s amadan.net/oficina/equipo/internal/equipotest TestReleaseStampContract
receipt: slow test 13.16s amadan.net/oficina/equipo/internal/equipotest TestRosterChangesAffectExistingSession
receipt: slow test 10.01s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalWhileAssigned
receipt: slow test 9.85s amadan.net/oficina/equipo/internal/equipotest TestRosterRemovalRollsBack
receipt: slow test 7.01s amadan.net/oficina/equipo/internal/equipotest TestRosterBootstrapOnce
machine: 32 CPUs, load 52.58, cpu waiting 33.44%, memory waiting 0.00%, io waiting 0.29%
--- shard 15 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: equipotest-rest started 30s late; cpu waiting 39.8%, load 25.32
test lane equipotest-rest: ./internal/equipotest
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m -skip '^Test[A-D]|^TestQ|^Test[E-P]|^TestR' ./internal/equipotest
receipt: test step 1m8.219s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m6.551s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 25.52s amadan.net/oficina/equipo/internal/equipotest TestSigninNoProof
receipt: slow test 24.3s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedExistingTeam
receipt: slow test 24.28s amadan.net/oficina/equipo/internal/equipotest TestSpecialistsSeedRollback
receipt: slow test 22.58s amadan.net/oficina/equipo/internal/equipotest TestSpecialistSettingsRollbackAndUnavailable
receipt: slow test 22.5s amadan.net/oficina/equipo/internal/equipotest TestSpecialistSettingsCurrentOwner
machine: 32 CPUs, load 54.28, cpu waiting 36.85%, memory waiting 0.00%, io waiting 0.32%
--- shard 16 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: plan3test started 30s late; cpu waiting 39.5%, load 25.32
test lane plan3test: ./internal/plan3test
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./internal/plan3test
receipt: test step 53.68s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 51.756s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 3.53s amadan.net/oficina/equipo/internal/plan3test TestPlan3Upgrade
receipt: slow test 3.5s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3B
receipt: slow test 1.64s amadan.net/oficina/equipo/internal/plan3test TestConversationQuestionRace
receipt: slow test 1.54s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorAcceptance3A
receipt: slow test 1.25s amadan.net/oficina/equipo/internal/plan3test TestCoordinatorMessageSourcesUpgrade
machine: 32 CPUs, load 59.73, cpu waiting 40.31%, memory waiting 0.00%, io waiting 0.43%
--- shard 17 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: rest started 30s late; cpu waiting 39.8%, load 25.32
test lane rest: ./cmd/equipo ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/door ./internal/equipo/github ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/idtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/claude/realcli ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/forgekey ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags testbuild -timeout 15m ./cmd/equipo ./cmd/equipo-runner ./cmd/equipo-tool-proxy ./internal/advice ./internal/attach ./internal/attach/attachtest ./internal/chatmarkdown ./internal/chatsend ./internal/chatstream ./internal/coordinator ./internal/coordinatorcontract ./internal/coordinatormail ./internal/copydesk ./internal/equipo ./internal/equipo/activity ./internal/equipo/assist ./internal/equipo/chat ./internal/equipo/conversation ./internal/equipo/conversation/chatstate ./internal/equipo/door ./internal/equipo/github ./internal/equipo/housekeeping ./internal/equipo/icons ./internal/equipo/identity ./internal/equipo/kernel ./internal/equipo/library ./internal/equipo/mergegate ./internal/equipo/notifications ./internal/equipo/oficina ./internal/equipo/oficina/oficinatest ./internal/equipo/oficinaid ./internal/equipo/ownermode ./internal/equipo/personapi ./internal/equipo/planning ./internal/equipo/push ./internal/equipo/setup ./internal/equipo/team ./internal/equipo/teamcontract ./internal/equipo/triage ./internal/fakeclaude ./internal/fakecodex ./internal/fakeopencode ./internal/fakepi ./internal/idtest ./internal/ownermodetest ./internal/release ./internal/runner/checks ./internal/runner/connect ./internal/runner/containment ./internal/runner/containment/sysunix ./internal/runner/egress ./internal/runner/forge ./internal/runner/forge/forgetest ./internal/runner/heartbeat ./internal/runner/mac ./internal/runner/mcpresource ./internal/runner/metered ./internal/runner/planflow ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/claude/realcli ./internal/runner/provider/codex ./internal/runner/provider/gotoolchain ./internal/runner/provider/opencode ./internal/runner/provider/pi ./internal/runner/setup ./internal/runner/transporttest ./internal/runner/webread ./internal/runner/workspace ./internal/runnerproto ./internal/schedule ./internal/sealbox ./internal/specialist ./internal/stagingtest ./internal/taskplan ./internal/testci ./internal/toolproxy ./internal/websource ./internal/wire ./internal/wire/forgekey ./internal/wire/wireschema ./internal/wire/wiretest ./tools/drive
cache miss: amadan.net/oficina/equipo/internal/chatmarkdown: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/claude/realcli: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/testci: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/webread: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/copydesk: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/opencode: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/containment: its inputs changed
cache miss: amadan.net/oficina/equipo/internal/runner/provider/pi: its inputs changed
budget note: internal/equipo took 52.277s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/chat took 20.935s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/github took 27.504s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/equipo/setup took 11.957s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/idtest took 1m49.074s, over the 10s the default allows; reported only, timing fails on CI
budget note: internal/release took 36.558s, over the 10s the default allows (measured on the run this cached result came from); reported only, timing fails on CI
budget note: internal/runner/containment took 51.238s, over the 15s its record on line 40 allows; reported only, timing fails on CI
budget note: internal/runner/forge took 22.11s, over the 20s its record on line 35 allows; reported only, timing fails on CI
budget note: internal/runner/provider/claude/realcli took 15.115s, over the 10s the default allows; reported only, timing fails on CI
receipt: test step 2m31.859s against a 60s target (the gate's other steps are not in this figure)
receipt: 37 packages ran, 29 cached, 17 without tests, 0 failed
receipt: slow package 1m49.074s amadan.net/oficina/equipo/internal/idtest
receipt: slow package 1m9.6s amadan.net/oficina/equipo/internal/runner/provider/opencode
receipt: slow package 55.592s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 52.691s amadan.net/oficina/equipo/internal/runner/provider/pi
receipt: slow package 52.277s amadan.net/oficina/equipo/internal/equipo
receipt: slow test 54.13s amadan.net/oficina/equipo/internal/idtest TestDoorRemembersOficinaID
receipt: slow test 44.9s amadan.net/oficina/equipo/internal/idtest TestDoorStepUpIsLocal
receipt: slow test 44.69s amadan.net/oficina/equipo/internal/idtest TestDoorOficinaSettingsUnreadableIsNoLoop
receipt: slow test 44.47s amadan.net/oficina/equipo/internal/idtest TestDoorForgetsOficinaIDForARefusedSession
receipt: slow test 44.39s amadan.net/oficina/equipo/internal/idtest TestDoorNeverJudgesANativeSession
machine: 32 CPUs, load 18.72, cpu waiting 9.50%, memory waiting 0.00%, io waiting 0.07%
--- shard 18 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-chat: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$' ./internal/headless
receipt: test step 1m24.136s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m22.466s amadan.net/oficina/equipo/internal/headless
receipt: slow test 38.67s amadan.net/oficina/equipo/internal/headless TestBrowserDraftIsTheMessage
receipt: slow test 14.76s amadan.net/oficina/equipo/internal/headless TestBrowserDraftStreamsFormatted
receipt: slow test 10.08s amadan.net/oficina/equipo/internal/headless TestBrowserChat
receipt: slow test 7.13s amadan.net/oficina/equipo/internal/headless TestBrowserComposer
receipt: slow test 6.67s amadan.net/oficina/equipo/internal/headless TestBrowserChatSendStaysOnPage
machine: 32 CPUs, load 59.73, cpu waiting 40.00%, memory waiting 0.00%, io waiting 0.41%
--- shard 19 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-work: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$' ./internal/headless
receipt: test step 1m29.919s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m28.219s amadan.net/oficina/equipo/internal/headless
receipt: slow test 27.16s amadan.net/oficina/equipo/internal/headless TestBrowserRailFollowsWork
receipt: slow test 21.28s amadan.net/oficina/equipo/internal/headless TestBrowserTaskThread
receipt: slow test 12.69s amadan.net/oficina/equipo/internal/headless TestBrowserReceiptFollowsReview
receipt: slow test 9.71s amadan.net/oficina/equipo/internal/headless TestBrowserTaskCard
receipt: slow test 8.93s amadan.net/oficina/equipo/internal/headless TestBrowserAskAfterMerge
machine: 32 CPUs, load 58.95, cpu waiting 39.89%, memory waiting 0.00%, io waiting 0.37%
--- shard 20 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-connections: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' ./internal/headless
receipt: test step 1m41.751s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m39.862s amadan.net/oficina/equipo/internal/headless
receipt: slow test 13.39s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsConversation
receipt: slow test 13.23s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAddPage
receipt: slow test 12.18s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsAdd
receipt: slow test 11.19s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsMeteredLimitRequired
receipt: slow test 11.03s amadan.net/oficina/equipo/internal/headless TestBrowserConnectionsOpenCodeGoLimitRequired
machine: 32 CPUs, load 54.28, cpu waiting 34.54%, memory waiting 0.00%, io waiting 0.30%
--- shard 21 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-headless-rest: ./internal/headless
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAskAfterMerge|TestBrowserChat|TestBrowserChatSendStaysOnPage|TestBrowserComposer|TestBrowserComposerDock|TestBrowserComposerFocus|TestBrowserComposerReconcile|TestBrowserConnectionsAdd|TestBrowserConnectionsAddPage|TestBrowserConnectionsConversation|TestBrowserConnectionsCopyLink|TestBrowserConnectionsEndedNote|TestBrowserConnectionsMeteredLimitRequired|TestBrowserConnectionsOpenCodeGoLimitRequired|TestBrowserConnectionsSignIn|TestBrowserConnectionsSignInSwitch|TestBrowserConnectionsToken|TestBrowserCopyContinue|TestBrowserCopySettingAndFlag|TestBrowserDraftIsTheMessage|TestBrowserDraftStreamsFormatted|TestBrowserEmptyExplore|TestBrowserMoveIn|TestBrowserNotebook|TestBrowserNotebookLook|TestBrowserPasteBox|TestBrowserPasteBoxLook|TestBrowserPasteCopiesItsBox|TestBrowserRailFollowsWork|TestBrowserReceiptFollowsReview|TestBrowserReceiptsDesktop|TestBrowserReceiptsTouch|TestBrowserRefreshRace|TestBrowserStalePageReloads|TestBrowserTaskCard|TestBrowserTaskThread|TestBrowserThinkingAndCards|TestBrowserUsageAndAdvice|TestBrowserWaitingTurns|TestNotebookScreenshots)$' -skip '^TestBrowserChat$|^TestBrowserChatSendStaysOnPage$|^TestBrowserComposer$|^TestBrowserComposerReconcile$|^TestBrowserComposerFocus$|^TestBrowserComposerDock$|^TestBrowserDraftStreamsFormatted$|^TestBrowserDraftIsTheMessage$|^TestBrowserTaskCard$|^TestBrowserReceiptFollowsReview$|^TestBrowserRailFollowsWork$|^TestBrowserTaskThread$|^TestBrowserAskAfterMerge$|^TestBrowserReceiptsDesktop$|^TestBrowserReceiptsTouch$|^TestBrowserConnections|^TestBrowserPasteBox$|^TestBrowserPasteCopiesItsBox$' ./internal/headless
receipt: test step 1m31.331s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 1m29.302s amadan.net/oficina/equipo/internal/headless
receipt: slow test 14.82s amadan.net/oficina/equipo/internal/headless TestBrowserThinkingAndCards
receipt: slow test 11.91s amadan.net/oficina/equipo/internal/headless TestBrowserStalePageReloads
receipt: slow test 10.21s amadan.net/oficina/equipo/internal/headless TestBrowserWaitingTurns
receipt: slow test 9.22s amadan.net/oficina/equipo/internal/headless TestBrowserMoveIn
receipt: slow test 7.59s amadan.net/oficina/equipo/internal/headless TestBrowserEmptyExplore
machine: 32 CPUs, load 58.95, cpu waiting 39.44%, memory waiting 0.00%, io waiting 0.36%
--- shard 22 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
timing budgets: reported, not enforced: a shared runner's load is not this change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)
browser: /opt/chromium-156.0.8078.79-1_deb13u1/chrome: Chromium 156.0.8078.79
browser lane browser-rest: ./internal/equipo
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserPreviewBlocksNavigation)$' ./internal/equipo
receipt: test step 2.105s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 488ms amadan.net/oficina/equipo/internal/equipo
receipt: slow test 490ms amadan.net/oficina/equipo/internal/equipo TestBrowserPreviewBlocksNavigation
browser lane browser-rest: ./internal/equipotest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserGitHubManifestCSP)$' ./internal/equipotest
receipt: test step 7.827s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 6.242s amadan.net/oficina/equipo/internal/equipotest
receipt: slow test 6.24s amadan.net/oficina/equipo/internal/equipotest TestBrowserGitHubManifestCSP
browser lane browser-rest: ./internal/idtest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserOficinaIDDoor|TestBrowserSmartDoor)$' ./internal/idtest
budget note: internal/idtest took 10.755s, over the 10s the default allows; reported only, timing fails on CI
receipt: test step 12.267s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 10.755s amadan.net/oficina/equipo/internal/idtest
receipt: slow test 8.6s amadan.net/oficina/equipo/internal/idtest TestBrowserSmartDoor
receipt: slow test 2.15s amadan.net/oficina/equipo/internal/idtest TestBrowserOficinaIDDoor
browser lane browser-rest: ./internal/plan3test
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestTeamsHierarchyBrowser)$' ./internal/plan3test
receipt: test step 3.648s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 2.052s amadan.net/oficina/equipo/internal/plan3test
receipt: slow test 2.05s amadan.net/oficina/equipo/internal/plan3test TestTeamsHierarchyBrowser
browser lane browser-rest: ./internal/thintest
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -tags browser,testbuild -timeout 15m -run '^(TestBrowserAccessEmojiByline|TestBrowserAccessFinalOutcomes|TestBrowserAccessRequest|TestBrowserAccessReview|TestBrowserActivitySubjects|TestBrowserAutonomySettings|TestBrowserCoordinatorQueue|TestBrowserEmptyConversation|TestBrowserEndedNoteStaysGone|TestBrowserHousekeeping|TestBrowserInnerGallery|TestBrowserInnerScreens|TestBrowserInstantThinking|TestBrowserInstantThinkingQueued|TestBrowserMachines|TestBrowserPhoneIndex|TestBrowserPlacementQuestionAndPending|TestBrowserProjectPlacement|TestBrowserProjectsList|TestBrowserReportActionFeedback|TestBrowserReportNextSteps|TestBrowserReportThread|TestBrowserRhythm|TestBrowserRollup|TestBrowserRosterAlignment|TestBrowserRosterDecisionStates|TestBrowserRosterQuietDay|TestBrowserRosterReports|TestBrowserRosterSetAside|TestBrowserRosterSubchat|TestBrowserRosterThinking|TestBrowserRosterVisual|TestBrowserSettingsHousekeepingGroups|TestBrowserSettingsMenu|TestBrowserSettingsRail|TestBrowserSettingsSaveBar|TestBrowserSettingsShots|TestBrowserSettingsStayOnPage|TestBrowserSettingsTeams|TestBrowserShipsButtons|TestBrowserSpecialistRows|TestBrowserSpendFollowsAnswers|TestBrowserTaskRows|TestBrowserTeamPanel|TestBrowserThinkingCycles|TestBrowserThinkingLinesClear|TestBrowserThinkingSteady|TestBrowserThinkingWords|TestBrowserTokenRowEmail|TestBrowserTrackPulse|TestBrowserTrackStarCentre|TestBrowserTryAgain)$' ./internal/thintest
receipt: test step 3m28.596s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 3m26.919s amadan.net/oficina/equipo/internal/thintest
receipt: slow test 26.39s amadan.net/oficina/equipo/internal/thintest TestBrowserAccessRequest
receipt: slow test 14.38s amadan.net/oficina/equipo/internal/thintest TestBrowserSettingsTeams
receipt: slow test 11.98s amadan.net/oficina/equipo/internal/thintest TestBrowserThinkingCycles
receipt: slow test 10.58s amadan.net/oficina/equipo/internal/thintest TestBrowserPlacementQuestionAndPending
receipt: slow test 8.83s amadan.net/oficina/equipo/internal/thintest TestBrowserRhythm
machine: 32 CPUs, load 8.28, cpu waiting 3.86%, memory waiting 0.00%, io waiting 0.02%
--- shard 23 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
shard 23: make test-quarantine
python3 scripts/ci-test.py quarantine
quarantine: 12 tests from scripts/ci-quarantine.txt; a failure is retried once, and a pass on the retry is reported as a flake
+ go test -tags testbuild -timeout 15m -v -run '^TestHeadlessConnections$/^A5_cancel_and_sign_out$|^TestHeadlessConnections$/^C4_claude_sign_in$|^TestHeadlessConnections$/^C5_engineering_failover$|^TestHeadlessConnections$/^C5_engineering_to_codex$|^TestHeadlessConnections$/^C5_engineering_waits$' ./internal/headless (52s)
ok ./internal/headless TestHeadlessConnections/A5_cancel_and_sign_out 4.62s
ok ./internal/headless TestHeadlessConnections/C4_claude_sign_in 1.14s
ok ./internal/headless TestHeadlessConnections/C5_engineering_failover 8.19s
ok ./internal/headless TestHeadlessConnections/C5_engineering_to_codex 8.59s
ok ./internal/headless TestHeadlessConnections/C5_engineering_waits 26.86s
+ go test -tags testbuild -timeout 15m -v -run '^TestHeadlessConnections$/^C5_review_auth$|^TestHeadlessConnections$/^C5_review_failover$|^TestHeadlessConnections$/^C5_review_on_codex$|^TestHeadlessConnections$/^C5_review_other_family_first$' ./internal/headless (55s)
ok ./internal/headless TestHeadlessConnections/C5_review_auth 11.66s
ok ./internal/headless TestHeadlessConnections/C5_review_failover 11.28s
ok ./internal/headless TestHeadlessConnections/C5_review_on_codex 9.90s
ok ./internal/headless TestHeadlessConnections/C5_review_other_family_first 19.79s
+ go test -tags testbuild -timeout 15m -v -run '^TestMixedVersions$' ./internal/headless (21s)
ok ./internal/headless TestMixedVersions 18.21s
+ go test -tags testbuild -timeout 15m -v -run '^TestCheckSandboxDeniedPathsTampering$' ./internal/runner/checks (2s)
ok ./internal/runner/checks TestCheckSandboxDeniedPathsTampering 0.85s
+ go test -tags testbuild -timeout 15m -v -run '^TestRunnerCancelAndSupersede$' ./internal/runner/thin (2s)
ok ./internal/runner/thin TestRunnerCancelAndSupersede 0.05s
quarantine: 0 flaked (passed on the retry), 0 failed
machine: 32 CPUs, load 59.65, cpu waiting 37.35%, memory waiting 0.00%, io waiting 0.67%
--- shard 24 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
shard 24: make runner-host
python3 scripts/runner-prerequisites.py
CGO_ENABLED=0 RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py retried runner-host -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks
receipt: test step 13.021s against a 60s target (the gate's other steps are not in this figure)
receipt: 4 packages ran, 0 cached, 4 without tests, 0 failed
receipt: slow package 7.682s amadan.net/oficina/equipo/internal/runner/checks
receipt: slow package 214ms amadan.net/oficina/equipo/internal/runner/provider/claude
receipt: slow package 133ms amadan.net/oficina/equipo/internal/runner/provider/codex
receipt: slow package 1ms amadan.net/oficina/equipo/internal/runner/provider
receipt: slow package 0s amadan.net/oficina/equipo/internal/runner/provider/claude/realcli
receipt: slow test 5.4s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsGoFixture
receipt: slow test 1.83s amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPaths
receipt: slow test 340ms amadan.net/oficina/equipo/internal/runner/checks TestCheckSandboxDeniedPathsCache
receipt: slow test 210ms amadan.net/oficina/equipo/internal/runner/provider/claude TestDirectJournalAdapterBarrier
receipt: slow test 130ms amadan.net/oficina/equipo/internal/runner/provider/codex TestDirectJournalAdapterBarrier
CGO_ENABLED=0 RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py retried runner-host -run '^TestNamespace' -count=1 ./internal/runner/containment
+ go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -no-time -run '^TestNamespace' -count=1 ./internal/runner/containment
receipt: test step 3.479s against a 60s target (the gate's other steps are not in this figure)
receipt: 1 packages ran, 0 cached, 0 without tests, 0 failed
receipt: slow package 3.056s amadan.net/oficina/equipo/internal/runner/containment
receipt: slow test 280ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceReadOnlyScratch
receipt: slow test 210ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryUnavailableProof
receipt: slow test 130ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceDirectPolicyAdmission
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryReusedPID
receipt: slow test 110ms amadan.net/oficina/equipo/internal/runner/containment TestNamespaceRecoveryCleansScratch
machine: 32 CPUs, load 10.73, cpu waiting 10.36%, memory waiting 0.00%, io waiting 1.31%
--- shard 25 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: runner-dead-references started 30s late; cpu waiting 39.8%, load 25.32
shard 25: make runner-dead-references lanes-check build vet fmt-check spacing budget migration-check
python3 scripts/runner-dead-references.py
reference scan: 2696 text files, 3210 matches, 0 failures
python3 scripts/ci-test.py check
lanes: 18 lanes and 5 browser lanes run every test once; 20-check@29
CGO_ENABLED=0 go build ./...
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o /dev/null ./cmd/equipo-runner
go vet ./...
go vet -tags testbuild ./internal/runner/thin ./internal/headless
GOOS=darwin GOARCH=arm64 go vet ./cmd/equipo-runner/... ./internal/runner/... ./internal/wire/... ./internal/release/...
go tool fiesta spacing -skip tokens.css internal/equipo/static
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 92 directories within budget
CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
ok amadan.net/oficina/equipo/internal/equipo 2.520s
machine: 32 CPUs, load 60.75, cpu waiting 41.06%, memory waiting 0.00%, io waiting 0.46%
--- shard 26 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: staticcheck started 30s late; cpu waiting 39.8%, load 25.32
shard 26: make staticcheck
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 -tags browser,perf,testbuild ./...
internal/equipotest/github_browser_test.go:53:138: should use constant http.StatusSeeOther instead of numeric literal 303 (ST1013)
internal/equipotest/github_browser_test.go:57:155: should use constant http.StatusSeeOther instead of numeric literal 303 (ST1013)
exit status 1
make[1]: *** [Makefile:195: staticcheck] Error 1
machine: 32 CPUs, load 59.65, cpu waiting 36.11%, memory waiting 0.00%, io waiting 0.69%
make: *** [Makefile:113: ci-shard] Error 2
amadan: step check shard 26 of 29 failed: exit status 2
--- shard 27 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: govulncheck started 30s late; cpu waiting 39.8%, load 25.32
shard 27: make govulncheck
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
=== Symbol Results ===
No vulnerabilities found.
Your code is affected by 0 vulnerabilities.
This scan also found 0 vulnerabilities in packages you import and 3
vulnerabilities in modules you require, but your code doesn't appear to call
these vulnerabilities.
Use '-show verbose' for more details.
machine: 32 CPUs, load 43.38, cpu waiting 23.86%, memory waiting 0.00%, io waiting 0.91%
--- shard 28 of 29 ---
RASTRILLO='go run amadan.net/rastrillo/rastrillo/cmd/rastrillo' python3 scripts/ci-test.py shard
stagger: gitleaks started 30s late; cpu waiting 39.5%, load 25.32
shard 28: make gitleaks
[90m8:56PM[0m [32mINF[0m [1mUnknown SCM platform. Use --platform to include links in findings.[0m [36mhost=[0mamadan.net
[90m8:56PM[0m [32mINF[0m [1m1127 commits scanned.[0m
[90m8:56PM[0m [32mINF[0m [1mscanned ~65186782 bytes (65.19 MB) in 24.5s[0m
[90m8:56PM[0m [32mINF[0m [1mno leaks found[0m
machine: 32 CPUs, load 59.65, cpu waiting 36.11%, memory waiting 0.00%, io waiting 0.69%
amadan: job failed at step check shard 26 of 29 — its output is above, not at the tail of this log
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 41646f4b..eaeed9d3 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,9 +14,9 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| -size internal/equipo 22112 - One Luna-reviewed output format for the GitHub egress diagnostic; measured 22112 source lines. |
| +size internal/equipo 22503 - GitHub owner routes, lifecycle rendering and configuration glue; measured 22503 source lines; domain logic is in equipo/github. |
| size internal/wire 6830 - Successful-push proposal diagnostic in existing Reason fields; measured 6830 source lines. |
| -size internal/equipotest - 12017 Task 21 repairs historical migration and conversation fixtures after Plan 3, and the Rastrillo upgrade contract comparing served assets with what Assets serves; measured 0/12017 source/test lines. |
| +size internal/equipotest - 12468 GitHub manifest, callback, value-search and browser CSP contracts; measured 12468 test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s). |
| @@ -30,7 +30,7 @@ size internal/runner/provider 5715 - Fable follow-up: base and diagnostic gates, |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
| -size internal/plan3test - 11900 Add the controller-approved Luna egress diagnostic key to release inventory; measured 11900 test lines, source cap unchanged. |
| +size internal/plan3test - 11901 Bound the 31 Luna-reviewed GitHub App keys in release inventory; measured 11901 test lines. |
| time internal/runner/forge 20s Plan 3 CI repair measured 10.527s for the full package (controller CI 10.407s). |
| time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full package (controller CI 10.709s); |
| @@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -size internal/runner/thin 28446 22619 Forge review fixes, real fileForge router coverage, authority and proposal regressions; measured 28446 source and 22619 test lines. |
| +size internal/runner/thin 28456 22660 GitHub token and PEM secret-scan rules and killing regressions; measured 28456 source and 22660 test lines. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
diff --git a/docs/superpowers/plans/2026-11-23-github-connect-copy.md b/docs/superpowers/plans/2026-11-23-github-connect-copy.md| index e3fc1a61..06aeb3b2 100644 |
| --- a/docs/superpowers/plans/2026-11-23-github-connect-copy.md |
| +++ b/docs/superpowers/plans/2026-11-23-github-connect-copy.md |
| @@ -98,9 +98,9 @@ No cleanup link silently points to a replacement App. |
| | Conversion/verification fails for this valid attempt | `github.setup_failed`, `github.app_remains`, `github.app_settings`, `github.connect`. | |
| | Invalid, wrong-stage, replayed or wrong-session callback | `github.setup_failed`, `github.connect`. Reveal no other owner's setup, settings URL or secret; do not delete another valid attempt. | |
| | Session no longer belongs to a current owner | Existing owner-forbidden copy; no GitHub account details or actions. The transaction roster check denies the write. | |
| -| Pending setup superseded by any current owner | `github.app_remains`, `github.app_settings` for the discarded App, followed by the new Start/account form keys. | |
| +| The team's single pending setup superseded by any current owner, for any account | `github.app_remains`, `github.app_settings` for the discarded App, followed by the new Start/account form keys. | |
| | Connected | `github.connected`, `github.disconnect`, `github.disconnect_hint`. | |
| -| Already connected, duplicate start or Connect | `github.already_connected`, with verified login; the existing connected surface remains. | |
| +| Already connected, duplicate start or Connect | `github.already_connected`, with verified login; the existing connected surface remains and the team's pending setup is untouched. | |
| | Owner Disconnect | `github.not_connected`, `github.app_remains`, `github.app_settings`, `github.reconnect`. | |
| | Uninstalled, key retained for seven days from first observation | `github.not_connected`, `github.check_again`. Never the 24-hour pending hint or a second Connect confirmation. | |
| | Same-App/account reinstall verified within seven days | `github.connected`, `github.disconnect`, `github.disconnect_hint`; existing projects revive by IDs. | |
| @@ -108,6 +108,9 @@ No cleanup link silently points to a replacement App. |
| | Unreadable sealed key, typed reconnect | `github.reconnect_hint`, `github.reconnect`, `github.app_remains`, `github.app_settings`. | |
| | Retryable installation check/network/rate-limit failure | `github.check_failed`, `github.check_again` while a valid key is held; without one, the failed-setup case applies. | |
| | Verified suspension | `github.suspended`; an owner with a held key also gets `github.check_again`. | |
| +| Projects group down after Disconnect or uninstall (branch B) | `github.group`, `github.not_connected`. | |
| +| Projects group suspended (branch B) | `github.group`, `github.suspended`. | |
| +| Pending Connect with more than 1000 repositories | `github.too_many`, `github.choose_repositories`, `github.check_again`. No `github.confirm` or count; recheck enables Connect only after a complete count within the limit. | |
| | Projects account group, complete current inventory | `github.group`; existing project controls and Available to add copy are reused. | |
| | Inventory stale or unknown after network or rate-limit failure | `github.group`, `github.stale`; no fake zero count or lost-access message. | |
| | Installation above 1000 repositories, snapshot unknown | `github.group`, `github.too_many`, `github.choose_repositories`; include `github.stale` if displaying an older snapshot. Never a partial current list. | |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-github-connect-app.md b/docs/superpowers/plans/CONTROLLER-REPORT-github-connect-app.md| new file mode 100644 |
| index 00000000..045ee0c3 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-github-connect-app.md |
| @@ -0,0 +1,290 @@ |
| +# GitHub App connection: implementation evidence |
| + |
| +Branch `github/connect-app`, based on main `eff421c7`. |
| +The controller approved the step-4 plan and assigned branch A on 2026-11-23. |
| +Implementation and local verification are complete. Linux CI is the final |
| +runner gate; its fixed commit and verdict are reported with the branch handoff. |
| + |
| +## Scope and order |
| + |
| +1. Token/key shape redaction and generated-key fake GitHub HTTP contract. |
| +2. Primary-database forge connection lifecycle, sealed App key, additive schema, |
| + owner checks, single-use callbacks and same-transaction audit records. |
| +3. Owner-only Settings section and manifest CSP, disabled by default. |
| +4. Lifetime, concurrency, value-search, browser and copy-rendering regressions. |
| +5. Individual guard mutations, local gates, commit, reference scan, push, CI. |
| + |
| +The controller's final implementation rulings supersede the plan where needed: |
| +only one pending setup per team; Start replaces it regardless of account, |
| +except an already-connected account leaves it untouched. Any current owner |
| +may Check again, Connect, supersede or Disconnect. More than 1000 repositories |
| +means an unknown snapshot with no Connect action until Check again obtains a |
| +complete count within the limit. Branch B renders down Projects groups with |
| +`github.group` plus `github.not_connected` or `github.suspended` and tests them. |
| + |
| +## Test-first evidence |
| + |
| +- `GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0 go test ./internal/runnerproto -run TestGitHubSecretShapes -count=1` |
| + failed first for all four GitHub token prefixes and all full/truncated PEM |
| + forms, then passed after shape redaction was implemented. The test supplies |
| + no known-secret list and checks nested JSON as well as plain text. |
| + |
| +## Mutation evidence |
| + |
| +Each mutation below was applied separately, the named test failed at runtime, |
| +and the source was restored. The final restored test passed. |
| + |
| +| Guard removed | Killing test | |
| +| --- | --- | |
| +| ghs_ recognition | TestGitHubSecretShapes/ghs_ | |
| +| ghu_ recognition | TestGitHubSecretShapes/ghu_ | |
| +| gho_ recognition | TestGitHubSecretShapes/gho_ | |
| +| ghr_ recognition | TestGitHubSecretShapes/ghr_ | |
| +| PEM block redaction | TestGitHubSecretShapes, full and truncated key cases | |
| + |
| +## Copy |
| + |
| +Use only the 39 keys and exact Luna-reviewed values in |
| +[the copy brief](2026-11-23-github-connect-copy.md). Runtime inventory and |
| +release acceptance list only keys actually introduced by this branch. |
| + |
| +## App API contract, first pass |
| + |
| +`GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0 go test ./internal/equipo/github -count=1` |
| +first failed at runtime against the API stubs, then passed (2.292s). Tests |
| +cover conversion with generated RSA keys, signed App JWTs, installation reads, |
| +selected/all modes, metadata-only token requests and memory reuse/revocation, |
| +redirect refusal, status classification including 403 rate limits, bounded |
| +responses and complete inventories of 0, 100, 101, 1000 and 1001 repositories. |
| +The later guards and HTTP value-search tests below complete the malformed-scope, |
| +concurrency and sink coverage. |
| + |
| +## Key sealing evidence |
| + |
| +`go test ./internal/equipo/github -run TestAppKeySealing -count=1` failed |
| +against the stub, then passed. Six separate mutations were killed: omit the |
| +origin binding, omit connection binding, omit App ID binding, use a fixed |
| +instance key, reuse the device-result purpose, and clear the random nonce. |
| +The restored test passed. The test also refuses corrupt ciphertext and checks |
| +that encoding alone cannot hide the plaintext. |
| + |
| +## Lifecycle and API mutation run |
| + |
| +Each command uses the pinned toolchain: `go test ./internal/equipo/github -run <test> -count=1`. |
| + |
| +| Guard mutation | Killing test | Result | |
| +| --- | --- | --- | |
| +| owner in write | `TestForgeRosterAndAuditGuards` | killed | |
| +| flag | `TestForgeFlagAndOwner` | SURVIVED | |
| +| audit save | `TestForgeRosterAndAuditGuards` | killed | |
| +| supersede key erasure | `TestForgeStartSinglePending` | killed | |
| +| already connected preserves pending | `TestForgeAlreadyConnectedPreservesPending` | killed | |
| +| disconnect erasure | `TestForgeConnectionLifecycle` | killed | |
| +| callback owner | `TestForgeCallbacksBound` | SURVIVED | |
| +| callback session | `TestForgeCallbacksBound` | killed | |
| +| callback origin | `TestForgeCallbacksBound` | killed | |
| +| callback expiry | `TestForgeCallbacksBound` | killed | |
| +| manifest single use | `TestForgeCallbacksBound\|TestForgeClaimAcrossProcesses` | killed | |
| +| installation single use | `TestForgeInstallationCallback` | killed | |
| +| late conversion generation | `TestForgeLateResults/convert/disconnect` | SURVIVED | |
| +| pending lifetime | `TestForgePendingAndUninstallDeadlines` | killed | |
| +| uninstall lifetime | `TestForgePendingAndUninstallDeadlines` | killed | |
| +| uninstall first seen | `TestForgePendingAndUninstallDeadlines` | killed | |
| +| reinstall no new Connect | `TestForgePendingAndUninstallDeadlines` | killed | |
| +| late check generation | `TestForgeLateResults/check/disconnect` | killed | |
| +| suspension | `TestForgeRecheckSuspensionAndRateLimit` | killed | |
| +| unknown count Connect | `TestForgeConnectUnknownCount` | killed | |
| +| unreadable key reconnect | `TestForgeUnreadableKey` | killed | |
| +| API app identity | `TestAppResponseGuards/app_id` | killed | |
| +| API owner identity | `TestAppResponseGuards/account_id` | killed | |
| +| API owner type | `TestAppResponseGuards/account_type` | killed | |
| +| API exact permissions | `TestAppResponseGuards/permissions` | killed | |
| +| API no webhook events | `TestAppResponseGuards/events` | killed | |
| +| API installation App | `TestAppResponseGuards/installation_app` | killed | |
| +| API installation account | `TestAppResponseGuards/installation_account` | killed | |
| +| API installation permissions | `TestAppResponseGuards/installation_permissions` | killed | |
| +| API token exact permissions | `TestAppResponseGuards/token_permissions\|TestAppResponseGuards/token_missing_permissions` | killed | |
| +| API token expiry | `TestAppResponseGuards/token_expired` | killed | |
| +| API token one hour | `TestAppResponseGuards/token_long_expiry` | killed | |
| +| API metadata-only request | `TestAppAPIContract` | killed | |
| +| API inventory bound | `TestAppInventoryBound/1001` | killed | |
| +| API inventory completeness | `TestAppResponseGuards/partial_inventory` | killed | |
| +| API duplicate repository | `TestAppResponseGuards/duplicate_repository` | killed | |
| +| API repository owner | `TestAppResponseGuards/repository_account` | killed | |
| + |
| +## Branch A copy inventory |
| + |
| +31 runtime keys use the exact reviewed values and Luna 2026-11-23 markers. |
| +`copy-status.py pending` ran first; acceptance was recorded from the controller's verdict, without invoking `accept`. The bounded `acceptedGitHubApp` list |
| +contains exactly these keys; the remaining eight belong to B, C and native. |
| + |
| +`github.title`, `github.connect`, `github.account`, `github.account_type`, `github.organization`, `github.personal_account`, `github.create_app`, `github.create_hint`, `github.confirm_account`, `github.repository_count`, `github.confirm`, `github.connected`, `github.already_connected`, `github.disconnect`, `github.disconnect_hint`, `github.pending`, `github.pending_hint`, `github.pending_approval`, `github.check_again`, `github.redirect_expired`, `github.pending_expired`, `github.setup_failed`, `github.app_remains`, `github.app_settings`, `github.reconnect`, `github.reconnect_hint`, `github.check_failed`, `github.not_connected`, `github.suspended`, `github.too_many`, `github.choose_repositories`. |
| +| API redirect refusal | `TestAppRedirectAndDeadline` | INVALID | |
| +| API 403 rate limit | `TestAppAPIRefusals/rate403\|TestAppAPIRefusals/secondary403` | killed | |
| +| API token cache lifetime | `TestAppTokenLifetime` | killed | |
| +| API token invalidation | `TestInventoryConditionalScope` | killed | |
| + |
| +## Strengthened and surface mutation run |
| + |
| +The initial survivors above motivated independent fixtures. A looping redirect |
| +mutant was terminated; its fixture now follows at most one redirect before a |
| +finite response. These reruns must fail at runtime, not compilation. |
| + |
| +| Guard mutation | Package / killing test | Result | |
| +| --- | --- | --- | |
| +| outer flag, strengthened | `./internal/equipo/github -run TestForgeFlagBeforeTransaction` | killed | |
| +| callback owner, strengthened | `./internal/equipo/github -run TestForgeOwnerBindingIndependentOfSession` | killed | |
| +| conversion generation, strengthened | `./internal/equipo/github -run TestForgeConversionGeneration` | killed | |
| +| verify conversion with JWT | `./internal/equipo/github -run TestForgeConversionVerification` | killed | |
| +| redirect, finite follow-up response | `./internal/equipo/github -run TestAppRedirectAndDeadline` | killed | |
| +| explicit empty events | `./internal/equipo/github -run TestAppResponseGuards/missing_events` | killed | |
| +| unknown inventory rows | `./internal/equipo/github -run TestAppResponseGuards/missing_rows` | killed | |
| +| idle metadata eviction | `./internal/equipo/github -run TestMetadataMemoryDeadline` | INVALID | |
| +| ETag generation | `./internal/equipo/github -run TestInventoryConditionalScope` | killed | |
| +| active account uniqueness | `./internal/equipo/github -run TestForgeUniqueAppAndNewNames` | killed | |
| +| App name randomness | `./internal/equipo/github -run TestForgeUniqueAppAndNewNames` | killed | |
| +| manifest private | `./internal/equipotest -run TestGitHubHTTPFlowAndValues` | killed | |
| +| manifest permissions | `./internal/equipotest -run TestGitHubHTTPFlowAndValues` | killed | |
| +| manifest expiry copy | `./internal/equipo -run TestGitHubStateCopy/manifest_expired` | killed | |
| +| installation expiry copy | `./internal/equipo -run TestGitHubStateCopy/installation_expired` | killed | |
| +| unmapped lifecycle copy | `./internal/equipo -run TestGitHubStateCopy/live` | killed | |
| +| manifest CSP browser | `./internal/equipotest -run TestBrowserGitHubManifestCSP` | killed | |
| +| CSP exception isolation | `./internal/equipotest -run TestGitHubHTTPFlowAndValues` | killed | |
| +| scanner ghs_ | `./internal/runner/thin -run TestGitHubSecretScan/ghs_` | killed | |
| +| scanner ghu_ | `./internal/runner/thin -run TestGitHubSecretScan/ghu_` | killed | |
| +| scanner gho_ | `./internal/runner/thin -run TestGitHubSecretScan/gho_` | killed | |
| +| scanner ghr_ | `./internal/runner/thin -run TestGitHubSecretScan/ghr_` | killed | |
| +| scanner PEM | `./internal/runner/thin -run TestGitHubSecretScan/PEM` | killed | |
| + |
| +## Final focused mutations |
| + |
| +| Guard | Killing test | Result | |
| +| --- | --- | --- | |
| +| idle metadata eviction corrected | `TestMetadataMemoryDeadline` | killed | |
| +| primary reads | `TestForgeReadsUsePrimary` | killed | |
| +| intended account login | `TestForgeAccountAndStageBinding/login` | killed | |
| +| intended account type | `TestForgeAccountAndStageBinding/type` | killed | |
| +| bounded read | `TestAppBodyBound` | killed | |
| +| oversized valid JSON | `TestAppBodyBound` | killed | |
| +| Disconnect while a pending/down key is held | `TestGitHubDisconnectHeldKey` | killed | |
| +| Custom default RoundTripper | `TestAppCustomDefaultTransport` | killed | |
| +| callback session epoch | `TestGitHubCallbackSessionRevokedDuringConversion` | killed | |
| +| check session epoch | `TestGitHubInventorySessionRevoked/check` | killed | |
| +| Connect session epoch | `TestGitHubInventorySessionRevoked/confirm` | killed | |
| +| App identity survives slug rename | `TestForgeSameAppRename` | killed | |
| +| verified renamed cleanup link | `TestForgeSameAppRename` | killed | |
| + |
| +## Final implementation |
| + |
| +- `internal/equipo/github` owns the GitHub API contract, primary-database |
| + lifecycle and memory-only metadata credentials. It has no runner dependency. |
| +- `internal/equipo` supplies current-owner/session checks, transactional audit, |
| + configuration, Settings rendering, callback handlers and background expiry. |
| + `EQUIPO_GITHUB=1` is required; the default is off. |
| +- Additive migration 0102 and the schema snapshot add `forge_connections` and |
| + `forge_pending`. Existing migrations, project rows and device wire stay unchanged. |
| +- `forgetest` supplies generated RSA keys, signed-JWT verification, single-use |
| + conversion, installation identity/permission replies, conditional inventory |
| + pages, metadata-only minting and revocation. No real credentials were read. |
| +- `runnerproto` redacts the four GitHub token shapes and full/truncated PEM; |
| + the runner's production gitleaks configuration scans the same shapes. |
| + The new test imports the already-pinned Viper dependency directly, with no |
| + dependency-version change. |
| + |
| +Owner browser routes are `GET /conversation/settings/github`, POST |
| +`/github/connect/start`, `/github/connect/check`, `/github/connect/confirm`, |
| +`/github/connect/disconnect`, and the two GET callbacks |
| +`/github/connect/manifest` and `/github/connect/installation`. Browser forms |
| +retain CSRF protection. The callbacks authenticate independently so every |
| +outcome can redirect to a clean URL without echoing a code or state. |
| +Only the manifest page expands `form-action` to GitHub; a real Chromium |
| +contract exercises its POST and redirects and proves ordinary pages still |
| +block an external form. |
| + |
| +The original owner's session, origin, account, attempt and stage bind each |
| +single-use redirect. Both use the original absolute ten-minute deadline. |
| +After creation, any current owner can act: pending keys last 24 hours; |
| +uninstalled keys last seven days from the first observed uninstall. Same-App |
| +reinstall preserves the existing Connect decision only for the same numeric |
| +account identity. A verified slug rename updates the cleanup URL without |
| +changing App identity. Unknown and over-limit inventory counts cannot Connect. |
| + |
| +Every lifecycle write checks the current roster and appends audit in its own |
| +transaction. The integration also carries the verified session epoch through |
| +GitHub calls: revoking a browser session during conversion, Check or Connect |
| +prevents the late result from committing. State claims, refresh claims and |
| +reads use the primary; generation fences stop stale responses after a new |
| +Start, Disconnect or another completed action. All API errors have safe types; |
| +upstream bodies never become user-facing text. |
| + |
| +The instance decrypts the App key only for an active API operation. An |
| +in-flight handler can retain its local plaintext until its bounded request |
| +returns; post-response roster, session and generation checks prevent it from |
| +restoring erased authority. The database keeps only authenticated ciphertext, |
| +bound to the purpose, instance origin, connection and numeric App ID. |
| +Disposable client/webhook secrets are discarded. Metadata tokens are held |
| +only in instance memory, revoked/dropped on invalidation and evicted shortly |
| +before expiry; they cannot read contents. ETags are scoped to that token and |
| +connection generation and discarded on a token change. No credential reaches |
| +a runner in A. The spec's compromised-runner read-token residual belongs to C. |
| + |
| +`TestGitHubHTTPFlowAndValues` searches the actual response/log and persisted |
| +report, frame, prompt and audit surfaces for generated key/token/client secret, |
| +webhook secret, code and state values. Initial manifest state and the verified |
| +installation redirect are the necessary browser exchange, explicitly excluded |
| +from the post-exchange clean-response assertion. The sanitized live inventory |
| +report is included verbatim beside the spec; it confirms the fake's per-token |
| +ETags, missing `repositories` field, all-false item permissions and 401 after |
| +revocation. |
| + |
| +A adds no device routes, protocol fields or runner content-reading authority; |
| +there is therefore no OpenAPI wire delta. B will render the recorded down-group |
| +rows and add project/reachability behavior. The native fixtures still pass. |
| +All existing test names/assertions are preserved except the bounded release |
| +copy-key acceptance list. No additional copy review is needed. |
| + |
| +## Verification and mutation total |
| + |
| +83 separate mutations were killed by runtime assertions: the 72 `killed` |
| +rows above, five initial redaction mutations and six key-sealing mutations. |
| +Three initial survivors are retained in the evidence table and have explicit |
| +strengthened killing reruns. Two invalid attempts are retained and excluded |
| +from the count; corrected versions failed at runtime. Every source was restored. |
| +The final same-App rename regression also failed with the old slug-identity |
| +comparison before the correction. |
| + |
| +Pinned environment for all checks: `GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0`, pinned |
| +GOROOT/bin first on PATH and physical TMPDIR (macOS /var is a symlink). |
| + |
| +Passed locally: |
| + |
| +- `make fmt-check budget migration-check copy-release-check lanes-check`. |
| + Size exceptions were raised only to measured values with feature reasons: |
| + equipo 22503 source, equipotest 12468 test, plan3test 11901 test, |
| + runner/thin 28456 source and 22660 test lines. |
| +- `python3 native/scripts/check-fixtures.py`: 11 device fixtures, 3586 markdown |
| + fixtures and 32000 differential cases. |
| +- Full equipo, chat, thintest and runner/forge suites, and all new github tests. |
| + Full equipotest passes with only the two acknowledged release/Python cases |
| + excluded; all new GitHub HTTP tests were rerun after the session-epoch fix. |
| +- `go test ./internal/plan3test -run TestPersonAPI -count=1`. |
| +- The real browser `TestBrowserGitHubManifestCSP`, restored after mutation. |
| +- Targeted vet and pinned staticcheck v0.7.0 on the touched server/fake/redactor |
| + packages (the whole tree's toolproxy package is Linux-only). |
| + |
| +The requested unfiltered run was also made: |
| +`go test ./internal/equipo/... ./internal/equipotest ./internal/thintest ./internal/runner/... -count=1 -timeout=12m`. |
| +It exposed two branch defects, both fixed and rerun: the schema snapshot needed |
| +both new tables, and the client constructor must accept a custom default |
| +RoundTripper. Remaining Mac failures are Linux sandbox/provider checks and |
| +the release tests `TestRunnerReleaseContractPackaging` and |
| +`TestReleasePinsAndProvenance`, whose fixed /usr/bin Python lacks |
| +`hashlib.file_digest`. The runner/thin suite reaches its 12-minute timeout in |
| +sandbox-dependent sign-in tests. An additional full runnerproto attempt fails |
| +`TestCheckPolicyNoRedundantRunner`, whose fixture requires /usr/bin/bwrap, |
| +absent on this Mac; the remainder and new redaction tests are checked separately. |
| +Linux CI, not a skipped local test, decides the final runner verdict. |
| + |
| +Post-commit requirements are run against the committed branch: gitleaks, |
| +`python3 scripts/runner-dead-references.py`, helper push, then Linux CI. |
| +The final handoff records their result and SHA without rewriting this commit. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index bc02f046..5bbfb6b9 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -6845,6 +6845,37 @@ records remain unchanged. |
| | `work.reason.tools_refused` | Equipo refused the commands it needed to run | Task page: fills "Engineering stopped: %s" when an Engineering step committed nothing after Equipo refused tool requests it made (stop reasons, 2026-11-23) | Runtime; COPY APPROVED (Paul, 2026-11-23, copy-review eavqvil43jg2zs3wxx3kxp3bpm, unchanged) | |
| | `work.reason.proposal_failed` | the branch was pushed, but the review request could not be created | Successful push diagnostic (GitHub seam, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| | `CopyGitHubEgress` | GitHub reachable: %t; status: %d; latency: %s; TLS peer: %s<br> | GitHub egress check (2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.title` | GitHub | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.connect` | Connect GitHub | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.account` | GitHub account | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.account_type` | Account type | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.organization` | Organization | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.personal_account` | Personal account | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.create_app` | Create a GitHub App | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.create_hint` | GitHub will ask you to create a GitHub App and choose the repositories Equipo can access. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.confirm_account` | Connect %s | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.repository_count` | Repositories: %d | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.confirm` | Connect | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.connected` | GitHub is connected | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.already_connected` | GitHub is already connected for %s. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.disconnect` | Disconnect | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.disconnect_hint` | Disconnecting stops Equipo from reading these GitHub repositories. These projects stay listed. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.pending` | The GitHub App is not connected yet. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.pending_hint` | You can check again for up to 24 hours after creating the GitHub App. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.pending_approval` | If approval is needed, ask a GitHub organization owner to approve it. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.check_again` | Check again | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.redirect_expired` | This GitHub setup link has expired. If you created the GitHub App, select Check again. Otherwise, start again. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.pending_expired` | The 24-hour setup window has ended. Connect GitHub again to create a new GitHub App. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.setup_failed` | GitHub setup could not be completed. Start again to create a new GitHub App. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.app_remains` | The GitHub App still exists on GitHub. You can delete it in GitHub App settings. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.app_settings` | Open GitHub App settings | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.reconnect` | Connect GitHub again | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.reconnect_hint` | Equipo can no longer use this GitHub App. Connect GitHub again to create a new one. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.check_failed` | Equipo could not check GitHub right now. Try again later. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.not_connected` | GitHub is not connected | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.suspended` | GitHub access is suspended | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.too_many` | Equipo can list up to %s repositories from this GitHub account. Choose fewer repositories on GitHub. | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| +| `github.choose_repositories` | Choose repositories on GitHub | (GitHub App connection, 2026-11-23; Luna, house rules) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) | |
| ## Task 21 |
diff --git a/docs/superpowers/specs/2026-11-22-equipo-github-connector-probe.md b/docs/superpowers/specs/2026-11-22-equipo-github-connector-probe.md| index 39e35d7b..16152a89 100644 |
| --- a/docs/superpowers/specs/2026-11-22-equipo-github-connector-probe.md |
| +++ b/docs/superpowers/specs/2026-11-22-equipo-github-connector-probe.md |
| @@ -238,3 +238,156 @@ permission, remains open. The complete merge table remains open as recorded |
| above. The organisation manifest flow, Actions on an App push and CARLOS |
| egress are confirmed, with the CARLOS method and production confirmation |
| remaining explicitly distinguished above. |
| + |
| +## Branch A inventory-token gate, 2026-11-23 20:15 UTC |
| + |
| +The controller ran `agent-tools/github-probe/probe_inventory.py` against the |
| +probe GitHub App installed on `oficina-equipo-test`. It minted two tokens with |
| +exactly metadata read, listed repositories, compared conditional requests with |
| +the same token and a fresh token, attempted a contents read, and revoked both. |
| +The script uses the controller's credentials outside the repository. Branch A |
| +uses generated keys only. No token, key or ETag value is copied here; ETags in |
| +this saved report are eight-character SHA-256 prefixes. |
| + |
| +The token response may omit `repositories`, as it did for this all-repositories |
| +installation. Item permission booleans are all false and do not establish reach. |
| +A token change invalidates cached ETags. The metadata-only token remains in |
| +instance memory until 30 seconds before its one-hour expiry or invalidation. |
| + |
| +Verbatim sanitized report `probe-inventory-20261123T201513Z.txt`: |
| + |
| +```json |
| +{ |
| + "calls": [ |
| + { |
| + "call": "POST /app/installations/{id}/access_tokens {permissions:{metadata:read}} (token A)", |
| + "status": 201, |
| + "permissions": { |
| + "metadata": "read" |
| + }, |
| + "repository_selection": "all", |
| + "repositories_field_present": false, |
| + "lifetime_s": 3600, |
| + "token_prefix": "ghs_" |
| + }, |
| + { |
| + "call": "GET /installation/repositories?per_page=100 (token A, first)", |
| + "status": 200, |
| + "if_none_match_sent": false, |
| + "etag_hash": "20ff57d5", |
| + "etag_weak": false, |
| + "vary": "Accept, Authorization, Cookie, X-GitHub-OTP,Accept-Encoding, Accept, X-Requested-With", |
| + "cache_control": "private, max-age=60, s-maxage=60", |
| + "x_ratelimit_used_present": true, |
| + "total_count": 2, |
| + "repositories": [ |
| + "probe", |
| + "probe-other" |
| + ], |
| + "repo_ids_present": true, |
| + "permissions_in_items": [ |
| + "{\"admin\": false, \"maintain\": false, \"push\": false, \"triage\": false, \"pull\": false}" |
| + ] |
| + }, |
| + { |
| + "call": "GET /installation/repositories?per_page=100 (token A, If-None-Match from token A)", |
| + "status": 304, |
| + "if_none_match_sent": true, |
| + "etag_hash": "20ff57d5", |
| + "etag_weak": false, |
| + "vary": "Accept, Authorization, Cookie, X-GitHub-OTP,Accept-Encoding, Accept, X-Requested-With", |
| + "cache_control": "private, max-age=60, s-maxage=60", |
| + "x_ratelimit_used_present": true, |
| + "total_count": null, |
| + "repositories": null, |
| + "repo_ids_present": null, |
| + "permissions_in_items": null |
| + }, |
| + { |
| + "call": "POST /app/installations/{id}/access_tokens {permissions:{metadata:read}} (token B, fresh)", |
| + "status": 201, |
| + "permissions": { |
| + "metadata": "read" |
| + }, |
| + "repository_selection": "all", |
| + "repositories_field_present": false, |
| + "lifetime_s": 3600, |
| + "token_prefix": "ghs_" |
| + }, |
| + { |
| + "call": "GET /installation/repositories?per_page=100 (token B, If-None-Match from token A)", |
| + "status": 200, |
| + "if_none_match_sent": true, |
| + "etag_hash": "ce4399ed", |
| + "etag_weak": false, |
| + "vary": "Accept, Authorization, Cookie, X-GitHub-OTP,Accept-Encoding, Accept, X-Requested-With", |
| + "cache_control": "private, max-age=60, s-maxage=60", |
| + "x_ratelimit_used_present": true, |
| + "total_count": 2, |
| + "repositories": [ |
| + "probe", |
| + "probe-other" |
| + ], |
| + "repo_ids_present": true, |
| + "permissions_in_items": [ |
| + "{\"admin\": false, \"maintain\": false, \"push\": false, \"triage\": false, \"pull\": false}" |
| + ] |
| + }, |
| + { |
| + "call": "GET /installation/repositories?per_page=100 (token B, unconditional)", |
| + "status": 200, |
| + "if_none_match_sent": false, |
| + "etag_hash": "ce4399ed", |
| + "etag_weak": false, |
| + "vary": "Accept, Authorization, Cookie, X-GitHub-OTP,Accept-Encoding, Accept, X-Requested-With", |
| + "cache_control": "private, max-age=60, s-maxage=60", |
| + "x_ratelimit_used_present": true, |
| + "total_count": 2, |
| + "repositories": [ |
| + "probe", |
| + "probe-other" |
| + ], |
| + "repo_ids_present": true, |
| + "permissions_in_items": [ |
| + "{\"admin\": false, \"maintain\": false, \"push\": false, \"triage\": false, \"pull\": false}" |
| + ] |
| + }, |
| + { |
| + "call": "GET /installation/repositories?per_page=100 (token B, If-None-Match from token B)", |
| + "status": 304, |
| + "if_none_match_sent": true, |
| + "etag_hash": "ce4399ed", |
| + "etag_weak": false, |
| + "vary": "Accept, Authorization, Cookie, X-GitHub-OTP,Accept-Encoding, Accept, X-Requested-With", |
| + "cache_control": "private, max-age=60, s-maxage=60", |
| + "x_ratelimit_used_present": true, |
| + "total_count": null, |
| + "repositories": null, |
| + "repo_ids_present": null, |
| + "permissions_in_items": null |
| + }, |
| + { |
| + "call": "GET /repos/{org}/probe/contents/README.md (token A)", |
| + "status": 403 |
| + }, |
| + { |
| + "call": "DELETE /installation/token (A)", |
| + "status": 204 |
| + }, |
| + { |
| + "call": "DELETE /installation/token (B)", |
| + "status": 204 |
| + }, |
| + { |
| + "call": "GET /installation/repositories after revoke (token A)", |
| + "status": 401 |
| + } |
| + ], |
| + "installation": { |
| + "status": 200, |
| + "repository_selection": "all", |
| + "suspended_at": null |
| + }, |
| + "etag_same_across_tokens": false |
| +} |
| +``` |
diff --git a/go.mod b/go.mod| index a441c20d..7f972759 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -21,6 +21,7 @@ require ( |
| amadan.net/oficina/home/connect v0.0.0-20261122114341-150d94e2370f |
| amadan.net/oficina/home/handoff v0.0.0-20261122114341-150d94e2370f |
| amadan.net/rastrillo/fiesta v1.6.1 |
| + github.com/spf13/viper v1.19.0 |
| github.com/sqids/sqids-go v0.4.1 |
| golang.org/x/crypto v0.55.0 |
| golang.org/x/net v0.58.0 |
| @@ -84,7 +85,6 @@ require ( |
| github.com/spf13/cast v1.7.1 // indirect |
| github.com/spf13/cobra v1.9.1 // indirect |
| github.com/spf13/pflag v1.0.6 // indirect |
| - github.com/spf13/viper v1.19.0 // indirect |
| github.com/subosito/gotenv v1.6.0 // indirect |
| github.com/tdewolff/minify/v2 v2.24.19 // indirect |
| github.com/tdewolff/parse/v2 v2.8.16 // indirect |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index a9d1e940..4457caf8 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -54,6 +54,11 @@ type application struct { |
| func (a *application) startBackground() *background.Group { |
| a.start.Do(func() { |
| + a.background.Loop(context.Background(), 15*time.Second, func() { |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + a.store.forge.API.Expire(ctx) |
| + }) |
| if a.executionEnabled && a.store.execution != nil { |
| execution := a.store.execution |
| a.background.Loop(context.Background(), 5*time.Second, func() { |
| @@ -86,6 +91,9 @@ func (a *application) startBackground() *background.Group { |
| a.background.Loop(context.Background(), time.Minute, func() { |
| ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| defer cancel() |
| + if err := a.store.forge.Sweep(ctx); err != nil { |
| + a.logger.Error(copyText("github.check_failed")) |
| + } |
| if err := a.store.personDevices().Sweep(ctx); err != nil { |
| a.logger.Error(copyAuthSweep, "err", err) |
| } |
| @@ -256,6 +264,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| runner := a.store.runnerRouter() |
| store.personOrigin = cfg.Origin |
| store.personKey = cfg.InstanceKey |
| + store.configureGitHub(cfg) |
| store.personCookie = func(r *http.Request) (personapi.PersonPrincipal, error) { |
| id, ok := a.sessionFrom(r) |
| if !ok { |
| @@ -280,6 +289,8 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| a.Post("/api/enrolments/token", a.exchangeEnrolment) |
| a.Mount("/api/runner/v2", runner) |
| a.Get(wire.StreamPath, a.store.RunnerStreamHandler(a.logger).ServeHTTP) |
| + a.Get("/github/connect/manifest", a.githubManifest) |
| + a.Get("/github/connect/installation", a.githubInstallation) |
| a.Get(wire.RunnerProtocolPath, func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Content-Type", "application/json") |
| w.Header().Set("Cache-Control", "no-store") |
| @@ -394,6 +405,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Get("/conversation/settings/housekeeping", a.settingsSectionHandler("housekeeping")) |
| r.Get("/conversation/connections", movedTo("/conversation/settings/connections")) |
| r.Get("/conversation/settings/connections", a.connectionsView) |
| + a.githubRoutes(r) |
| r.Get("/conversation/settings/connections/add", a.connectionsAdd) |
| r.Get("/conversation/settings/machines", a.machinesList) |
| r.Get("/conversation/settings/machines/add", a.machinesAdd) |
diff --git a/internal/equipo/config.go b/internal/equipo/config.go| index a6f60157..95754ef0 100644 |
| --- a/internal/equipo/config.go |
| +++ b/internal/equipo/config.go |
| @@ -6,6 +6,7 @@ import ( |
| "amadan.net/oficina/home/connect" |
| "errors" |
| "net" |
| + "net/http" |
| "net/url" |
| "regexp" |
| "strconv" |
| @@ -13,6 +14,9 @@ import ( |
| ) |
| type Config struct { |
| + GitHubEnabled bool |
| + // GitHubTransport is a trusted embedding/test transport. URLs remain pinned. |
| + GitHubTransport http.RoundTripper |
| AgentIssuer string |
| AgentTeam string |
| Home *connect.DecodedCredentials |
| @@ -55,6 +59,7 @@ type Config struct { |
| func LoadConfig(getenv func(string) string) (Config, error) { |
| cfg := Config{AgentIssuer: getenv("EQUIPO_AGENT_ISSUER"), AgentTeam: getenv("EQUIPO_AGENT_TEAM"), RunnerReleaseDir: getenv("EQUIPO_RUNNER_RELEASE_DIR"), |
| + GitHubEnabled: getenv("EQUIPO_GITHUB") == "1", |
| ExecutionEnabled: getenv("EQUIPO_EXECUTION_ENABLED") == "1", |
| ExecutionMarkerPath: getenv("EQUIPO_EXECUTION_MARKER_PATH"), |
| Origin: strings.TrimSpace(getenv("EQUIPO_ORIGIN")), |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index b6dba594..7298c061 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -73,6 +73,38 @@ const CopyGitHubEgress = "GitHub reachable: %t; status: %d; latency: %s; TLS pee |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + "github.title": "GitHub", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.connect": "Connect GitHub", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.account": "GitHub account", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.account_type": "Account type", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.organization": "Organization", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.personal_account": "Personal account", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.create_app": "Create a GitHub App", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.create_hint": "GitHub will ask you to create a GitHub App and choose the repositories Equipo can access.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.confirm_account": "Connect %s", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.repository_count": "Repositories: %d", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.confirm": "Connect", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.connected": "GitHub is connected", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.already_connected": "GitHub is already connected for %s.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.disconnect": "Disconnect", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.disconnect_hint": "Disconnecting stops Equipo from reading these GitHub repositories. These projects stay listed.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.pending": "The GitHub App is not connected yet.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.pending_hint": "You can check again for up to 24 hours after creating the GitHub App.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.pending_approval": "If approval is needed, ask a GitHub organization owner to approve it.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.check_again": "Check again", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.redirect_expired": "This GitHub setup link has expired. If you created the GitHub App, select Check again. Otherwise, start again.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.pending_expired": "The 24-hour setup window has ended. Connect GitHub again to create a new GitHub App.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.setup_failed": "GitHub setup could not be completed. Start again to create a new GitHub App.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.app_remains": "The GitHub App still exists on GitHub. You can delete it in GitHub App settings.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.app_settings": "Open GitHub App settings", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.reconnect": "Connect GitHub again", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.reconnect_hint": "Equipo can no longer use this GitHub App. Connect GitHub again to create a new one.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.check_failed": "Equipo could not check GitHub right now. Try again later.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.not_connected": "GitHub is not connected", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.suspended": "GitHub access is suspended", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.too_many": "Equipo can list up to %s repositories from this GitHub account. Choose fewer repositories on GitHub.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + "github.choose_repositories": "Choose repositories on GitHub", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| + |
| "api.repo_not_allowed": "Your runner can't reach this project's repository. Make sure the repository is available, then try again.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| "api.card_answered": "This card has already been answered. Check the conversation for what happened.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
| "api.card_stale": "This item has changed. Check it before trying again.", // COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23) |
diff --git a/internal/equipo/github/budget_test.go b/internal/equipo/github/budget_test.go| new file mode 100644 |
| index 00000000..bb92ac33 |
| --- /dev/null |
| +++ b/internal/equipo/github/budget_test.go |
| @@ -0,0 +1,9 @@ |
| +package github |
| + |
| +import ( |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "os" |
| + "testing" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
diff --git a/internal/equipo/github/callback.go b/internal/equipo/github/callback.go| new file mode 100644 |
| index 00000000..96763a7e |
| --- /dev/null |
| +++ b/internal/equipo/github/callback.go |
| @@ -0,0 +1,127 @@ |
| +package github |
| + |
| +import ( |
| + "context" |
| + "gorm.io/gorm" |
| + "net/url" |
| +) |
| + |
| +func (s *Store) claimCallback(ctx context.Context, p Principal, state, stage string) (Connection, error) { |
| + var c Connection |
| + var refused error |
| + if state == "" { |
| + return c, ErrAccess |
| + } |
| + err := s.write(ctx, p, func(tx *gorm.DB) error { |
| + column := "manifest_hash" |
| + if stage == "installation" { |
| + column = "installation_hash" |
| + } |
| + if err := tx.Where(column+" = ?", digest(state)).First(&c).Error; err != nil { |
| + return ErrAccess |
| + } |
| + if c.Owner != p.Address || c.Session != digest(p.Session) || c.Origin != s.Origin { |
| + return ErrAccess |
| + } |
| + if !s.now().Before(c.RedirectUntil) { |
| + if stage == "manifest" { |
| + erase(&c, "manifest_expired") |
| + } else if !s.now().Before(c.PendingUntil) { |
| + erase(&c, "expired") |
| + } else { |
| + c.InstallationHash = "" |
| + c.State = "installation_expired" |
| + } |
| + if err := s.save(tx, p, &c, "forge.expire_redirect"); err != nil { |
| + return err |
| + } |
| + refused = &Refusal{s.view(c), ErrAccess} |
| + return nil |
| + } |
| + if stage == "manifest" { |
| + c.ManifestHash = "" |
| + c.State = "converting" |
| + } else { |
| + c.InstallationHash = "" |
| + } |
| + return s.save(tx, p, &c, "forge.claim_"+stage) |
| + }) |
| + if err != nil { |
| + return c, err |
| + } |
| + return c, refused |
| +} |
| +func (s *Store) Convert(ctx context.Context, p Principal, state, code string) (View, error) { |
| + claimed, err := s.claimCallback(ctx, p, state, "manifest") |
| + if err != nil { |
| + return s.view(claimed), err |
| + } |
| + app, callErr := s.API.Convert(ctx, code) |
| + if callErr == nil { |
| + if app.Owner.Type != claimed.AccountType || !equalLogin(app.Owner.Login, claimed.Login) { |
| + callErr = ErrAccess |
| + } else { |
| + app, callErr = s.API.Verify(ctx, app) |
| + } |
| + } |
| + var result Connection |
| + err = s.write(ctx, p, func(tx *gorm.DB) error { |
| + if e := tx.First(&result, "id = ?", claimed.ID).Error; e != nil { |
| + return e |
| + } |
| + if result.Generation != claimed.Generation || result.State != "converting" { |
| + return ErrAccess |
| + } |
| + var slot Pending |
| + if tx.First(&slot, "id = ?", 1).Error != nil || slot.ConnectionID != result.ID { |
| + return ErrAccess |
| + } |
| + if callErr != nil { |
| + erase(&result, "failed") |
| + return s.save(tx, p, &result, "forge.convert_failed") |
| + } |
| + sealed, e := sealKey(s.Root, s.Origin, result.ID, app.ID, app.pem) |
| + if e != nil { |
| + return e |
| + } |
| + result.AppID, result.Slug, result.AccountID, result.Login = app.ID, app.Slug, app.Owner.ID, app.Owner.Login |
| + result.SealedKey, result.State = sealed, "pending" |
| + result.PendingUntil = s.now().Add(24 * hour) |
| + result.InstallationHash = digest(s.state(result, "installation")) |
| + return s.save(tx, p, &result, "forge.convert") |
| + }) |
| + if err != nil { |
| + return View{}, err |
| + } |
| + if callErr != nil { |
| + return s.view(result), &Refusal{s.view(result), callErr} |
| + } |
| + return s.view(result), nil |
| +} |
| +func (s *Store) Install(ctx context.Context, p Principal, state string) (View, error) { |
| + c, err := s.claimCallback(ctx, p, state, "installation") |
| + if err != nil { |
| + return s.view(c), err |
| + } |
| + return s.Check(ctx, p, c.ID) |
| +} |
| + |
| +// InstallationURL is used only after the first callback's clean-URL redirect. |
| +// The raw state is derived in memory; only its digest is stored. |
| +func (s *Store) InstallationURL(ctx context.Context, p Principal, id string) (string, error) { |
| + if !s.Enabled { |
| + return "", ErrAccess |
| + } |
| + tx := s.primary(ctx) |
| + if err := s.Owner(tx, p.Address); err != nil { |
| + return "", err |
| + } |
| + var c Connection |
| + if err := tx.First(&c, "id = ?", id).Error; err != nil { |
| + return "", err |
| + } |
| + if c.Owner != p.Address || c.Session != digest(p.Session) || c.Origin != s.Origin || c.InstallationHash == "" || c.SealedKey == "" || !s.now().Before(c.RedirectUntil) { |
| + return "", ErrAccess |
| + } |
| + return "https://github.com/apps/" + url.PathEscape(c.Slug) + "/installations/new?state=" + url.QueryEscape(s.state(c, "installation")), nil |
| +} |
diff --git a/internal/equipo/github/check.go b/internal/equipo/github/check.go| new file mode 100644 |
| index 00000000..b3ebe029 |
| --- /dev/null |
| +++ b/internal/equipo/github/check.go |
| @@ -0,0 +1,185 @@ |
| +package github |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "errors" |
| + "strings" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +const hour = time.Hour |
| + |
| +func equalLogin(a, b string) bool { return strings.EqualFold(a, b) } |
| +func (s *Store) expired(c Connection) string { |
| + if !c.Confirmed && !c.PendingUntil.IsZero() && !s.now().Before(c.PendingUntil) { |
| + return "expired" |
| + } |
| + if c.Confirmed && !c.UninstalledAt.IsZero() && !s.now().Before(c.UninstalledAt.Add(7*24*time.Hour)) { |
| + return "uninstalled_expired" |
| + } |
| + return "" |
| +} |
| +func (s *Store) Check(ctx context.Context, p Principal, id string) (View, error) { |
| + var claimed Connection |
| + var refused error |
| + err := s.write(ctx, p, func(tx *gorm.DB) error { |
| + if err := tx.First(&claimed, "id = ?", id).Error; err != nil { |
| + return err |
| + } |
| + if state := s.expired(claimed); state != "" && claimed.SealedKey != "" { |
| + erase(&claimed, state) |
| + if err := s.save(tx, p, &claimed, "forge.expire"); err != nil { |
| + return err |
| + } |
| + if err := tx.Where("connection_id = ?", id).Delete(&Pending{}).Error; err != nil { |
| + return err |
| + } |
| + refused = &Refusal{s.view(claimed), ErrAccess} |
| + return nil |
| + } |
| + if claimed.SealedKey == "" { |
| + return ErrAccess |
| + } |
| + if claimed.Claim != "" && s.now().Before(claimed.ClaimUntil) { |
| + return ErrUnavailable |
| + } |
| + claimed.Claim = strings.ToLower(rand.Text()) |
| + claimed.ClaimUntil = s.now().Add(30 * time.Second) |
| + return s.save(tx, p, &claimed, "forge.check_claim") |
| + }) |
| + if err != nil { |
| + return View{}, err |
| + } |
| + if refused != nil { |
| + s.API.Forget(ctx, claimed.AppID) |
| + return s.view(claimed), refused |
| + } |
| + app, callErr := s.app(claimed) |
| + var installation Installation |
| + var inventory Inventory |
| + found := false |
| + if callErr == nil { |
| + app, callErr = s.API.Verify(ctx, app) |
| + } |
| + if callErr == nil { |
| + var rows []Installation |
| + rows, callErr = s.API.Installations(ctx, app) |
| + if callErr == nil { |
| + for _, row := range rows { |
| + if row.AppID == app.ID && row.Account.ID == app.Owner.ID { |
| + if found { |
| + callErr = ErrAccess |
| + break |
| + } |
| + installation = row |
| + found = true |
| + } |
| + } |
| + } |
| + } |
| + if callErr == nil && found { |
| + installation, callErr = s.API.Installation(ctx, app, installation.ID) |
| + } |
| + if callErr == nil && found && installation.Suspended == nil { |
| + inventory, callErr = s.API.Inventory(ctx, app, installation) |
| + } |
| + var result Connection |
| + err = s.write(ctx, p, func(tx *gorm.DB) error { |
| + if err := tx.First(&result, "id = ?", id).Error; err != nil { |
| + return err |
| + } |
| + if result.Generation != claimed.Generation || result.Claim != claimed.Claim || !s.now().Before(result.ClaimUntil) { |
| + return ErrAccess |
| + } |
| + if app.ID == result.AppID && app.Slug != "" { |
| + result.Slug = app.Slug |
| + } |
| + result.Claim = "" |
| + result.ClaimUntil = time.Time{} |
| + if state := s.expired(result); state != "" { |
| + erase(&result, state) |
| + refused = &Refusal{s.view(result), ErrAccess} |
| + } else if errors.Is(callErr, ErrReconnect) { |
| + erase(&result, "reconnect") |
| + refused = &Refusal{s.view(result), ErrReconnect} |
| + } else if errors.Is(callErr, ErrTooMany) { |
| + result.State = "too_many" |
| + result.CountKnown = false |
| + result.InstallationID = installation.ID |
| + result.Selection = installation.Selection |
| + } else if callErr != nil { |
| + result.State = "check_failed" |
| + result.CountKnown = false |
| + refused = &Refusal{s.view(result), callErr} |
| + } else if !found { |
| + result.CountKnown = false |
| + if result.Confirmed { |
| + result.State = "uninstalled" |
| + if result.UninstalledAt.IsZero() { |
| + result.UninstalledAt = s.now() |
| + } |
| + } else { |
| + result.State = "pending" |
| + } |
| + } else if installation.Suspended != nil { |
| + result.State = "suspended" |
| + result.CountKnown = false |
| + result.InstallationID = installation.ID |
| + } else { |
| + result.InstallationID = installation.ID |
| + result.Selection = installation.Selection |
| + result.Count = inventory.Count |
| + result.CountKnown = true |
| + result.UninstalledAt = time.Time{} |
| + result.Login = installation.Account.Login |
| + result.State = "ready" |
| + if result.Confirmed { |
| + result.State = "live" |
| + } |
| + } |
| + return s.save(tx, p, &result, "forge.check") |
| + }) |
| + if err != nil || result.SealedKey == "" || result.State == "uninstalled" || result.State == "suspended" { |
| + s.API.Forget(ctx, claimed.AppID) |
| + } |
| + if err != nil { |
| + return View{}, err |
| + } |
| + return s.view(result), refused |
| +} |
| +func (s *Store) Connect(ctx context.Context, p Principal, id string) (View, error) { |
| + checked, err := s.Check(ctx, p, id) |
| + if err != nil { |
| + return checked, err |
| + } |
| + var c Connection |
| + err = s.write(ctx, p, func(tx *gorm.DB) error { |
| + if err := tx.First(&c, "id = ?", id).Error; err != nil { |
| + return err |
| + } |
| + if c.Generation != checked.Generation { |
| + return ErrAccess |
| + } |
| + if c.Confirmed && c.State == "live" { |
| + return nil |
| + } |
| + if c.State != "ready" || !c.CountKnown || c.Count > MaxRepositories || c.SealedKey == "" || s.expired(c) != "" { |
| + return &Refusal{s.view(c), ErrAccess} |
| + } |
| + c.Confirmed = true |
| + c.State = "live" |
| + c.ActiveAccount = &c.AccountID |
| + if err := s.save(tx, p, &c, "forge.connect"); err != nil { |
| + return err |
| + } |
| + return tx.Where("connection_id = ?", id).Delete(&Pending{}).Error |
| + }) |
| + result := s.view(c) |
| + if err == nil && checked.Confirmed { |
| + result.State = "already_connected" |
| + } |
| + return result, err |
| +} |
diff --git a/internal/equipo/github/client.go b/internal/equipo/github/client.go| new file mode 100644 |
| index 00000000..311696bb |
| --- /dev/null |
| +++ b/internal/equipo/github/client.go |
| @@ -0,0 +1,416 @@ |
| +// Package github is the instance's GitHub App client and forge connection lifecycle. |
| +package github |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto" |
| + "crypto/rand" |
| + "crypto/rsa" |
| + "crypto/sha256" |
| + "crypto/x509" |
| + "encoding/base64" |
| + "encoding/json" |
| + "encoding/pem" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "maps" |
| + "net/http" |
| + "net/url" |
| + "regexp" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +var ( |
| + ErrUnavailable = errors.New("github: unavailable") |
| + ErrAccess = errors.New("github: access refused") |
| + ErrRateLimit = errors.New("github: rate limited") |
| + ErrTooMany = errors.New("github: repository limit") |
| +) |
| + |
| +const MaxRepositories = 1000 |
| +const maxAnswer = 2 << 20 |
| + |
| +var component = regexp.MustCompile(`^[A-Za-z0-9_-]{1,256}$`) |
| +var loginPattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$`) |
| + |
| +func ValidAccount(login, kind string) bool { |
| + return loginPattern.MatchString(login) && (kind == "Organization" || kind == "User") |
| +} |
| +func permissions() map[string]string { |
| + return map[string]string{"contents": "write", "pull_requests": "write", "checks": "read", "statuses": "read", "actions": "read", "metadata": "read"} |
| +} |
| + |
| +type Account struct { |
| + ID int64 `json:"id"` |
| + Login string `json:"login"` |
| + Type string `json:"type"` |
| +} |
| +type App struct { |
| + ID int64 `json:"id"` |
| + Slug string `json:"slug"` |
| + Owner Account `json:"owner"` |
| + Permissions map[string]string `json:"permissions"` |
| + Events []string `json:"events"` |
| + pem string |
| + generation int64 |
| +} |
| + |
| +func (a App) String() string { return fmt.Sprintf("github.App(%d)", a.ID) } |
| +func (a App) GoString() string { return a.String() } |
| + |
| +type Installation struct { |
| + ID int64 `json:"id"` |
| + AppID int64 `json:"app_id"` |
| + Account Account `json:"account"` |
| + Permissions map[string]string `json:"permissions"` |
| + Events []string `json:"events"` |
| + Selection string `json:"repository_selection"` |
| + Suspended *time.Time `json:"suspended_at"` |
| +} |
| +type Repository struct { |
| + ID int64 `json:"id"` |
| + Name string `json:"full_name"` |
| + Owner Account `json:"owner"` |
| +} |
| +type Inventory struct { |
| + Repositories []Repository |
| + Count int |
| +} |
| +type APIError struct { |
| + Status int |
| + Kind error |
| +} |
| + |
| +func (e *APIError) Error() string { return e.Kind.Error() } |
| +func (e *APIError) Unwrap() error { return e.Kind } |
| + |
| +// metadataCredential never leaves the instance or becomes a project grant. |
| +type metadataCredential struct { |
| + value string |
| + expires time.Time |
| + installation int64 |
| + selection string |
| + pages map[int]inventoryPage |
| + generation int64 |
| +} |
| +type API struct { |
| + client *http.Client |
| + now func() time.Time |
| + mu sync.Mutex |
| + tokens map[int64]metadataCredential |
| +} |
| + |
| +func NewAPI(transport http.RoundTripper, now func() time.Time) *API { |
| + if transport == nil { |
| + transport = http.DefaultTransport |
| + if base, ok := transport.(*http.Transport); ok { |
| + owned := base.Clone() |
| + owned.MaxResponseHeaderBytes = 32 << 10 |
| + transport = owned |
| + } |
| + } |
| + if now == nil { |
| + now = time.Now |
| + } |
| + return &API{client: &http.Client{Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, now: now, tokens: map[int64]metadataCredential{}} |
| +} |
| +func (a *API) request(ctx context.Context, method, path, credential string, body, out any, conditional ...string) (http.Header, error) { |
| + var payload []byte |
| + var err error |
| + if body != nil { |
| + payload, err = json.Marshal(body) |
| + if err != nil { |
| + return nil, ErrUnavailable |
| + } |
| + } |
| + req, err := http.NewRequestWithContext(ctx, method, "https://api.github.com"+path, bytes.NewReader(payload)) |
| + if err != nil { |
| + return nil, ErrUnavailable |
| + } |
| + req.Header.Set("Accept", "application/vnd.github+json") |
| + req.Header.Set("X-GitHub-Api-Version", "2022-11-28") |
| + req.Header.Set("User-Agent", "Equipo") |
| + if body != nil { |
| + req.Header.Set("Content-Type", "application/json") |
| + } |
| + if credential != "" { |
| + req.Header.Set("Authorization", "Bearer "+credential) |
| + } |
| + if len(conditional) == 1 && conditional[0] != "" { |
| + req.Header.Set("If-None-Match", conditional[0]) |
| + } |
| + response, err := a.client.Do(req) |
| + if err != nil { |
| + return nil, ErrUnavailable |
| + } |
| + defer response.Body.Close() |
| + if response.StatusCode == http.StatusNotModified { |
| + return response.Header, errNotModified |
| + } |
| + if response.StatusCode < 200 || response.StatusCode >= 300 { |
| + kind := ErrUnavailable |
| + if response.StatusCode == 401 || response.StatusCode == 403 || response.StatusCode == 404 || response.StatusCode == 422 { |
| + kind = ErrAccess |
| + } |
| + if response.StatusCode == 429 || (response.StatusCode == 403 && (response.Header.Get("X-RateLimit-Remaining") == "0" || response.Header.Get("Retry-After") != "")) { |
| + kind = ErrRateLimit |
| + } |
| + return nil, &APIError{response.StatusCode, kind} |
| + } |
| + if out == nil { |
| + return response.Header, nil |
| + } |
| + raw, err := io.ReadAll(io.LimitReader(response.Body, maxAnswer+1)) |
| + if err != nil || len(raw) > maxAnswer { |
| + return nil, ErrUnavailable |
| + } |
| + if json.Unmarshal(raw, out) != nil { |
| + return nil, ErrUnavailable |
| + } |
| + return response.Header, nil |
| +} |
| +func parseKey(raw string) (*rsa.PrivateKey, error) { |
| + block, rest := pem.Decode([]byte(raw)) |
| + if block == nil || len(bytes.TrimSpace(rest)) != 0 { |
| + return nil, ErrUnavailable |
| + } |
| + var key *rsa.PrivateKey |
| + if block.Type == "RSA PRIVATE KEY" { |
| + key, _ = x509.ParsePKCS1PrivateKey(block.Bytes) |
| + } else if block.Type == "PRIVATE KEY" { |
| + value, _ := x509.ParsePKCS8PrivateKey(block.Bytes) |
| + key, _ = value.(*rsa.PrivateKey) |
| + } |
| + if key == nil || key.N.BitLen() < 2048 || key.Validate() != nil { |
| + return nil, ErrUnavailable |
| + } |
| + return key, nil |
| +} |
| +func (a *API) jwt(app App) (string, error) { |
| + key, err := parseKey(app.pem) |
| + if err != nil || app.ID <= 0 { |
| + return "", ErrUnavailable |
| + } |
| + raw, _ := json.Marshal(map[string]any{"iss": strconv.FormatInt(app.ID, 10), "iat": a.now().Add(-time.Minute).Unix(), "exp": a.now().Add(5 * time.Minute).Unix()}) |
| + message := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","typ":"JWT"}`)) + "." + base64.RawURLEncoding.EncodeToString(raw) |
| + digest := sha256.Sum256([]byte(message)) |
| + sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:]) |
| + if err != nil { |
| + return "", ErrUnavailable |
| + } |
| + return message + "." + base64.RawURLEncoding.EncodeToString(sig), nil |
| +} |
| +func validApp(app App) bool { |
| + return app.ID > 0 && component.MatchString(app.Slug) && app.Owner.ID > 0 && ValidAccount(app.Owner.Login, app.Owner.Type) && maps.Equal(app.Permissions, permissions()) && app.Events != nil && len(app.Events) == 0 |
| +} |
| +func (a *API) Convert(ctx context.Context, code string) (App, error) { |
| + if !component.MatchString(code) { |
| + return App{}, ErrAccess |
| + } |
| + var reply struct { |
| + App |
| + PEM string `json:"pem"` |
| + } |
| + _, err := a.request(ctx, "POST", "/app-manifests/"+code+"/conversions", "", nil, &reply) |
| + if err != nil { |
| + return App{}, err |
| + } |
| + if !validApp(reply.App) { |
| + return App{}, ErrAccess |
| + } |
| + if _, err = parseKey(reply.PEM); err != nil { |
| + return App{}, err |
| + } |
| + reply.App.pem = reply.PEM |
| + return reply.App, nil |
| +} |
| +func (a *API) Verify(ctx context.Context, app App) (App, error) { |
| + jwt, err := a.jwt(app) |
| + if err != nil { |
| + return App{}, err |
| + } |
| + var reply App |
| + _, err = a.request(ctx, "GET", "/app", jwt, nil, &reply) |
| + if err != nil { |
| + return App{}, err |
| + } |
| + if !validApp(reply) || reply.ID != app.ID || reply.Owner.ID != app.Owner.ID || reply.Owner.Type != app.Owner.Type { |
| + return App{}, ErrAccess |
| + } |
| + reply.pem = app.pem |
| + return reply, nil |
| +} |
| +func (a *API) Installations(ctx context.Context, app App) ([]Installation, error) { |
| + jwt, err := a.jwt(app) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var all []Installation |
| + for page := 1; page <= 10; page++ { |
| + var rows []Installation |
| + headers, err := a.request(ctx, "GET", fmt.Sprintf("/app/installations?per_page=100&page=%d", page), jwt, nil, &rows) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(rows) > 100 { |
| + return nil, ErrUnavailable |
| + } |
| + all = append(all, rows...) |
| + more, err := nextPage(headers, "/app/installations", page) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !more { |
| + return all, nil |
| + } |
| + } |
| + return nil, ErrUnavailable |
| +} |
| +func (a *API) Installation(ctx context.Context, app App, id int64) (Installation, error) { |
| + if id <= 0 { |
| + return Installation{}, ErrAccess |
| + } |
| + jwt, err := a.jwt(app) |
| + if err != nil { |
| + return Installation{}, err |
| + } |
| + var reply Installation |
| + _, err = a.request(ctx, "GET", fmt.Sprintf("/app/installations/%d", id), jwt, nil, &reply) |
| + if err != nil { |
| + return Installation{}, err |
| + } |
| + if reply.ID != id || reply.AppID != app.ID || reply.Account.ID != app.Owner.ID || !ValidAccount(reply.Account.Login, reply.Account.Type) || reply.Account.Type != app.Owner.Type || !maps.Equal(reply.Permissions, permissions()) || reply.Events == nil || len(reply.Events) != 0 || (reply.Selection != "selected" && reply.Selection != "all") { |
| + return Installation{}, ErrAccess |
| + } |
| + return reply, nil |
| +} |
| +func nextPage(headers http.Header, path string, page int) (bool, error) { |
| + more := false |
| + for _, part := range strings.Split(headers.Get("Link"), ",") { |
| + part = strings.TrimSpace(part) |
| + if part == "" { |
| + continue |
| + } |
| + fields := strings.SplitN(part, ";", 2) |
| + if len(fields) != 2 { |
| + return false, ErrUnavailable |
| + } |
| + u, err := url.Parse(strings.Trim(fields[0], "<> ")) |
| + if err != nil || u.Scheme != "https" || u.Host != "api.github.com" || u.User != nil || u.Path != path || u.Fragment != "" { |
| + return false, ErrUnavailable |
| + } |
| + if strings.Contains(fields[1], `rel="next"`) { |
| + if more || u.Query().Get("page") != strconv.Itoa(page+1) || u.Query().Get("per_page") != "100" { |
| + return false, ErrUnavailable |
| + } |
| + more = true |
| + } |
| + } |
| + return more, nil |
| +} |
| +func (a *API) metadata(ctx context.Context, app App, inst Installation) (string, error) { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + old := a.tokens[app.ID] |
| + if old.value != "" && old.installation == inst.ID && old.selection == inst.Selection && a.now().Add(30*time.Second).Before(old.expires) { |
| + return old.value, nil |
| + } |
| + delete(a.tokens, app.ID) |
| + if old.value != "" { |
| + _, _ = a.request(ctx, "DELETE", "/installation/token", old.value, nil, nil) |
| + } |
| + jwt, err := a.jwt(app) |
| + if err != nil { |
| + return "", err |
| + } |
| + var reply struct { |
| + Token string `json:"token"` |
| + Expires time.Time `json:"expires_at"` |
| + Permissions map[string]string `json:"permissions"` |
| + Selection string `json:"repository_selection"` |
| + } |
| + _, err = a.request(ctx, "POST", fmt.Sprintf("/app/installations/%d/access_tokens", inst.ID), jwt, map[string]any{"permissions": map[string]string{"metadata": "read"}}, &reply) |
| + if err != nil { |
| + return "", err |
| + } |
| + if reply.Token == "" || strings.ContainsAny(reply.Token, "\r\n\x00 ") || !maps.Equal(reply.Permissions, map[string]string{"metadata": "read"}) || !a.now().Add(30*time.Second).Before(reply.Expires) || reply.Expires.After(a.now().Add(time.Hour)) || reply.Selection != inst.Selection { |
| + if reply.Token != "" && !strings.ContainsAny(reply.Token, "\r\n\x00 ") { |
| + _, _ = a.request(ctx, "DELETE", "/installation/token", reply.Token, nil, nil) |
| + } |
| + return "", ErrAccess |
| + } |
| + a.tokens[app.ID] = metadataCredential{value: reply.Token, expires: reply.Expires, installation: inst.ID, selection: inst.Selection, pages: map[int]inventoryPage{}, generation: app.generation} |
| + return reply.Token, nil |
| +} |
| +func (a *API) Inventory(ctx context.Context, app App, inst Installation) (Inventory, error) { |
| + if inst.ID <= 0 || inst.AppID != app.ID || inst.Account.ID != app.Owner.ID || inst.Suspended != nil { |
| + return Inventory{}, ErrAccess |
| + } |
| + token, err := a.metadata(ctx, app, inst) |
| + if err != nil { |
| + return Inventory{}, err |
| + } |
| + all := []Repository{} |
| + seen := map[int64]bool{} |
| + total := -1 |
| + for page := 1; page <= 11; page++ { |
| + var reply inventoryReply |
| + cached := a.cachedPage(app, token, page) |
| + headers, err := a.request(ctx, "GET", fmt.Sprintf("/installation/repositories?per_page=100&page=%d", page), token, nil, &reply, cached.etag) |
| + if errors.Is(err, errNotModified) { |
| + if cached.etag == "" { |
| + return Inventory{}, ErrUnavailable |
| + } |
| + reply = cached.reply |
| + headers = cached.headers |
| + err = nil |
| + } |
| + if err != nil { |
| + return Inventory{}, err |
| + } |
| + if reply.Total == nil || reply.Rows == nil { |
| + return Inventory{}, ErrUnavailable |
| + } |
| + if *reply.Total > MaxRepositories || len(all)+len(reply.Rows) > MaxRepositories { |
| + return Inventory{}, ErrTooMany |
| + } |
| + if *reply.Total < 0 || len(reply.Rows) > 100 || (total >= 0 && *reply.Total != total) { |
| + return Inventory{}, ErrUnavailable |
| + } |
| + total = *reply.Total |
| + for _, r := range reply.Rows { |
| + parts := strings.Split(r.Name, "/") |
| + if r.ID <= 0 || seen[r.ID] || r.Owner.ID != app.Owner.ID || len(parts) != 2 || !strings.EqualFold(parts[0], r.Owner.Login) || parts[1] == "" || strings.ContainsAny(r.Name, "\r\n\x00 ?#") { |
| + return Inventory{}, ErrAccess |
| + } |
| + seen[r.ID] = true |
| + all = append(all, r) |
| + } |
| + a.cachePage(app, token, page, inventoryPage{headers.Get("ETag"), reply, headers.Clone()}) |
| + more, err := nextPage(headers, "/installation/repositories", page) |
| + if err != nil { |
| + return Inventory{}, err |
| + } |
| + if !more { |
| + if len(all) != total { |
| + return Inventory{}, ErrUnavailable |
| + } |
| + return Inventory{all, total}, nil |
| + } |
| + } |
| + return Inventory{}, ErrTooMany |
| +} |
| +func (a *API) Forget(ctx context.Context, id int64) { |
| + a.mu.Lock() |
| + entry := a.tokens[id] |
| + delete(a.tokens, id) |
| + a.mu.Unlock() |
| + if entry.value != "" { |
| + _, _ = a.request(ctx, "DELETE", "/installation/token", entry.value, nil, nil) |
| + } |
| +} |
diff --git a/internal/equipo/github/client_test.go b/internal/equipo/github/client_test.go| new file mode 100644 |
| index 00000000..726d89f1 |
| --- /dev/null |
| +++ b/internal/equipo/github/client_test.go |
| @@ -0,0 +1,132 @@ |
| +package github |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/forge/forgetest" |
| +) |
| + |
| +func TestAppAPIContract(t *testing.T) { |
| + g := forgetest.NewGitHub(t) |
| + api := NewAPI(g.Transport(), func() time.Time { return g.Now }) |
| + ctx := context.Background() |
| + app, err := api.Convert(ctx, g.Code) |
| + if err != nil { |
| + t.Fatal("conversion:", err) |
| + } |
| + if app.ID != g.AppID || app.Owner.ID != g.AccountID || app.pem != g.PEM { |
| + t.Fatal("conversion lost identity or key") |
| + } |
| + verified, err := api.Verify(ctx, app) |
| + if err != nil || verified.ID != app.ID { |
| + t.Fatal("JWT verification:", err) |
| + } |
| + rows, err := api.Installations(ctx, app) |
| + if err != nil || len(rows) != 1 { |
| + t.Fatal("installation listing:", err) |
| + } |
| + installation, err := api.Installation(ctx, app, rows[0].ID) |
| + if err != nil || installation.Account.ID != g.AccountID { |
| + t.Fatal("installation read:", err) |
| + } |
| + for _, mode := range []string{"selected", "all"} { |
| + g.Selection = mode |
| + installation, err = api.Installation(ctx, app, g.InstallationID) |
| + if err != nil || installation.Selection != mode { |
| + t.Fatal("repository selection:", err) |
| + } |
| + } |
| + inventory, err := api.Inventory(ctx, app, installation) |
| + if err != nil || inventory.Count != 2 || len(inventory.Repositories) != 2 { |
| + t.Fatal("metadata inventory:", err) |
| + } |
| + if _, err = api.Inventory(ctx, app, installation); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := g.Calls("POST", fmt.Sprintf("/app/installations/%d/access_tokens", g.InstallationID)); got != 1 { |
| + t.Fatalf("metadata token not cached in memory: %d", got) |
| + } |
| + api.Forget(ctx, app.ID) |
| + if g.Calls("DELETE", "/installation/token") != 1 { |
| + t.Fatal("metadata token not revoked") |
| + } |
| + if _, err = api.Convert(ctx, g.Code); err == nil { |
| + t.Fatal("code accepted twice") |
| + } |
| + // Diagnostic formatting must not accidentally disclose a retained App key. |
| + for _, value := range []string{fmt.Sprint(app), fmt.Sprintf("%#v", app)} { |
| + if strings.Contains(value, g.PEM) || strings.Contains(value, "PRIVATE KEY") { |
| + t.Fatal("App diagnostics disclose key") |
| + } |
| + } |
| +} |
| + |
| +func TestAppAPIRefusals(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + status int |
| + header http.Header |
| + body string |
| + want error |
| + }{ |
| + {"redirect", 302, http.Header{"Location": []string{"https://evil.example/"}}, "", ErrUnavailable}, |
| + {"access", 401, nil, "discarded body", ErrAccess}, |
| + {"rate403", 403, http.Header{"X-Ratelimit-Remaining": []string{"0"}}, "", ErrRateLimit}, |
| + {"secondary403", 403, http.Header{"Retry-After": []string{"20"}}, "", ErrRateLimit}, |
| + {"rate429", 429, nil, "", ErrRateLimit}, |
| + {"forbidden403", 403, nil, "", ErrAccess}, |
| + {"server", 503, nil, "", ErrUnavailable}, |
| + {"oversized", 200, nil, strings.Repeat("x", (2<<20)+1), ErrUnavailable}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + g := forgetest.NewGitHub(t) |
| + api := NewAPI(g.Transport(), func() time.Time { return g.Now }) |
| + app, err := api.Convert(context.Background(), g.Code) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + g.FailPath, g.FailStatus, g.FailHeaders, g.FailBody = "/app", tc.status, tc.header, tc.body+g.ClientSecret |
| + _, err = api.Verify(context.Background(), app) |
| + if !errors.Is(err, tc.want) { |
| + t.Fatalf("wrong safe outcome: %v", err) |
| + } |
| + if strings.Contains(err.Error(), g.ClientSecret) || strings.Contains(err.Error(), g.Code) { |
| + t.Fatal("API error contains a secret") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAppInventoryBound(t *testing.T) { |
| + for _, count := range []int{0, 100, 101, 1000, 1001} { |
| + t.Run(fmt.Sprint(count), func(t *testing.T) { |
| + g := forgetest.NewGitHub(t) |
| + g.Count = count |
| + api := NewAPI(g.Transport(), func() time.Time { return g.Now }) |
| + app, err := api.Convert(context.Background(), g.Code) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + inst, err := api.Installation(context.Background(), app, g.InstallationID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := api.Inventory(context.Background(), app, inst) |
| + if count > 1000 { |
| + if !errors.Is(err, ErrTooMany) || got.Count != 0 || len(got.Repositories) != 0 { |
| + t.Fatal("over-limit inventory was presented as complete") |
| + } |
| + return |
| + } |
| + if err != nil || got.Count != count || len(got.Repositories) != count { |
| + t.Fatalf("incomplete inventory: count=%d err=%v", got.Count, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/equipo/github/guards_test.go b/internal/equipo/github/guards_test.go| new file mode 100644 |
| index 00000000..e2989499 |
| --- /dev/null |
| +++ b/internal/equipo/github/guards_test.go |
| @@ -0,0 +1,291 @@ |
| +package github |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/forge/forgetest" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type transportFunc func(*http.Request) (*http.Response, error) |
| + |
| +func (f transportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| +func alter(g *forgetest.GitHub, path string, change func(map[string]any)) http.RoundTripper { |
| + base := g.Transport() |
| + return transportFunc(func(r *http.Request) (*http.Response, error) { |
| + response, err := base.RoundTrip(r) |
| + if err != nil || r.URL.Path != path { |
| + return response, err |
| + } |
| + var body map[string]any |
| + err = json.NewDecoder(response.Body).Decode(&body) |
| + response.Body.Close() |
| + if err != nil { |
| + return nil, err |
| + } |
| + change(body) |
| + raw, err := json.Marshal(body) |
| + if err != nil { |
| + return nil, err |
| + } |
| + response.Body = io.NopCloser(strings.NewReader(string(raw))) |
| + return response, nil |
| + }) |
| +} |
| +func TestAppResponseGuards(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, path string |
| + change func(map[string]any) |
| + stage string |
| + }{ |
| + {"app id", "/app", func(v map[string]any) { v["id"] = 999 }, "app"}, |
| + {"account id", "/app", func(v map[string]any) { v["owner"].(map[string]any)["id"] = 999 }, "app"}, |
| + {"account type", "/app", func(v map[string]any) { v["owner"].(map[string]any)["type"] = "User" }, "app"}, |
| + {"app slug", "/app", func(v map[string]any) { v["slug"] = "../different" }, "app"}, |
| + {"permissions", "/app", func(v map[string]any) { v["permissions"].(map[string]any)["workflows"] = "write" }, "app"}, |
| + {"missing events", "/app", func(v map[string]any) { delete(v, "events") }, "app"}, |
| + {"missing count", "/installation/repositories", func(v map[string]any) { delete(v, "total_count"); v["repositories"] = []any{} }, "token"}, |
| + {"missing rows", "/installation/repositories", func(v map[string]any) { delete(v, "repositories"); v["total_count"] = 0 }, "token"}, |
| + {"events", "/app", func(v map[string]any) { v["events"] = []string{"push"} }, "app"}, |
| + {"installation id", "/app/installations/303", func(v map[string]any) { v["id"] = 999 }, "installation"}, |
| + {"installation app", "/app/installations/303", func(v map[string]any) { v["app_id"] = 999 }, "installation"}, |
| + {"installation account", "/app/installations/303", func(v map[string]any) { v["account"].(map[string]any)["id"] = 999 }, "installation"}, |
| + {"installation type", "/app/installations/303", func(v map[string]any) { v["account"].(map[string]any)["type"] = "User" }, "installation"}, |
| + {"installation permissions", "/app/installations/303", func(v map[string]any) { v["permissions"].(map[string]any)["contents"] = "read" }, "installation"}, |
| + {"installation events", "/app/installations/303", func(v map[string]any) { v["events"] = []string{"push"} }, "installation"}, |
| + {"selection", "/app/installations/303", func(v map[string]any) { v["repository_selection"] = "unknown" }, "installation"}, |
| + {"token permissions", "/app/installations/303/access_tokens", func(v map[string]any) { v["permissions"].(map[string]any)["contents"] = "write" }, "token"}, |
| + {"token missing permissions", "/app/installations/303/access_tokens", func(v map[string]any) { delete(v, "permissions") }, "token"}, |
| + {"token expired", "/app/installations/303/access_tokens", func(v map[string]any) { v["expires_at"] = time.Now().Add(-time.Minute) }, "token"}, |
| + {"token long expiry", "/app/installations/303/access_tokens", func(v map[string]any) { v["expires_at"] = time.Now().Add(2 * time.Hour) }, "token"}, |
| + {"token selection", "/app/installations/303/access_tokens", func(v map[string]any) { v["repository_selection"] = "all" }, "token"}, |
| + {"repository account", "/installation/repositories", func(v map[string]any) { |
| + v["repositories"].([]any)[0].(map[string]any)["owner"].(map[string]any)["id"] = 999 |
| + }, "token"}, |
| + {"duplicate repository", "/installation/repositories", func(v map[string]any) { rows := v["repositories"].([]any); rows[1] = rows[0] }, "token"}, |
| + {"partial inventory", "/installation/repositories", func(v map[string]any) { v["total_count"] = 3 }, "token"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + g := forgetest.NewGitHub(t) |
| + api := NewAPI(alter(g, tc.path, tc.change), func() time.Time { return g.Now }) |
| + app, err := api.Convert(context.Background(), g.Code) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + switch tc.stage { |
| + case "app": |
| + _, err = api.Verify(context.Background(), app) |
| + case "installation": |
| + _, err = api.Installation(context.Background(), app, g.InstallationID) |
| + case "token": |
| + inst, e := api.Installation(context.Background(), app, g.InstallationID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + var got Inventory |
| + got, err = api.Inventory(context.Background(), app, inst) |
| + if len(got.Repositories) != 0 { |
| + t.Fatal("partial or unsafe inventory published") |
| + } |
| + } |
| + if err == nil { |
| + t.Fatal("unsafe API answer accepted") |
| + } |
| + }) |
| + } |
| +} |
| +func TestAppRedirectAndDeadline(t *testing.T) { |
| + g := forgetest.NewGitHub(t) |
| + var calls int |
| + base := g.Transport() |
| + api := NewAPI(transportFunc(func(r *http.Request) (*http.Response, error) { |
| + calls++ |
| + if calls > 1 { |
| + return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("{}")), Request: r}, nil |
| + } |
| + return &http.Response{StatusCode: 302, Header: http.Header{"Location": {"https://api.github.com/app"}}, Body: io.NopCloser(strings.NewReader("")), Request: r}, nil |
| + }), nil) |
| + if _, err := api.Convert(context.Background(), g.Code); err == nil || calls != 1 { |
| + t.Fatal("redirect followed") |
| + } |
| + api = NewAPI(base, nil) |
| + if api.client.Timeout <= 0 || api.client.Timeout > 10*time.Second { |
| + t.Fatal("unbounded deadline") |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + if _, err := api.Convert(ctx, g.Code); err == nil { |
| + t.Fatal("cancelled API call continued") |
| + } |
| +} |
| +func TestAppTokenLifetime(t *testing.T) { |
| + g := forgetest.NewGitHub(t) |
| + api := NewAPI(g.Transport(), func() time.Time { return g.Now }) |
| + ctx := context.Background() |
| + app, e := api.Convert(ctx, g.Code) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + inst, e := api.Installation(ctx, app, g.InstallationID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = api.Inventory(ctx, app, inst); e != nil { |
| + t.Fatal(e) |
| + } |
| + g.Now = g.Now.Add(time.Hour - 29*time.Second) |
| + if _, e = api.Inventory(ctx, app, inst); e != nil { |
| + t.Fatal(e) |
| + } |
| + if g.Calls("POST", fmt.Sprintf("/app/installations/%d/access_tokens", g.InstallationID)) != 2 { |
| + t.Fatal("expired token reused") |
| + } |
| + if g.Calls("DELETE", "/installation/token") != 1 { |
| + t.Fatal("old token not revoked") |
| + } |
| + inst.Suspended = &g.Now |
| + if _, e = api.Inventory(ctx, app, inst); !errors.Is(e, ErrAccess) { |
| + t.Fatal("suspended inventory admitted") |
| + } |
| +} |
| + |
| +func TestInventoryConditionalScope(t *testing.T) { |
| + g := forgetest.NewGitHub(t) |
| + base := g.Transport() |
| + var conditional int |
| + api := NewAPI(transportFunc(func(r *http.Request) (*http.Response, error) { |
| + if r.URL.Path == "/installation/repositories" && r.Header.Get("If-None-Match") != "" { |
| + conditional++ |
| + } |
| + return base.RoundTrip(r) |
| + }), func() time.Time { return g.Now }) |
| + ctx := context.Background() |
| + app, e := api.Convert(ctx, g.Code) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + inst, e := api.Installation(ctx, app, g.InstallationID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + for i := 0; i < 2; i++ { |
| + got, e := api.Inventory(ctx, app, inst) |
| + if e != nil || got.Count != 2 { |
| + t.Fatal("conditional inventory", e) |
| + } |
| + } |
| + if conditional != 1 { |
| + t.Fatal("ETag not revalidated") |
| + } |
| + app.generation++ |
| + if _, e = api.Inventory(ctx, app, inst); e != nil { |
| + t.Fatal(e) |
| + } |
| + if conditional != 1 { |
| + t.Fatal("ETag crossed connection generation") |
| + } |
| + api.Forget(ctx, app.ID) |
| + if _, e = api.Inventory(ctx, app, inst); e != nil { |
| + t.Fatal(e) |
| + } |
| + if conditional != 1 { |
| + t.Fatal("ETag crossed invalidation") |
| + } |
| +} |
| + |
| +func TestMetadataMemoryDeadline(t *testing.T) { |
| + r := storeRig(t) |
| + v := r.created(t) |
| + if _, e := r.s.Check(context.Background(), r.owner, v.ID); e != nil { |
| + t.Fatal(e) |
| + } |
| + r.advance(time.Hour - 29*time.Second) |
| + r.s.Maintain = func(tx *gorm.DB) error { var owners []testOwner; return tx.Find(&owners).Error } |
| + if e := r.s.Sweep(context.Background()); e != nil { |
| + t.Fatal(e) |
| + } |
| + r.s.API.mu.Lock() |
| + n := len(r.s.API.tokens) |
| + r.s.API.mu.Unlock() |
| + if n != 0 { |
| + t.Fatal("idle expired token retained in instance memory") |
| + } |
| + if r.g.Calls("DELETE", "/installation/token") != 1 { |
| + t.Fatal("idle expiring token not revoked") |
| + } |
| +} |
| + |
| +func TestMetadataCannotReadContentsAndRevocation(t *testing.T) { |
| + g := forgetest.NewGitHub(t) |
| + api := NewAPI(g.Transport(), func() time.Time { return g.Now }) |
| + ctx := context.Background() |
| + app, e := api.Convert(ctx, g.Code) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + inst, e := api.Installation(ctx, app, g.InstallationID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + token, e := api.metadata(ctx, app, inst) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = api.request(ctx, "GET", "/repos/"+g.Login+"/probe/contents/README.md", token, nil, nil); !errors.Is(e, ErrAccess) { |
| + t.Fatal("metadata token read contents") |
| + } |
| + api.Forget(ctx, app.ID) |
| + _, e = api.request(ctx, "GET", "/installation/repositories?per_page=100&page=1", token, nil, nil) |
| + var refusal *APIError |
| + if !errors.As(e, &refusal) || refusal.Status != 401 { |
| + t.Fatal("revoked token survived") |
| + } |
| +} |
| + |
| +type countingBody struct { |
| + reader *strings.Reader |
| + read int |
| +} |
| + |
| +func (b *countingBody) Read(p []byte) (int, error) { |
| + n, e := b.reader.Read(p) |
| + b.read += n |
| + return n, e |
| +} |
| +func (*countingBody) Close() error { return nil } |
| +func TestAppBodyBound(t *testing.T) { |
| + for _, size := range []int{maxAnswer + 1, maxAnswer + 4096} { |
| + t.Run(fmt.Sprint(size), func(t *testing.T) { |
| + body := &countingBody{reader: strings.NewReader(`{"ok":true}` + strings.Repeat(" ", size-len(`{"ok":true}`)))} |
| + api := NewAPI(transportFunc(func(req *http.Request) (*http.Response, error) { |
| + return &http.Response{StatusCode: 200, Header: http.Header{}, Body: body, Request: req}, nil |
| + }), nil) |
| + var out map[string]any |
| + if _, e := api.request(context.Background(), "GET", "/app", "", nil, &out); e == nil { |
| + t.Fatal("oversized valid JSON accepted") |
| + } |
| + if body.read > maxAnswer+1 { |
| + t.Fatal("API read beyond bounded body") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestAppCustomDefaultTransport(t *testing.T) { |
| + g := forgetest.NewGitHub(t) |
| + before := http.DefaultTransport |
| + http.DefaultTransport = g.Transport() |
| + defer func() { http.DefaultTransport = before }() |
| + api := NewAPI(nil, func() time.Time { return g.Now }) |
| + if _, e := api.Convert(context.Background(), g.Code); e != nil { |
| + t.Fatal("custom default transport ignored", e) |
| + } |
| +} |
diff --git a/internal/equipo/github/inventory_cache.go b/internal/equipo/github/inventory_cache.go| new file mode 100644 |
| index 00000000..a6b62b54 |
| --- /dev/null |
| +++ b/internal/equipo/github/inventory_cache.go |
| @@ -0,0 +1,61 @@ |
| +package github |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "time" |
| +) |
| + |
| +var errNotModified = errors.New("github: not modified") |
| + |
| +type inventoryReply struct { |
| + Total *int `json:"total_count"` |
| + Rows []Repository `json:"repositories"` |
| +} |
| +type inventoryPage struct { |
| + etag string |
| + reply inventoryReply |
| + headers http.Header |
| +} |
| + |
| +func (a *API) cachedPage(app App, token string, page int) inventoryPage { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + entry := a.tokens[app.ID] |
| + if entry.value != token || entry.generation != app.generation { |
| + return inventoryPage{} |
| + } |
| + return entry.pages[page] |
| +} |
| +func (a *API) cachePage(app App, token string, page int, value inventoryPage) { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + entry := a.tokens[app.ID] |
| + if entry.value != token { |
| + return |
| + } |
| + if entry.generation != app.generation { |
| + entry.generation = app.generation |
| + entry.pages = map[int]inventoryPage{} |
| + } |
| + entry.pages[page] = value |
| + a.tokens[app.ID] = entry |
| +} |
| + |
| +// Expire drops idle metadata credentials before expiry, even with the flag off. |
| +// The serving loop runs every 15 seconds; the margin is 30 seconds. |
| +func (a *API) Expire(ctx context.Context) { |
| + a.mu.Lock() |
| + var expired []string |
| + for id, entry := range a.tokens { |
| + if !a.now().Add(30 * time.Second).Before(entry.expires) { |
| + expired = append(expired, entry.value) |
| + delete(a.tokens, id) |
| + } |
| + } |
| + a.mu.Unlock() |
| + for _, value := range expired { |
| + _, _ = a.request(ctx, "DELETE", "/installation/token", value, nil, nil) |
| + } |
| +} |
diff --git a/internal/equipo/github/lifecycle_guards_test.go b/internal/equipo/github/lifecycle_guards_test.go| new file mode 100644 |
| index 00000000..e2c1affc |
| --- /dev/null |
| +++ b/internal/equipo/github/lifecycle_guards_test.go |
| @@ -0,0 +1,387 @@ |
| +package github |
| + |
| +import ( |
| + "amadan.net/rastrillo/rastrillo/gormlite" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "gorm.io/gorm/logger" |
| + "gorm.io/plugin/dbresolver" |
| + "net/http" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestForgeLateResults(t *testing.T) { |
| + for _, phase := range []string{"convert", "check"} { |
| + for _, action := range []string{"disconnect", "supersede", "remove owner"} { |
| + t.Run(phase+"/"+action, func(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + began, e := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + id := began.View.ID |
| + if phase == "check" { |
| + if _, e = r.s.Convert(ctx, r.owner, began.State, r.g.Code); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + base := r.g.Transport() |
| + r.s.API = NewAPI(transportFunc(func(req *http.Request) (*http.Response, error) { |
| + block := phase == "convert" && strings.Contains(req.URL.Path, "/conversions") || phase == "check" && req.URL.Path == "/installation/repositories" |
| + response, e := base.RoundTrip(req) |
| + if block { |
| + close(entered) |
| + <-release |
| + } |
| + return response, e |
| + }), func() time.Time { return r.now }) |
| + done := make(chan error, 1) |
| + go func() { |
| + if phase == "convert" { |
| + _, e := r.s.Convert(ctx, r.owner, began.State, r.g.Code) |
| + done <- e |
| + } else { |
| + _, e := r.s.Check(ctx, r.owner, id) |
| + done <- e |
| + } |
| + }() |
| + select { |
| + case <-entered: |
| + case <-time.After(5 * time.Second): |
| + close(release) |
| + t.Fatal("API did not enter") |
| + } |
| + // Another process uses the primary database, not an in-memory authority lock. |
| + other := *r.s |
| + other.API = NewAPI(r.g.Transport(), func() time.Time { return r.now }) |
| + switch action { |
| + case "disconnect": |
| + _, e = other.Disconnect(ctx, r.other, id) |
| + case "supersede": |
| + _, e = other.Start(ctx, r.other, "another-account", "Organization") |
| + case "remove owner": |
| + e = r.s.DB.Model(&testOwner{}).Where("address = ?", r.owner.Address).Update("active", false).Error |
| + } |
| + close(release) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = <-done; e == nil { |
| + t.Fatal("late result restored lost authority") |
| + } |
| + var c Connection |
| + if e = r.s.DB.First(&c, "id = ?", id).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if action != "remove owner" && c.SealedKey != "" { |
| + t.Fatal("late result restored key") |
| + } |
| + if c.Confirmed { |
| + t.Fatal("late result activated") |
| + } |
| + r.s.API.mu.Lock() |
| + n := len(r.s.API.tokens) |
| + r.s.API.mu.Unlock() |
| + if n != 0 { |
| + t.Fatal("late inventory retained a token") |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestForgeClaimAcrossProcesses(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + began, e := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + base := r.g.Transport() |
| + r.s.API = NewAPI(transportFunc(func(req *http.Request) (*http.Response, error) { |
| + if strings.Contains(req.URL.Path, "/conversions") { |
| + close(entered) |
| + <-release |
| + } |
| + return base.RoundTrip(req) |
| + }), func() time.Time { return r.now }) |
| + done := make(chan error, 1) |
| + go func() { _, e := r.s.Convert(ctx, r.owner, began.State, r.g.Code); done <- e }() |
| + <-entered |
| + other := *r.s |
| + other.API = NewAPI(r.g.Transport(), func() time.Time { return r.now }) |
| + if _, e = other.Convert(ctx, r.owner, began.State, r.g.Code); e == nil { |
| + close(release) |
| + t.Fatal("concurrent state reused") |
| + } |
| + close(release) |
| + if e = <-done; e != nil { |
| + t.Fatal(e) |
| + } |
| + if r.g.Calls("POST", "/app-manifests/"+r.g.Code+"/conversions") != 1 { |
| + t.Fatal("multiple conversions") |
| + } |
| +} |
| + |
| +func TestForgeRosterAndAuditGuards(t *testing.T) { |
| + for _, action := range []string{"start", "convert", "install", "check", "connect", "disconnect"} { |
| + for _, failure := range []string{"roster", "audit"} { |
| + t.Run(action+"/"+failure, func(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + began, e := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if action != "start" && action != "convert" { |
| + if _, e = r.s.Convert(ctx, r.owner, began.State, r.g.Code); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + var before Connection |
| + r.s.DB.First(&before, "id = ?", began.View.ID) |
| + if failure == "roster" { |
| + r.s.DB.Model(&testOwner{}).Where("address = ?", r.owner.Address).Update("active", false) |
| + } else { |
| + r.s.Audit = func(*gorm.DB, string, string, string) error { return errors.New("audit refused") } |
| + } |
| + switch action { |
| + case "start": |
| + _, e = r.s.Start(ctx, r.owner, "next-account", "Organization") |
| + case "convert": |
| + _, e = r.s.Convert(ctx, r.owner, began.State, r.g.Code) |
| + case "install": |
| + _, e = r.s.Install(ctx, r.owner, r.s.state(before, "installation")) |
| + case "check": |
| + _, e = r.s.Check(ctx, r.owner, began.View.ID) |
| + case "connect": |
| + _, e = r.s.Connect(ctx, r.owner, began.View.ID) |
| + case "disconnect": |
| + _, e = r.s.Disconnect(ctx, r.owner, began.View.ID) |
| + } |
| + if e == nil { |
| + t.Fatal("forbidden write accepted") |
| + } |
| + var after Connection |
| + r.s.DB.First(&after, "id = ?", began.View.ID) |
| + if before != after { |
| + t.Fatal("refused transaction changed connection") |
| + } |
| + }) |
| + } |
| + } |
| +} |
| +func TestForgeUnreadableKey(t *testing.T) { |
| + for _, mode := range []string{"root", "ciphertext"} { |
| + t.Run(mode, func(t *testing.T) { |
| + r := storeRig(t) |
| + v := r.created(t) |
| + if mode == "root" { |
| + r.s.Root = "new-instance-key" |
| + } else { |
| + r.s.DB.Model(&Connection{}).Where("id = ?", v.ID).Update("sealed_key", "corrupt") |
| + } |
| + got, e := r.s.Check(context.Background(), r.other, v.ID) |
| + if !errors.Is(e, ErrReconnect) || got.State != "reconnect" || got.SettingsURL == "" { |
| + t.Fatal("unreadable key not reconnect", e) |
| + } |
| + var c Connection |
| + r.s.DB.First(&c, "id = ?", v.ID) |
| + if c.SealedKey != "" { |
| + t.Fatal("unreadable key retained") |
| + } |
| + }) |
| + } |
| +} |
| +func TestForgeRecheckSuspensionAndRateLimit(t *testing.T) { |
| + r := storeRig(t) |
| + v := r.created(t) |
| + ctx := context.Background() |
| + r.g.Suspended = true |
| + got, e := r.s.Connect(ctx, r.owner, v.ID) |
| + if e == nil || got.Confirmed || got.State != "suspended" { |
| + t.Fatal("suspended Connect admitted") |
| + } |
| + r.g.Suspended = false |
| + if _, e = r.s.Connect(ctx, r.owner, v.ID); e != nil { |
| + t.Fatal(e) |
| + } |
| + r.g.FailPath = "/app/installations" |
| + r.g.FailStatus = 403 |
| + r.g.FailHeaders = http.Header{"X-Ratelimit-Remaining": {"0"}} |
| + got, e = r.s.Check(ctx, r.owner, v.ID) |
| + if !errors.Is(e, ErrRateLimit) || got.State != "check_failed" { |
| + t.Fatal("rate limit became lost access") |
| + } |
| + var c Connection |
| + r.s.DB.First(&c, "id = ?", v.ID) |
| + if c.SealedKey == "" || !c.UninstalledAt.IsZero() || c.ActiveAccount == nil { |
| + t.Fatal("rate limit revoked connection") |
| + } |
| +} |
| + |
| +func TestForgeConversionVerification(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + began, e := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + r.g.FailPath = "/app" |
| + r.g.FailStatus = 403 |
| + got, e := r.s.Convert(ctx, r.owner, began.State, r.g.Code) |
| + if e == nil || got.State != "failed" { |
| + t.Fatal("conversion activated without verified App") |
| + } |
| + var c Connection |
| + r.s.DB.First(&c, "id = ?", began.View.ID) |
| + if c.SealedKey != "" { |
| + t.Fatal("failed verification retained key") |
| + } |
| +} |
| + |
| +func TestForgeUniqueAppAndNewNames(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + first, e := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + second, e := r.s.Start(ctx, r.other, r.g.Login, r.g.AccountType) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if first.Name == second.Name || first.State == second.State { |
| + t.Fatal("reconnect reused App name or state") |
| + } |
| + account := r.g.AccountID |
| + if e = r.s.DB.Create(&Connection{ID: "live-a", ActiveAccount: &account}).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = r.s.DB.Create(&Connection{ID: "live-b", ActiveAccount: &account}).Error; e == nil { |
| + t.Fatal("duplicate active account admitted") |
| + } |
| +} |
| + |
| +func TestForgeOwnerBindingIndependentOfSession(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + began, e := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + p := r.other |
| + p.Session = r.owner.Session |
| + if _, e = r.s.Convert(ctx, p, began.State, r.g.Code); e == nil { |
| + t.Fatal("callback owner binding omitted") |
| + } |
| + if r.g.Calls("POST", "/app-manifests/"+r.g.Code+"/conversions") != 0 { |
| + t.Fatal("wrong owner consumed code") |
| + } |
| +} |
| +func TestForgeFlagBeforeTransaction(t *testing.T) { |
| + r := storeRig(t) |
| + r.s.Enabled = false |
| + called := false |
| + write := r.s.Write |
| + r.s.Write = func(ctx context.Context, fn func(*gorm.DB) error) error { called = true; return write(ctx, fn) } |
| + if _, e := r.s.Start(context.Background(), r.owner, r.g.Login, r.g.AccountType); e == nil || called { |
| + t.Fatal("disabled Start entered a write") |
| + } |
| +} |
| +func TestForgeConversionGeneration(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + began, e := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + base := r.g.Transport() |
| + r.s.API = NewAPI(transportFunc(func(req *http.Request) (*http.Response, error) { |
| + response, e := base.RoundTrip(req) |
| + if strings.Contains(req.URL.Path, "/conversions") { |
| + if err := r.s.DB.Model(&Connection{}).Where("id = ?", began.View.ID).Update("generation", gorm.Expr("generation + 1")).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return response, e |
| + }), func() time.Time { return r.now }) |
| + if _, e = r.s.Convert(ctx, r.owner, began.State, r.g.Code); e == nil { |
| + t.Fatal("conversion ignored generation fence") |
| + } |
| +} |
| + |
| +func TestForgeAccountAndStageBinding(t *testing.T) { |
| + for _, change := range []string{"login", "type", "stage"} { |
| + t.Run(change, func(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + began, e := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + switch change { |
| + case "login": |
| + r.g.Login = "different-account" |
| + case "type": |
| + r.g.AccountType = "User" |
| + case "stage": |
| + if _, e = r.s.Install(ctx, r.owner, began.State); e == nil { |
| + t.Fatal("manifest state used for installation") |
| + } |
| + return |
| + } |
| + v, e := r.s.Convert(ctx, r.owner, began.State, r.g.Code) |
| + if e == nil || v.State != "failed" { |
| + t.Fatal("wrong intended account accepted") |
| + } |
| + }) |
| + } |
| +} |
| +func TestForgeReadsUsePrimary(t *testing.T) { |
| + r := storeRig(t) |
| + v := r.created(t) |
| + writer, e := r.s.DB.DB() |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + replica, e := sql.Open("sqlite", filepath.Join(t.TempDir(), "empty-replica.db")) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer replica.Close() |
| + g, e := gorm.Open(gormlite.Dialector{Conn: writer}, &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = g.Use(dbresolver.Register(dbresolver.Config{Replicas: []gorm.Dialector{gormlite.Dialector{Conn: replica}}})); e != nil { |
| + t.Fatal(e) |
| + } |
| + r.s.DB = g |
| + rows, e := r.s.List(context.Background(), r.other) |
| + if e != nil || len(rows) != 1 { |
| + t.Fatal("owner read hit stale replica", e) |
| + } |
| + if _, e = r.s.InstallationURL(context.Background(), r.owner, v.ID); e != nil { |
| + t.Fatal("installation redirect hit replica", e) |
| + } |
| +} |
| + |
| +func TestForgeSameAppRename(t *testing.T) { |
| + r := storeRig(t) |
| + v := r.created(t) |
| + r.s.API = NewAPI(alter(r.g, "/app", func(body map[string]any) { body["slug"] = "renamed-app" }), func() time.Time { return r.now }) |
| + got, e := r.s.Check(context.Background(), r.other, v.ID) |
| + if e != nil || got.State != "ready" || !strings.HasSuffix(got.SettingsURL, "/renamed-app") { |
| + t.Fatal("same numeric App identity lost after rename", e) |
| + } |
| +} |
diff --git a/internal/equipo/github/models.go b/internal/equipo/github/models.go| new file mode 100644 |
| index 00000000..e217b7bd |
| --- /dev/null |
| +++ b/internal/equipo/github/models.go |
| @@ -0,0 +1,61 @@ |
| +package github |
| + |
| +import "time" |
| + |
| +// Connection is a team forge connection, never a person's model connection. |
| +// Only View is exposed to a browser or a device. |
| +type Connection struct { |
| + ID string `gorm:"primaryKey"` |
| + Generation int64 |
| + State string |
| + Login string |
| + AccountType string |
| + AccountID int64 |
| + AppID int64 |
| + Slug string |
| + AppName string |
| + InstallationID int64 |
| + Selection string |
| + Confirmed bool |
| + ActiveAccount *int64 `gorm:"uniqueIndex:forge_active_account"` |
| + SealedKey string `json:"-"` |
| + Owner string `json:"-"` |
| + Session string `json:"-"` |
| + Origin string |
| + ManifestHash string `json:"-"` |
| + InstallationHash string `json:"-"` |
| + StartedAt time.Time |
| + RedirectUntil time.Time |
| + PendingUntil time.Time |
| + UninstalledAt time.Time |
| + Count int |
| + CountKnown bool |
| + Claim string `json:"-"` |
| + ClaimUntil time.Time |
| + UpdatedAt time.Time |
| +} |
| + |
| +func (Connection) TableName() string { return "forge_connections" } |
| + |
| +// Pending has one row per team instance. Start replaces its connection atomically. |
| +type Pending struct { |
| + ID int64 `gorm:"primaryKey;autoIncrement:false"` |
| + ConnectionID string |
| +} |
| + |
| +func (Pending) TableName() string { return "forge_pending" } |
| + |
| +var Models = []any{&Connection{}, &Pending{}} |
| + |
| +type Principal struct{ Address, Session string } |
| +type View struct { |
| + ID, State, Login, AccountType, Slug, SettingsURL string |
| + Generation, AppID, AccountID, InstallationID int64 |
| + Count int |
| + CountKnown, Confirmed bool |
| +} |
| +type Started struct { |
| + View View |
| + State, Name string |
| + Superseded *View |
| +} |
diff --git a/internal/equipo/github/seal.go b/internal/equipo/github/seal.go| new file mode 100644 |
| index 00000000..1b51c08a |
| --- /dev/null |
| +++ b/internal/equipo/github/seal.go |
| @@ -0,0 +1,53 @@ |
| +package github |
| + |
| +import ( |
| + "crypto/aes" |
| + "crypto/cipher" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| +) |
| + |
| +var ErrReconnect = errors.New("github: reconnect required") |
| + |
| +func appCipher(root string) (cipher.AEAD, error) { |
| + block, err := aes.NewCipher(kernel.PurposeKey(root, "forge-github-app-key")) |
| + if err != nil { |
| + return nil, ErrUnavailable |
| + } |
| + return cipher.NewGCM(block) |
| +} |
| +func appBinding(origin, id string, appID int64) []byte { |
| + raw, _ := json.Marshal([]any{"github-app-key-v1", origin, id, appID}) |
| + return raw |
| +} |
| +func sealKey(root, origin, id string, appID int64, key string) (string, error) { |
| + box, err := appCipher(root) |
| + if err != nil { |
| + return "", err |
| + } |
| + nonce := make([]byte, box.NonceSize()) |
| + if _, err = rand.Read(nonce); err != nil { |
| + return "", ErrUnavailable |
| + } |
| + sealed := box.Seal(nonce, nonce, []byte(key), appBinding(origin, id, appID)) |
| + return base64.RawURLEncoding.EncodeToString(sealed), nil |
| +} |
| +func openKey(root, origin, id string, appID int64, sealed string) (string, error) { |
| + box, err := appCipher(root) |
| + if err != nil { |
| + return "", ErrReconnect |
| + } |
| + raw, err := base64.RawURLEncoding.DecodeString(sealed) |
| + if err != nil || len(raw) < box.NonceSize()+box.Overhead() { |
| + return "", ErrReconnect |
| + } |
| + plain, err := box.Open(nil, raw[:box.NonceSize()], raw[box.NonceSize():], appBinding(origin, id, appID)) |
| + if err != nil { |
| + return "", ErrReconnect |
| + } |
| + return string(plain), nil |
| +} |
diff --git a/internal/equipo/github/seal_test.go b/internal/equipo/github/seal_test.go| new file mode 100644 |
| index 00000000..bab7da56 |
| --- /dev/null |
| +++ b/internal/equipo/github/seal_test.go |
| @@ -0,0 +1,60 @@ |
| +package github |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "crypto/aes" |
| + "crypto/cipher" |
| + "encoding/base64" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestAppKeySealing(t *testing.T) { |
| + secret := "generated key material for this test" |
| + sealed, err := sealKey("instance-key", "https://equipo.example", "connection-one", 101, secret) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(sealed, secret) { |
| + t.Fatal("key persisted in plaintext") |
| + } |
| + raw, _ := base64.RawURLEncoding.DecodeString(sealed) |
| + if strings.Contains(string(raw), secret) { |
| + t.Fatal("key merely encoded") |
| + } |
| + opened, err := openKey("instance-key", "https://equipo.example", "connection-one", 101, sealed) |
| + if err != nil || opened != secret { |
| + t.Fatal("sealed key cannot be opened") |
| + } |
| + for _, tc := range []struct { |
| + name, root, origin, id string |
| + app int64 |
| + }{ |
| + {"root", "other-key", "https://equipo.example", "connection-one", 101}, |
| + {"origin", "instance-key", "https://other.example", "connection-one", 101}, |
| + {"connection", "instance-key", "https://equipo.example", "connection-two", 101}, |
| + {"app", "instance-key", "https://equipo.example", "connection-one", 102}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + got, err := openKey(tc.root, tc.origin, tc.id, tc.app, sealed) |
| + if err == nil || got != "" { |
| + t.Fatal("key opened with the wrong binding") |
| + } |
| + }) |
| + } |
| + for _, purpose := range []string{"person-device-results", "person-api-cursor"} { |
| + block, _ := aes.NewCipher(kernel.PurposeKey("instance-key", purpose)) |
| + box, _ := cipher.NewGCM(block) |
| + if _, err := box.Open(nil, raw[:box.NonceSize()], raw[box.NonceSize():], appBinding("https://equipo.example", "connection-one", 101)); err == nil { |
| + t.Fatal("App key shares a credential purpose") |
| + } |
| + } |
| + raw[len(raw)-1] ^= 1 |
| + if got, err := openKey("instance-key", "https://equipo.example", "connection-one", 101, base64.RawURLEncoding.EncodeToString(raw)); err == nil || got != "" { |
| + t.Fatal("corrupt ciphertext accepted") |
| + } |
| + second, err := sealKey("instance-key", "https://equipo.example", "connection-one", 101, secret) |
| + if err != nil || sealed == second { |
| + t.Fatal("nonce was reused") |
| + } |
| +} |
diff --git a/internal/equipo/github/store.go b/internal/equipo/github/store.go| new file mode 100644 |
| index 00000000..8016eca0 |
| --- /dev/null |
| +++ b/internal/equipo/github/store.go |
| @@ -0,0 +1,244 @@ |
| +package github |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "errors" |
| + "net/url" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "gorm.io/gorm" |
| + "gorm.io/plugin/dbresolver" |
| +) |
| + |
| +type Store struct { |
| + Maintain func(*gorm.DB) error |
| + DB *gorm.DB |
| + Write func(context.Context, func(*gorm.DB) error) error |
| + Owner func(*gorm.DB, string) error |
| + Audit func(*gorm.DB, string, string, string) error |
| + Now func() time.Time |
| + API *API |
| + Root, Origin string |
| + Enabled bool |
| +} |
| + |
| +// Refusal carries a public lifecycle state without an upstream body or URL. |
| +type Refusal struct { |
| + View View |
| + Cause error |
| +} |
| + |
| +func (e *Refusal) Error() string { return e.Cause.Error() } |
| +func (e *Refusal) Unwrap() error { return e.Cause } |
| +func (s *Store) now() time.Time { |
| + if s.Now != nil { |
| + return s.Now().UTC() |
| + } |
| + return time.Now().UTC() |
| +} |
| +func (s *Store) write(ctx context.Context, p Principal, fn func(*gorm.DB) error) error { |
| + if !s.Enabled || s.Write == nil || s.Owner == nil || s.Audit == nil || p.Address == "" || p.Session == "" { |
| + return ErrAccess |
| + } |
| + return s.Write(ctx, func(tx *gorm.DB) error { |
| + if !s.Enabled { |
| + return ErrAccess |
| + } |
| + if err := s.Owner(tx, p.Address); err != nil { |
| + return err |
| + } |
| + return fn(tx) |
| + }) |
| +} |
| +func (s *Store) primary(ctx context.Context) *gorm.DB { |
| + return s.DB.WithContext(ctx).Clauses(dbresolver.Write).Session(&gorm.Session{}) |
| +} |
| +func (s *Store) save(tx *gorm.DB, p Principal, c *Connection, kind string) error { |
| + c.Generation++ |
| + c.UpdatedAt = s.now() |
| + fields := []string{"Generation", "State", "Login", "AccountType", "AccountID", "AppID", "Slug", "AppName", "InstallationID", "Selection", "Confirmed", "ActiveAccount", "SealedKey", "Owner", "Session", "Origin", "ManifestHash", "InstallationHash", "StartedAt", "RedirectUntil", "PendingUntil", "UninstalledAt", "Count", "CountKnown", "Claim", "ClaimUntil", "UpdatedAt"} |
| + if err := tx.Model(&Connection{}).Where("id = ?", c.ID).Select(fields).Updates(c).Error; err != nil { |
| + return err |
| + } |
| + return s.Audit(tx, p.Address, kind, c.ID) |
| +} |
| +func digest(raw string) string { sum := sha256.Sum256([]byte(raw)); return hex.EncodeToString(sum[:]) } |
| +func (s *Store) state(c Connection, stage string) string { |
| + mac := hmac.New(sha256.New, kernel.PurposeKey(s.Root, "forge-github-redirect-state")) |
| + for _, value := range []string{c.ID, stage, c.Owner, c.Session, c.Origin} { |
| + mac.Write([]byte(value)) |
| + mac.Write([]byte{0}) |
| + } |
| + return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) |
| +} |
| +func (s *Store) view(c Connection) View { |
| + settings := "https://github.com/settings/apps" |
| + if c.AccountType == "Organization" { |
| + settings = "https://github.com/organizations/" + url.PathEscape(c.Login) + "/settings/apps" |
| + } |
| + if c.Slug != "" { |
| + settings += "/" + url.PathEscape(c.Slug) |
| + } |
| + return View{ID: c.ID, State: c.State, Login: c.Login, AccountType: c.AccountType, Slug: c.Slug, SettingsURL: settings, Generation: c.Generation, AppID: c.AppID, AccountID: c.AccountID, InstallationID: c.InstallationID, Count: c.Count, CountKnown: c.CountKnown, Confirmed: c.Confirmed} |
| +} |
| +func erase(c *Connection, state string) { |
| + c.SealedKey = "" |
| + c.ManifestHash = "" |
| + c.InstallationHash = "" |
| + c.Claim = "" |
| + c.ClaimUntil = time.Time{} |
| + c.ActiveAccount = nil |
| + c.CountKnown = false |
| + c.State = state |
| +} |
| +func (s *Store) Start(ctx context.Context, p Principal, login, kind string) (Started, error) { |
| + login = strings.ToLower(strings.TrimSpace(login)) |
| + if !ValidAccount(login, kind) { |
| + return Started{}, ErrAccess |
| + } |
| + var result Started |
| + var forgotten int64 |
| + err := s.write(ctx, p, func(tx *gorm.DB) error { |
| + var active Connection |
| + err := tx.Where("LOWER(login) = ? AND account_type = ? AND active_account IS NOT NULL", login, kind).First(&active).Error |
| + if err == nil { |
| + result.View = s.view(active) |
| + result.View.State = "already_connected" |
| + return nil |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return err |
| + } |
| + var slot Pending |
| + err = tx.First(&slot, "id = ?", 1).Error |
| + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return err |
| + } |
| + if slot.ConnectionID != "" { |
| + var old Connection |
| + if err = tx.First(&old, "id = ?", slot.ConnectionID).Error; err != nil { |
| + return err |
| + } |
| + prior := s.view(old) |
| + result.Superseded = &prior |
| + forgotten = old.AppID |
| + erase(&old, "superseded") |
| + if err = s.save(tx, p, &old, "forge.supersede"); err != nil { |
| + return err |
| + } |
| + } |
| + now := s.now() |
| + c := Connection{ID: strings.ToLower(rand.Text()), Generation: 1, State: "manifest", Login: login, AccountType: kind, AppName: "equipo-" + strings.ToLower(rand.Text()[:12]), Owner: p.Address, Session: digest(p.Session), Origin: s.Origin, StartedAt: now, RedirectUntil: now.Add(10 * time.Minute), UpdatedAt: now} |
| + raw := s.state(c, "manifest") |
| + c.ManifestHash = digest(raw) |
| + if err = tx.Create(&c).Error; err != nil { |
| + return err |
| + } |
| + if slot.ID == 0 { |
| + err = tx.Create(&Pending{1, c.ID}).Error |
| + } else { |
| + err = tx.Model(&Pending{}).Where("id = ?", 1).Select("ConnectionID").Updates(&Pending{ConnectionID: c.ID}).Error |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if err = s.Audit(tx, p.Address, "forge.start", c.ID); err != nil { |
| + return err |
| + } |
| + result.View, result.State, result.Name = s.view(c), raw, c.AppName |
| + return nil |
| + }) |
| + if err == nil && forgotten != 0 { |
| + s.API.Forget(ctx, forgotten) |
| + } |
| + return result, err |
| +} |
| +func (s *Store) List(ctx context.Context, p Principal) ([]View, error) { |
| + if !s.Enabled { |
| + return nil, ErrAccess |
| + } |
| + tx := s.primary(ctx) |
| + if err := s.Owner(tx, p.Address); err != nil { |
| + return nil, err |
| + } |
| + var records []Connection |
| + if err := tx.Order("started_at DESC").Find(&records).Error; err != nil { |
| + return nil, err |
| + } |
| + views := make([]View, 0, len(records)) |
| + for _, record := range records { |
| + views = append(views, s.view(record)) |
| + } |
| + return views, nil |
| +} |
| +func (s *Store) Disconnect(ctx context.Context, p Principal, id string) (View, error) { |
| + var c Connection |
| + err := s.write(ctx, p, func(tx *gorm.DB) error { |
| + if err := tx.First(&c, "id = ?", id).Error; err != nil { |
| + return err |
| + } |
| + erase(&c, "disconnected") |
| + if err := s.save(tx, p, &c, "forge.disconnect"); err != nil { |
| + return err |
| + } |
| + return tx.Where("connection_id = ?", id).Delete(&Pending{}).Error |
| + }) |
| + if err == nil { |
| + s.API.Forget(ctx, c.AppID) |
| + } |
| + return s.view(c), err |
| +} |
| +func (s *Store) app(c Connection) (App, error) { |
| + key, err := openKey(s.Root, s.Origin, c.ID, c.AppID, c.SealedKey) |
| + if err != nil { |
| + return App{}, err |
| + } |
| + return App{ID: c.AppID, Slug: c.Slug, Owner: Account{c.AccountID, c.Login, c.AccountType}, Permissions: permissions(), Events: []string{}, pem: key, generation: c.Generation}, nil |
| +} |
| + |
| +// Sweep erases expired keys even while the feature is disabled. Maintain checks |
| +// the current roster as a system cleanup, without impersonating a removed owner. |
| +func (s *Store) Sweep(ctx context.Context) error { |
| + s.API.Expire(ctx) |
| + if s.Write == nil || s.Maintain == nil { |
| + return ErrAccess |
| + } |
| + var forget []int64 |
| + err := s.Write(ctx, func(tx *gorm.DB) error { |
| + if err := s.Maintain(tx); err != nil { |
| + return err |
| + } |
| + var rows []Connection |
| + if err := tx.Where("sealed_key <> ?", "").Find(&rows).Error; err != nil { |
| + return err |
| + } |
| + for _, c := range rows { |
| + state := s.expired(c) |
| + if state == "" { |
| + continue |
| + } |
| + forget = append(forget, c.AppID) |
| + erase(&c, state) |
| + if err := s.save(tx, Principal{}, &c, "forge.expire"); err != nil { |
| + return err |
| + } |
| + if err := tx.Where("connection_id = ?", c.ID).Delete(&Pending{}).Error; err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| + }) |
| + if err == nil { |
| + for _, id := range forget { |
| + s.API.Forget(ctx, id) |
| + } |
| + } |
| + return err |
| +} |
diff --git a/internal/equipo/github/store_test.go b/internal/equipo/github/store_test.go| new file mode 100644 |
| index 00000000..7ad08b81 |
| --- /dev/null |
| +++ b/internal/equipo/github/store_test.go |
| @@ -0,0 +1,405 @@ |
| +package github |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/forge/forgetest" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "gorm.io/gorm" |
| + "gorm.io/plugin/dbresolver" |
| +) |
| + |
| +type testOwner struct { |
| + Address string `gorm:"primaryKey"` |
| + Active bool |
| +} |
| +type testAudit struct { |
| + ID int64 |
| + Person, Kind, Record string |
| +} |
| +type rig struct { |
| + s *Store |
| + g *forgetest.GitHub |
| + now time.Time |
| + owner, other Principal |
| +} |
| + |
| +func storeRig(t *testing.T) *rig { |
| + t.Helper() |
| + d, err := db.Open(filepath.Join(t.TempDir(), "github.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + if err = d.G.AutoMigrate(&Connection{}, &Pending{}, &testOwner{}, &testAudit{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, a := range []string{"owner@example.test", "other@example.test"} { |
| + if err = d.G.Create(&testOwner{a, true}).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + r := &rig{g: forgetest.NewGitHub(t), now: time.Now().UTC(), owner: Principal{"owner@example.test", "first-session"}, other: Principal{"other@example.test", "second-session"}} |
| + r.g.Now = r.now |
| + r.s = &Store{DB: d.G, Root: "test-instance-key", Origin: "https://equipo.example", Enabled: true, Now: func() time.Time { return r.now }} |
| + r.s.API = NewAPI(r.g.Transport(), func() time.Time { return r.now }) |
| + r.s.Write = func(ctx context.Context, fn func(*gorm.DB) error) error { |
| + return d.G.WithContext(ctx).Clauses(dbresolver.Write).Transaction(fn) |
| + } |
| + r.s.Owner = func(tx *gorm.DB, person string) error { |
| + var owner testOwner |
| + if tx.Where("address = ? AND active = ?", person, true).First(&owner).Error != nil { |
| + return ErrAccess |
| + } |
| + return nil |
| + } |
| + r.s.Audit = func(tx *gorm.DB, person, kind, id string) error { |
| + return tx.Create(&testAudit{Person: person, Kind: kind, Record: id}).Error |
| + } |
| + return r |
| +} |
| +func (r *rig) created(t *testing.T) View { |
| + t.Helper() |
| + began, err := r.s.Start(context.Background(), r.owner, r.g.Login, r.g.AccountType) |
| + if err != nil { |
| + t.Fatal("start:", err) |
| + } |
| + view, err := r.s.Convert(context.Background(), r.owner, began.State, r.g.Code) |
| + if err != nil { |
| + t.Fatal("convert:", err) |
| + } |
| + if view.AppID != r.g.AppID { |
| + t.Fatal("converted wrong App") |
| + } |
| + return view |
| +} |
| +func TestForgeConnectionLifecycle(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + view := r.created(t) |
| + var stored Connection |
| + if err := r.s.DB.First(&stored, "id = ?", view.ID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if stored.SealedKey == "" || strings.Contains(stored.SealedKey, r.g.PEM) || stored.ManifestHash != "" { |
| + t.Fatal("key not sealed or callback state not consumed") |
| + } |
| + key, err := openKey(r.s.Root, r.s.Origin, view.ID, r.g.AppID, stored.SealedKey) |
| + if err != nil || key != r.g.PEM { |
| + t.Fatal("sealed wrong key") |
| + } |
| + checked, err := r.s.Check(ctx, r.other, view.ID) |
| + if err != nil || checked.State != "ready" || checked.Count != 2 || !checked.CountKnown { |
| + t.Fatal("other owner check:", err, checked) |
| + } |
| + live, err := r.s.Connect(ctx, r.other, view.ID) |
| + if err != nil || live.State != "live" || !live.Confirmed { |
| + t.Fatal("other owner connect:", err, live) |
| + } |
| + down, err := r.s.Disconnect(ctx, r.owner, view.ID) |
| + if err != nil || down.State != "disconnected" { |
| + t.Fatal("disconnect:", err) |
| + } |
| + if err := r.s.DB.First(&stored, "id = ?", view.ID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if stored.SealedKey != "" || stored.ActiveAccount != nil || stored.Generation <= live.Generation { |
| + t.Fatal("disconnect retained authority") |
| + } |
| + var audits []testAudit |
| + r.s.DB.Find(&audits) |
| + for _, kind := range []string{"forge.start", "forge.convert", "forge.check", "forge.connect", "forge.disconnect"} { |
| + found := false |
| + for _, row := range audits { |
| + found = found || row.Kind == kind |
| + } |
| + if !found { |
| + t.Error("missing audit", kind) |
| + } |
| + } |
| +} |
| +func TestForgeStartSinglePending(t *testing.T) { |
| + r := storeRig(t) |
| + old := r.created(t) |
| + next, err := r.s.Start(context.Background(), r.other, "another-org", "Organization") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if next.Superseded == nil || next.Superseded.ID != old.ID { |
| + t.Fatal("old App cleanup not shown") |
| + } |
| + var record Connection |
| + r.s.DB.First(&record, "id = ?", old.ID) |
| + if record.SealedKey != "" || record.State != "superseded" { |
| + t.Fatal("superseded App key retained") |
| + } |
| + var pending []Pending |
| + r.s.DB.Find(&pending) |
| + if len(pending) != 1 || pending[0].ConnectionID != next.View.ID { |
| + t.Fatal("more than one pending setup") |
| + } |
| + var rows []testAudit |
| + r.s.DB.Where("kind = ?", "forge.supersede").Find(&rows) |
| + if len(rows) != 1 { |
| + t.Fatal("replacement not audited") |
| + } |
| +} |
| +func TestForgeCallbacksBound(t *testing.T) { |
| + for _, change := range []string{"owner", "session", "origin", "expired", "replay", "roster"} { |
| + t.Run(change, func(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + began, err := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + who := r.owner |
| + switch change { |
| + case "owner": |
| + who = r.other |
| + case "session": |
| + who.Session = "new-session" |
| + case "origin": |
| + r.s.Origin = "https://other.example" |
| + case "expired": |
| + r.now = r.now.Add(10 * time.Minute) |
| + case "replay": |
| + if _, err = r.s.Convert(ctx, who, began.State, r.g.Code); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "roster": |
| + r.s.DB.Model(&testOwner{}).Where("address = ?", who.Address).Update("active", false) |
| + } |
| + _, err = r.s.Convert(ctx, who, began.State, r.g.Code) |
| + if err == nil { |
| + t.Fatal("invalid callback accepted") |
| + } |
| + want := 0 |
| + if change == "replay" { |
| + want = 1 |
| + } |
| + if got := r.g.Calls("POST", "/app-manifests/"+r.g.Code+"/conversions"); got != want { |
| + t.Fatal("unbound conversion reached GitHub") |
| + } |
| + }) |
| + } |
| +} |
| +func TestForgeFlagAndOwner(t *testing.T) { |
| + for _, enabled := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "off", true: "member"}[enabled], func(t *testing.T) { |
| + r := storeRig(t) |
| + r.s.Enabled = enabled |
| + who := r.owner |
| + if enabled { |
| + who.Address = "member@example.test" |
| + } |
| + if _, err := r.s.Start(context.Background(), who, r.g.Login, r.g.AccountType); !errors.Is(err, ErrAccess) { |
| + t.Fatal("setup admitted without flag/current owner") |
| + } |
| + var n int64 |
| + r.s.DB.Model(&Connection{}).Count(&n) |
| + if n != 0 { |
| + t.Fatal("refused start wrote a connection") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func (r *rig) advance(d time.Duration) { r.now = r.now.Add(d); r.g.Now = r.now } |
| +func TestForgePendingAndUninstallDeadlines(t *testing.T) { |
| + ctx := context.Background() |
| + t.Run("pending24h", func(t *testing.T) { |
| + r := storeRig(t) |
| + view := r.created(t) |
| + r.advance(11 * time.Minute) |
| + if _, err := r.s.Check(ctx, r.other, view.ID); err != nil { |
| + t.Fatal("Check again incorrectly needs live redirect:", err) |
| + } |
| + r.advance(24*time.Hour - 11*time.Minute) |
| + got, err := r.s.Check(ctx, r.other, view.ID) |
| + if err == nil || got.State != "expired" { |
| + t.Fatal("pending key did not expire") |
| + } |
| + var c Connection |
| + r.s.DB.First(&c, "id = ?", view.ID) |
| + if c.SealedKey != "" { |
| + t.Fatal("expired key retained") |
| + } |
| + }) |
| + for _, reinstall := range []bool{true, false} { |
| + t.Run(map[bool]string{true: "reinstall", false: "uninstall7d"}[reinstall], func(t *testing.T) { |
| + r := storeRig(t) |
| + view := r.created(t) |
| + if _, err := r.s.Connect(ctx, r.owner, view.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.g.Uninstalled = true |
| + down, err := r.s.Check(ctx, r.other, view.ID) |
| + if err != nil || down.State != "uninstalled" { |
| + t.Fatal("uninstall not detected") |
| + } |
| + var c Connection |
| + r.s.DB.First(&c, "id = ?", view.ID) |
| + first := c.UninstalledAt |
| + if c.SealedKey == "" { |
| + t.Fatal("uninstall immediately erased key") |
| + } |
| + r.advance(3 * 24 * time.Hour) |
| + if _, err = r.s.Check(ctx, r.other, view.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.s.DB.First(&c, "id = ?", view.ID) |
| + if !c.UninstalledAt.Equal(first) { |
| + t.Fatal("refresh extended uninstall retention") |
| + } |
| + if reinstall { |
| + r.g.Uninstalled = false |
| + got, err := r.s.Check(ctx, r.other, view.ID) |
| + if err != nil || got.State != "live" || !got.Confirmed { |
| + t.Fatal("reinstall required another Connect:", err) |
| + } |
| + } else { |
| + r.advance(4 * 24 * time.Hour) |
| + got, err := r.s.Check(ctx, r.other, view.ID) |
| + if err == nil || got.State != "uninstalled_expired" { |
| + t.Fatal("uninstall retention not enforced") |
| + } |
| + r.s.DB.First(&c, "id = ?", view.ID) |
| + if c.SealedKey != "" || c.ActiveAccount != nil { |
| + t.Fatal("uninstall expiry retained key/authority") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestForgeAlreadyConnectedPreservesPending(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + view := r.created(t) |
| + if _, err := r.s.Connect(ctx, r.owner, view.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + pending, err := r.s.Start(ctx, r.other, "another-org", "Organization") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + existing, err := r.s.Start(ctx, r.other, r.g.Login, r.g.AccountType) |
| + if err != nil || existing.View.State != "already_connected" { |
| + t.Fatal("duplicate start not refused") |
| + } |
| + var slot Pending |
| + r.s.DB.First(&slot, "id = ?", 1) |
| + if slot.ConnectionID != pending.View.ID { |
| + t.Fatal("duplicate start replaced unrelated pending setup") |
| + } |
| +} |
| +func TestForgeConnectUnknownCount(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + view := r.created(t) |
| + r.g.Count = 1001 |
| + over, err := r.s.Check(ctx, r.other, view.ID) |
| + if err != nil || over.State != "too_many" || over.CountKnown { |
| + t.Fatal("overflow became a known count") |
| + } |
| + if _, err = r.s.Connect(ctx, r.other, view.ID); err == nil { |
| + t.Fatal("Connect accepted unknown count") |
| + } |
| + r.g.Count = 1000 |
| + checked, err := r.s.Check(ctx, r.other, view.ID) |
| + if err != nil || !checked.CountKnown || checked.Count != 1000 { |
| + t.Fatal("recheck did not recover complete count") |
| + } |
| + if _, err = r.s.Connect(ctx, r.other, view.ID); err != nil { |
| + t.Fatal("Connect refused complete inventory:", err) |
| + } |
| +} |
| +func TestForgeInstallationCallback(t *testing.T) { |
| + for _, test := range []string{"ok", "expired", "wrong-session", "replay"} { |
| + t.Run(test, func(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + view := r.created(t) |
| + var c Connection |
| + r.s.DB.First(&c, "id = ?", view.ID) |
| + state := r.s.state(c, "installation") |
| + who := r.owner |
| + switch test { |
| + case "expired": |
| + r.advance(10 * time.Minute) |
| + case "wrong-session": |
| + who.Session = "different" |
| + case "replay": |
| + if _, err := r.s.Install(ctx, who, state); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + got, err := r.s.Install(ctx, who, state) |
| + if test == "ok" { |
| + if err != nil || got.State != "ready" { |
| + t.Fatal("installation callback:", err) |
| + } |
| + return |
| + } |
| + if err == nil { |
| + t.Fatal("invalid installation callback accepted") |
| + } |
| + if test == "expired" { |
| + if got.State != "installation_expired" { |
| + t.Fatal("wrong expiry state") |
| + } |
| + if _, err := r.s.Check(ctx, r.other, view.ID); err != nil { |
| + t.Fatal("installation expiry lost held key") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestForgeAuditRollback(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + r.s.Audit = func(*gorm.DB, string, string, string) error { return ErrUnavailable } |
| + if _, err := r.s.Start(ctx, r.owner, r.g.Login, r.g.AccountType); err == nil { |
| + t.Fatal("ignored audit failure") |
| + } |
| + var count int64 |
| + if err := r.s.DB.Model(&Connection{}).Count(&count).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if count != 0 { |
| + t.Fatal("unaudited connection persisted") |
| + } |
| +} |
| + |
| +func TestForgeSweepWithoutFeatureFlag(t *testing.T) { |
| + r := storeRig(t) |
| + ctx := context.Background() |
| + view := r.created(t) |
| + r.s.Maintain = func(tx *gorm.DB) error { var rows []testOwner; return tx.Find(&rows).Error } |
| + r.advance(24 * time.Hour) |
| + r.s.Enabled = false |
| + if err := r.s.Sweep(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + var c Connection |
| + if err := r.s.DB.First(&c, "id = ?", view.ID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if c.SealedKey != "" || c.State != "expired" { |
| + t.Fatal("disabled flag retained expired App key") |
| + } |
| + var count int64 |
| + if err := r.s.DB.Model(&testAudit{}).Where("kind = ?", "forge.expire").Count(&count).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if count != 1 { |
| + t.Fatal("expiry audit absent") |
| + } |
| +} |
diff --git a/internal/equipo/github_config_test.go b/internal/equipo/github_config_test.go| new file mode 100644 |
| index 00000000..1e23b758 |
| --- /dev/null |
| +++ b/internal/equipo/github_config_test.go |
| @@ -0,0 +1,16 @@ |
| +package equipo |
| + |
| +import "testing" |
| + |
| +func TestGitHubFlagExplicit(t *testing.T) { |
| + for _, value := range []string{"", "0", "true", "1"} { |
| + env := map[string]string{"EQUIPO_ORIGIN": "https://equipo.example", "EQUIPO_INSTANCE_KEY": "test-key", "CARLOS_MAIL": "submit", "EQUIPO_GITHUB": value} |
| + cfg, err := LoadConfig(func(k string) string { return env[k] }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cfg.GitHubEnabled != (value == "1") { |
| + t.Fatalf("GitHub flag %q: %v", value, cfg.GitHubEnabled) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/github_http.go b/internal/equipo/github_http.go| new file mode 100644 |
| index 00000000..a7f1b3d3 |
| --- /dev/null |
| +++ b/internal/equipo/github_http.go |
| @@ -0,0 +1,191 @@ |
| +package equipo |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/github" |
| + "amadan.net/oficina/equipo/internal/equipo/identity" |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +func (a *application) githubRoutes(r chi.Router) { |
| + r.Get("/conversation/settings/github", a.githubSettings) |
| + r.Post("/github/connect/start", a.githubStart) |
| + r.Post("/github/connect/check", a.githubAction("check")) |
| + r.Post("/github/connect/confirm", a.githubAction("confirm")) |
| + r.Post("/github/connect/disconnect", a.githubAction("disconnect")) |
| +} |
| +func (a *application) githubPerson(w http.ResponseWriter, r *http.Request) (github.Principal, bool) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| + if a.store.forge == nil || !a.store.forge.Enabled { |
| + a.failure(w, r, ErrNotFound) |
| + return github.Principal{}, false |
| + } |
| + _, person, ok := sessionContext(r) |
| + cookie, err := r.Cookie(a.auth.SessionCookie()) |
| + if !ok || err != nil || cookie.Value == "" { |
| + a.failure(w, r, ErrForbidden) |
| + return github.Principal{}, false |
| + } |
| + p := github.Principal{Address: person, Session: cookie.Value} |
| + // The lifecycle repeats this on the primary inside each write transaction. |
| + if _, err = a.store.forge.List(r.Context(), p); err != nil { |
| + a.failure(w, r, ErrForbidden) |
| + return github.Principal{}, false |
| + } |
| + return p, true |
| +} |
| +func (a *application) githubRender(w http.ResponseWriter, r *http.Request, view githubPageView) { |
| + data, err := a.settingsPage(r, "github", false) |
| + if err != nil { |
| + a.failure(w, r, err) |
| + return |
| + } |
| + data.Title = "github.title" |
| + data.GitHub = view |
| + render(w, "github", data) |
| +} |
| +func (a *application) githubSettings(w http.ResponseWriter, r *http.Request) { |
| + p, ok := a.githubPerson(w, r) |
| + if !ok { |
| + return |
| + } |
| + if r.URL.Query().Get("install") == "1" { |
| + target, err := a.store.forge.InstallationURL(r.Context(), p, r.URL.Query().Get("id")) |
| + if err == nil { |
| + http.Redirect(w, r, target, http.StatusSeeOther) |
| + return |
| + } |
| + } |
| + rows, err := a.store.forge.List(r.Context(), p) |
| + if err != nil { |
| + a.failure(w, r, ErrUnavailable) |
| + return |
| + } |
| + view := githubPageView{} |
| + if r.URL.Query().Get("failed") == "1" { |
| + view.Notice = copyText("github.setup_failed") |
| + } |
| + for _, v := range rows { |
| + view.Rows = append(view.Rows, githubRow(r, v)) |
| + } |
| + a.githubRender(w, r, view) |
| +} |
| +func (a *application) githubStart(w http.ResponseWriter, r *http.Request) { |
| + p, ok := a.githubPerson(w, r) |
| + if !ok { |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + if r.ParseForm() != nil { |
| + a.failure(w, r, ErrInvalid) |
| + return |
| + } |
| + ctx, _, _ := sessionContext(r) |
| + started, err := a.store.forge.Start(ctx, p, r.PostForm.Get("account"), r.PostForm.Get("account_type")) |
| + if err != nil { |
| + a.failure(w, r, ErrInvalid) |
| + return |
| + } |
| + view := githubPageView{} |
| + if started.Superseded != nil { |
| + old := *started.Superseded |
| + old.State = "superseded" |
| + view.Rows = append(view.Rows, githubRow(r, old)) |
| + } |
| + if started.State == "" { |
| + view.Rows = append(view.Rows, githubRow(r, started.View)) |
| + a.githubRender(w, r, view) |
| + return |
| + } |
| + manifest := map[string]any{ |
| + "name": started.Name, "url": a.origin, "public": false, |
| + "redirect_url": a.origin + "/github/connect/manifest", |
| + "setup_url": a.origin + "/github/connect/installation", |
| + "hook_attributes": map[string]any{"url": a.origin + "/github/events", "active": false}, |
| + "default_events": []string{}, "request_oauth_on_install": false, |
| + "default_permissions": map[string]string{"contents": "write", "pull_requests": "write", "checks": "read", "statuses": "read", "actions": "read", "metadata": "read"}, |
| + } |
| + raw, err := json.Marshal(manifest) |
| + if err != nil { |
| + a.failure(w, r, ErrUnavailable) |
| + return |
| + } |
| + view.Manifest = string(raw) |
| + view.ManifestURL = "https://github.com/settings/apps/new" |
| + if started.View.AccountType == "Organization" { |
| + view.ManifestURL = "https://github.com/organizations/" + started.View.Login + "/settings/apps/new" |
| + } |
| + view.ManifestURL += "?state=" + url.QueryEscape(started.State) |
| + githubManifestCSP(w) |
| + a.githubRender(w, r, view) |
| +} |
| +func (a *application) githubCallback(w http.ResponseWriter, r *http.Request, manifest bool) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| + id, ok := a.sessionFrom(r) |
| + cookie, cookieErr := r.Cookie(a.auth.SessionCookie()) |
| + if !ok || cookieErr != nil || !a.store.forge.Enabled { |
| + http.Redirect(w, r, "/conversation/settings/github?failed=1", http.StatusSeeOther) |
| + return |
| + } |
| + r = identity.With(r, id) |
| + ctx, _, _ := sessionContext(r) |
| + p := github.Principal{Address: normalizeAddress(id.Address), Session: cookie.Value} |
| + var view github.View |
| + var err error |
| + if manifest { |
| + view, err = a.store.forge.Convert(ctx, p, r.URL.Query().Get("state"), r.URL.Query().Get("code")) |
| + } else { |
| + view, err = a.store.forge.Install(ctx, p, r.URL.Query().Get("state")) |
| + } |
| + // No code, state, upstream body or raw error survives into the clean URL. |
| + target := "/conversation/settings/github" |
| + var refused *github.Refusal |
| + if err != nil && !errors.As(err, &refused) { |
| + target += "?failed=1" |
| + } else if manifest && err == nil { |
| + target += "?id=" + url.QueryEscape(view.ID) + "&install=1" |
| + } |
| + http.Redirect(w, r, target, http.StatusSeeOther) |
| +} |
| +func (a *application) githubManifest(w http.ResponseWriter, r *http.Request) { |
| + a.githubCallback(w, r, true) |
| +} |
| +func (a *application) githubInstallation(w http.ResponseWriter, r *http.Request) { |
| + a.githubCallback(w, r, false) |
| +} |
| +func (a *application) githubAction(action string) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + p, ok := a.githubPerson(w, r) |
| + if !ok { |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + if r.ParseForm() != nil { |
| + a.failure(w, r, ErrInvalid) |
| + return |
| + } |
| + id := r.PostForm.Get("id") |
| + ctx, _, _ := sessionContext(r) |
| + var err error |
| + switch action { |
| + case "check": |
| + _, err = a.store.forge.Check(ctx, p, id) |
| + case "confirm": |
| + _, err = a.store.forge.Connect(ctx, p, id) |
| + case "disconnect": |
| + _, err = a.store.forge.Disconnect(ctx, p, id) |
| + } |
| + var refusal *github.Refusal |
| + target := "/conversation/settings/github" |
| + if err != nil && !errors.As(err, &refusal) { |
| + target += "?failed=1" |
| + } |
| + http.Redirect(w, r, target, http.StatusSeeOther) |
| + } |
| +} |
diff --git a/internal/equipo/github_store.go b/internal/equipo/github_store.go| new file mode 100644 |
| index 00000000..f5908aa5 |
| --- /dev/null |
| +++ b/internal/equipo/github_store.go |
| @@ -0,0 +1,20 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/github" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func (s *Store) configureGitHub(cfg Config) { |
| + s.forge = &github.Store{ |
| + DB: s.db.G, Write: s.write, Root: cfg.InstanceKey, Origin: cfg.Origin, Enabled: cfg.GitHubEnabled, |
| + Now: s.runnerClock.Now, API: github.NewAPI(cfg.GitHubTransport, s.runnerClock.Now), |
| + Owner: func(tx *gorm.DB, person string) error { return requireOwner(tx, Actor{Address: person}) }, |
| + Audit: func(tx *gorm.DB, person, kind, id string) error { |
| + return appendAudit(tx, Actor{Address: person}, kind, id) |
| + }, |
| + // Trusted expiry maintenance reads the current roster in its transaction. |
| + // It erases authority even if the initiating owner has since been removed. |
| + Maintain: func(tx *gorm.DB) error { var members []Member; return tx.Find(&members).Error }, |
| + } |
| +} |
diff --git a/internal/equipo/github_view.go b/internal/equipo/github_view.go| new file mode 100644 |
| index 00000000..4c205327 |
| --- /dev/null |
| +++ b/internal/equipo/github_view.go |
| @@ -0,0 +1,122 @@ |
| +package equipo |
| + |
| +import ( |
| + "fmt" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/github" |
| + "amadan.net/rastrillo/rastrillo" |
| + numbers "amadan.net/rastrillo/rastrillo/number" |
| +) |
| + |
| +type githubPageView struct { |
| + Rows []githubRowView |
| + Manifest, ManifestURL string |
| + Notice string |
| +} |
| +type githubRowView struct { |
| + github.View |
| + Lines []string |
| + Check, Confirm, Disconnect, Cleanup, Reconnect bool |
| + RepositoriesURL string |
| +} |
| + |
| +func githubStateKeys(v github.View) []string { |
| + switch v.State { |
| + case "manifest", "converting": |
| + return []string{"github.create_hint"} |
| + case "pending": |
| + keys := []string{"github.pending", "github.pending_hint"} |
| + if v.AccountType == "Organization" { |
| + keys = append(keys, "github.pending_approval") |
| + } |
| + return keys |
| + case "ready": |
| + return []string{"github.confirm_account", "github.repository_count"} |
| + case "live": |
| + return []string{"github.connected", "github.disconnect_hint"} |
| + case "already_connected": |
| + return []string{"github.already_connected", "github.connected", "github.disconnect_hint"} |
| + case "manifest_expired", "failed": |
| + return []string{"github.setup_failed", "github.app_remains"} |
| + case "installation_expired": |
| + return []string{"github.redirect_expired"} |
| + case "expired": |
| + return []string{"github.pending_expired", "github.app_remains"} |
| + case "superseded": |
| + return []string{"github.app_remains"} |
| + case "disconnected", "uninstalled_expired": |
| + return []string{"github.not_connected", "github.app_remains"} |
| + case "uninstalled": |
| + return []string{"github.not_connected"} |
| + case "reconnect": |
| + return []string{"github.reconnect_hint", "github.app_remains"} |
| + case "check_failed": |
| + return []string{"github.check_failed"} |
| + case "suspended": |
| + return []string{"github.suspended"} |
| + case "too_many": |
| + return []string{"github.too_many"} |
| + default: |
| + return nil |
| + } |
| +} |
| +func githubRow(r *http.Request, v github.View) githubRowView { |
| + row := githubRowView{View: v} |
| + for _, key := range githubStateKeys(v) { |
| + text := copyText(key) |
| + switch key { |
| + case "github.confirm_account", "github.already_connected": |
| + text = fmt.Sprintf(text, v.Login) |
| + case "github.repository_count": |
| + if !v.CountKnown { |
| + continue |
| + } |
| + text = fmt.Sprintf(text, v.Count) |
| + case "github.too_many": |
| + n, _ := numbers.Format(rastrillo.FormatLocale(r), numbers.Decimal(strconv.Itoa(github.MaxRepositories)), numbers.Options{}) |
| + text = fmt.Sprintf(text, n) |
| + case "github.app_remains": |
| + row.Cleanup = true |
| + } |
| + row.Lines = append(row.Lines, text) |
| + } |
| + switch v.State { |
| + case "pending", "installation_expired", "check_failed", "uninstalled", "suspended", "too_many", "ready": |
| + row.Check = true |
| + row.Disconnect = true |
| + case "live", "already_connected": |
| + row.Disconnect = true |
| + case "expired", "uninstalled_expired", "disconnected", "reconnect": |
| + row.Reconnect = true |
| + } |
| + row.Confirm = v.State == "ready" && v.CountKnown && v.Count <= github.MaxRepositories |
| + if v.State == "too_many" && v.InstallationID > 0 { |
| + base := "https://github.com/settings/installations/" |
| + if v.AccountType == "Organization" { |
| + base = "https://github.com/organizations/" + v.Login + "/settings/installations/" |
| + } |
| + row.RepositoriesURL = base + strconv.FormatInt(v.InstallationID, 10) |
| + } |
| + return row |
| +} |
| + |
| +// Only the manifest document may submit outside the instance. Preserve the |
| +// framework's other directives, including frame-ancestors and base-uri. |
| +func githubManifestCSP(w http.ResponseWriter) { |
| + policy := w.Header().Get("Content-Security-Policy") |
| + parts := strings.Split(policy, ";") |
| + found := false |
| + for i, part := range parts { |
| + if strings.HasPrefix(strings.TrimSpace(part), "form-action ") { |
| + parts[i] = " form-action 'self' https://github.com" |
| + found = true |
| + } |
| + } |
| + if !found { |
| + parts = append(parts, "form-action 'self' https://github.com") |
| + } |
| + w.Header().Set("Content-Security-Policy", strings.Join(parts, ";")) |
| +} |
diff --git a/internal/equipo/github_view_test.go b/internal/equipo/github_view_test.go| new file mode 100644 |
| index 00000000..88131172 |
| --- /dev/null |
| +++ b/internal/equipo/github_view_test.go |
| @@ -0,0 +1,84 @@ |
| +package equipo |
| + |
| +import ( |
| + "net/http/httptest" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/github" |
| +) |
| + |
| +func TestGitHubStateCopy(t *testing.T) { |
| + cases := map[string][]string{ |
| + "manifest": {"github.create_hint"}, "converting": {"github.create_hint"}, |
| + "pending": {"github.pending", "github.pending_hint", "github.pending_approval"}, |
| + "ready": {"github.confirm_account", "github.repository_count"}, |
| + "live": {"github.connected", "github.disconnect_hint"}, |
| + "already_connected": {"github.already_connected", "github.connected", "github.disconnect_hint"}, |
| + "manifest_expired": {"github.setup_failed", "github.app_remains"}, |
| + "installation_expired": {"github.redirect_expired"}, |
| + "expired": {"github.pending_expired", "github.app_remains"}, |
| + "failed": {"github.setup_failed", "github.app_remains"}, |
| + "superseded": {"github.app_remains"}, |
| + "disconnected": {"github.not_connected", "github.app_remains"}, |
| + "uninstalled": {"github.not_connected"}, |
| + "uninstalled_expired": {"github.not_connected", "github.app_remains"}, |
| + "reconnect": {"github.reconnect_hint", "github.app_remains"}, |
| + "check_failed": {"github.check_failed"}, "suspended": {"github.suspended"}, "too_many": {"github.too_many"}, |
| + } |
| + for state, want := range cases { |
| + t.Run(state, func(t *testing.T) { |
| + got := githubStateKeys(github.View{State: state, AccountType: "Organization"}) |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("state keys %v, want %v", got, want) |
| + } |
| + for _, key := range got { |
| + if copyText(key) == "" || copyText(key) == key { |
| + t.Fatalf("unrendered %s", key) |
| + } |
| + } |
| + }) |
| + } |
| + if got := githubStateKeys(github.View{State: "pending", AccountType: "User"}); !reflect.DeepEqual(got, []string{"github.pending", "github.pending_hint"}) { |
| + t.Fatalf("personal account: %v", got) |
| + } |
| +} |
| + |
| +func TestGitHubCSPIsolation(t *testing.T) { |
| + policy := "default-src 'self'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" |
| + w := httptest.NewRecorder() |
| + w.Header().Set("Content-Security-Policy", policy) |
| + githubManifestCSP(w) |
| + if got := w.Header().Get("Content-Security-Policy"); got != "default-src 'self'; base-uri 'self'; form-action 'self' https://github.com; frame-ancestors 'none'" { |
| + t.Fatalf("manifest policy: %s", got) |
| + } |
| +} |
| + |
| +func TestGitHubConfirmationAndCleanup(t *testing.T) { |
| + r := httptest.NewRequest("GET", "https://equipo.example/settings", nil) |
| + for _, v := range []github.View{{State: "too_many", InstallationID: 12, AccountType: "Organization", Login: "oficina"}, {State: "ready", CountKnown: false}, {State: "ready", CountKnown: true, Count: 1001}} { |
| + if githubRow(r, v).Confirm { |
| + t.Fatal("Connect shown without complete allowed count") |
| + } |
| + } |
| + row := githubRow(r, github.View{State: "too_many", InstallationID: 12, AccountType: "Organization", Login: "oficina"}) |
| + if !strings.Contains(row.Lines[0], "1,000") || row.RepositoriesURL != "https://github.com/organizations/oficina/settings/installations/12" || !row.Check { |
| + t.Fatal("over-limit controls or localized bound missing") |
| + } |
| + for _, state := range []string{"expired", "uninstalled_expired", "disconnected", "reconnect", "failed", "manifest_expired", "superseded"} { |
| + row := githubRow(r, github.View{State: state}) |
| + if !row.Cleanup || row.Check { |
| + t.Fatalf("cleanup state %s offers Check or omits cleanup", state) |
| + } |
| + } |
| +} |
| + |
| +func TestGitHubDisconnectHeldKey(t *testing.T) { |
| + r := httptest.NewRequest("GET", "https://equipo.example/settings", nil) |
| + for _, state := range []string{"pending", "ready", "installation_expired", "check_failed", "uninstalled", "suspended", "too_many", "live"} { |
| + if !githubRow(r, github.View{State: state}).Disconnect { |
| + t.Fatalf("owner cannot disconnect %s", state) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go| index 21eae397..52884cbc 100644 |
| --- a/internal/equipo/handlers.go |
| +++ b/internal/equipo/handlers.go |
| @@ -27,6 +27,7 @@ type budgetForm struct { |
| Fields []budgetField |
| } |
| type pageData struct { |
| + GitHub githubPageView |
| Placement placementView |
| ID oficinaid.View |
| Repositories []string |
diff --git a/internal/equipo/migrations/0102_forge_connections.sql b/internal/equipo/migrations/0102_forge_connections.sql| new file mode 100644 |
| index 00000000..bc57d878 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0102_forge_connections.sql |
| @@ -0,0 +1,12 @@ |
| +-- Forge authority belongs to the team; pending setup is a single team slot. |
| +CREATE TABLE forge_connections ( |
| + id text PRIMARY KEY, generation integer, state text, login text, |
| + account_type text, account_id integer, app_id integer, slug text, app_name text, |
| + installation_id integer, selection text, confirmed numeric, active_account integer, |
| + sealed_key text, owner text, session text, origin text, manifest_hash text, |
| + installation_hash text, started_at datetime, redirect_until datetime, |
| + pending_until datetime, uninstalled_at datetime, count integer, count_known numeric, |
| + claim text, claim_until datetime, updated_at datetime |
| +); |
| +CREATE UNIQUE INDEX forge_active_account ON forge_connections(active_account); |
| +CREATE TABLE forge_pending (id integer PRIMARY KEY, connection_id text); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 9ca0c316..6362f4ce 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -772,3 +772,16 @@ CREATE TABLE chat_project_names ( |
| ALTER TABLE chat_projects ADD COLUMN title_set numeric; |
| ALTER TABLE chat_projects ADD COLUMN description_set numeric; |
| UPDATE chat_projects SET title_set = metadata_set, description_set = metadata_set; |
| + |
| +-- Forge authority belongs to the team; pending setup is a single team slot. |
| +CREATE TABLE forge_connections ( |
| + id text PRIMARY KEY, generation integer, state text, login text, |
| + account_type text, account_id integer, app_id integer, slug text, app_name text, |
| + installation_id integer, selection text, confirmed numeric, active_account integer, |
| + sealed_key text, owner text, session text, origin text, manifest_hash text, |
| + installation_hash text, started_at datetime, redirect_until datetime, |
| + pending_until datetime, uninstalled_at datetime, count integer, count_known numeric, |
| + claim text, claim_until datetime, updated_at datetime |
| +); |
| +CREATE UNIQUE INDEX forge_active_account ON forge_connections(active_account); |
| +CREATE TABLE forge_pending (id integer PRIMARY KEY, connection_id text); |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index b9a643c8..61b63a31 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -2,6 +2,7 @@ package equipo |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/chat" |
| + "amadan.net/oficina/equipo/internal/equipo/github" |
| "amadan.net/oficina/equipo/internal/equipo/library" |
| "amadan.net/oficina/equipo/internal/equipo/notifications" |
| "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| @@ -56,5 +57,6 @@ type projectRequest = setup.ProjectRequest |
| type Specialist = library.Specialist |
| func init() { |
| + Models = append(Models, github.Models...) |
| Models = append(append(Models, oficinaid.Models...), &oficinaConnectionRecord{}) |
| } |
diff --git a/internal/equipo/render.go b/internal/equipo/render.go| index 67332f39..0e96bc83 100644 |
| --- a/internal/equipo/render.go |
| +++ b/internal/equipo/render.go |
| @@ -61,7 +61,7 @@ func init() { |
| }).ParseFS(ui.Templates(), "*.html")) |
| layout := template.Must(template.Must(base.Clone()).ParseFS(appFS, "templates/layout.html")) |
| shell := template.Must(template.Must(layout.Clone()).ParseFS(appFS, "templates/chrome.html", "templates/forms.html", "templates/task_card.html", "templates/conversation_card.html", "templates/work_parts.html", "templates/housekeeping_settings.html", "templates/autonomy_settings.html", "templates/settings_nav.html", "templates/merge_policy.html", "templates/placement_chip.html", "templates/access_card.html")) |
| - for _, name := range []string{"placement", "oficina_id", "id_public", "person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "chat", "jobs", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "door", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval", "notebook", "housekeeping", "work_tasks", "work_task", "work_projects", "work_project", "models", "work_needs", "settings_hub", "team", "usage"} { |
| + for _, name := range []string{"github", "placement", "oficina_id", "id_public", "person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "chat", "jobs", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "door", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval", "notebook", "housekeeping", "work_tasks", "work_task", "work_projects", "work_project", "models", "work_needs", "settings_hub", "team", "usage"} { |
| var page *template.Template |
| switch name { |
| case "id_public": |
diff --git a/internal/equipo/settings_hub.go b/internal/equipo/settings_hub.go| index f402d936..8e8311ef 100644 |
| --- a/internal/equipo/settings_hub.go |
| +++ b/internal/equipo/settings_hub.go |
| @@ -43,6 +43,7 @@ type settingsLink struct { |
| } |
| var settingsSections = []settingsLink{ |
| + {Key: "github", Href: "/conversation/settings/github", CopyKey: "github.title", Icon: "plug"}, |
| {Key: "autonomy", Href: "/conversation/settings/autonomy", CopyKey: "autonomy.title", Icon: "list-checks"}, |
| {Key: "oficina-id", Href: "/conversation/settings/oficina-id", CopyKey: "id.title", Icon: "users"}, |
| {Key: "thinking", Href: "/conversation/settings/thinking", CopyKey: "thinking.title", Icon: "type"}, |
| @@ -72,6 +73,9 @@ func (a *application) settingsPage(r *http.Request, section string, root bool) ( |
| return data, err |
| } |
| for _, s := range settingsSections { |
| + if s.Key == "github" && (!data.Owner || a.store.forge == nil || !a.store.forge.Enabled) { |
| + continue |
| + } |
| if s.Key == "autonomy" && !data.Owner { |
| continue |
| } |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index 2e5c0072..c0f7836d 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -1,6 +1,7 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/github" |
| "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "context" |
| @@ -57,6 +58,7 @@ type InvitationApplication = setup.Application |
| // against the current roster and append an AuditEvent in their transaction. |
| type Store struct { |
| + forge *github.Store |
| coordinatorRelease *release.Manifest |
| *NotificationApplication |
| *PlanApplication |
diff --git a/internal/equipo/templates/github.html b/internal/equipo/templates/github.html| new file mode 100644 |
| index 00000000..9d931997 |
| --- /dev/null |
| +++ b/internal/equipo/templates/github.html |
| @@ -0,0 +1,33 @@ |
| +{{define "up"}}{{template "settings-up" .}}{{end}} |
| +{{define "up-label"}}{{template "settings-up-label" .}}{{end}} |
| +{{define "title"}}{{copy "github.title"}}{{end}} |
| +{{define "content"}} |
| +<div equipo-settings-layout data-section="github"> |
| +{{template "settings-nav" .}} |
| +<section equipo-settings-body equipo-settings-section id="github"> |
| +<h1>{{copy "github.title"}}</h1> |
| +{{with .GitHub}} |
| +{{with .Notice}}<p role="status">{{.}}</p>{{end}} |
| +{{range .Rows}}<section equipo-sp-group data-forge-connection="{{.ID}}" data-state="{{.State}}"> |
| +<h2>{{.Login}}</h2> |
| +{{range .Lines}}<p>{{.}}</p>{{end}} |
| +{{if .Cleanup}}<a rst-btn href="{{.SettingsURL}}" rel="noreferrer">{{copy "github.app_settings"}}</a>{{end}} |
| +{{if .RepositoriesURL}}<a rst-btn href="{{.RepositoriesURL}}" rel="noreferrer">{{copy "github.choose_repositories"}}</a>{{end}} |
| +{{if .Check}}<form method="post" action="/github/connect/check"><input type="hidden" name="id" value="{{.ID}}"><button rst-btn>{{copy "github.check_again"}}</button></form>{{end}} |
| +{{if .Confirm}}<form method="post" action="/github/connect/confirm"><input type="hidden" name="id" value="{{.ID}}"><button rst-btn="primary">{{copy "github.confirm"}}</button></form>{{end}} |
| +{{if .Disconnect}}<form method="post" action="/github/connect/disconnect"><input type="hidden" name="id" value="{{.ID}}"><button rst-btn>{{copy "github.disconnect"}}</button></form>{{end}} |
| +{{if .Reconnect}}<a rst-btn href="#github-start">{{copy "github.reconnect"}}</a>{{end}} |
| +</section>{{else}}{{if not .Manifest}}<p>{{copy "github.not_connected"}}</p>{{end}}{{end}} |
| +{{if .Manifest}} |
| +<p>{{copy "github.create_hint"}}</p> |
| +<form method="post" action="{{.ManifestURL}}"><input type="hidden" name="manifest" value="{{.Manifest}}"><button rst-btn="primary">{{copy "github.create_app"}}</button></form> |
| +{{else}} |
| +<form equipo-form method="post" action="/github/connect/start" id="github-start"> |
| +<label for="github-account">{{copy "github.account"}}</label><input rst-input name="account" id="github-account" maxlength="39" pattern="[A-Za-z0-9][A-Za-z0-9-]*" required> |
| +<label for="github-account-type">{{copy "github.account_type"}}</label><select rst-input name="account_type" id="github-account-type"><option value="Organization">{{copy "github.organization"}}</option><option value="User">{{copy "github.personal_account"}}</option></select> |
| +<p>{{copy "github.create_hint"}}</p><button rst-btn="primary">{{copy "github.connect"}}</button> |
| +</form> |
| +{{end}} |
| +{{end}} |
| +</section></div> |
| +{{end}} |
diff --git a/internal/equipotest/github_app_test.go b/internal/equipotest/github_app_test.go| new file mode 100644 |
| index 00000000..df9135d0 |
| --- /dev/null |
| +++ b/internal/equipotest/github_app_test.go |
| @@ -0,0 +1,334 @@ |
| +package equipotest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/github" |
| + "amadan.net/rastrillo/rastrillo" |
| + "bytes" |
| + "encoding/json" |
| + "html" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "reflect" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/runner/forge/forgetest" |
| +) |
| + |
| +type githubAuthFixture struct { |
| + authFixture |
| + logs *bytes.Buffer |
| +} |
| + |
| +func githubFixture(t *testing.T, enabled bool, observe ...func(*http.Request)) (githubAuthFixture, *forgetest.GitHub) { |
| + t.Helper() |
| + d, _ := foundationDB(t) |
| + logs := new(bytes.Buffer) |
| + logger := slog.New(slog.NewTextHandler(logs, nil)) |
| + mail := &capturingMailer{} |
| + g := forgetest.NewGitHub(t) |
| + cfg := testConfig(testOrigin) |
| + cfg.GitHubEnabled = enabled |
| + cfg.GitHubTransport = g.Transport() |
| + if len(observe) > 0 { |
| + base := cfg.GitHubTransport |
| + cfg.GitHubTransport = githubHTTPTransportFunc(func(r *http.Request) (*http.Response, error) { |
| + response, err := base.RoundTrip(r) |
| + if err == nil { |
| + observe[0](r) |
| + } |
| + return response, err |
| + }) |
| + } |
| + router, err := equipo.Router(d, cfg, mail, logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + handler, closeHandler, err := rastrillo.Handler(rastrillo.Options{Mux: equipo.Mux(router), Logger: logger}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = closeHandler() }) |
| + server := httptest.NewServer(handler) |
| + t.Cleanup(server.Close) |
| + return githubAuthFixture{authFixture{d, equipo.NewStore(d), mail, server}, logs}, g |
| +} |
| +func githubBody(t *testing.T, response *http.Response) string { |
| + t.Helper() |
| + defer response.Body.Close() |
| + raw, err := io.ReadAll(response.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(raw) |
| +} |
| +func TestGitHubOwnerSettings(t *testing.T) { |
| + for _, enabled := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "off", true: "on"}[enabled], func(t *testing.T) { |
| + f, g := githubFixture(t, enabled) |
| + client := signinClient(t, f.server.URL) |
| + signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) |
| + page := clientGet(t, client, f.server.URL+"/conversation/settings/github") |
| + if enabled && page.StatusCode != 200 { |
| + t.Fatalf("owner page status %d", page.StatusCode) |
| + } |
| + if !enabled && page.StatusCode != 404 { |
| + t.Fatalf("flag-off page status %d", page.StatusCode) |
| + } |
| + body := githubBody(t, page) |
| + if enabled && !strings.Contains(body, "Connect GitHub") { |
| + t.Fatal("owner setup missing") |
| + } |
| + request := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}}) |
| + if enabled && request.StatusCode != 200 { |
| + t.Fatalf("manifest page status %d", request.StatusCode) |
| + } |
| + if !enabled && request.StatusCode != 404 { |
| + t.Fatalf("flag-off start status %d", request.StatusCode) |
| + } |
| + body = githubBody(t, request) |
| + if enabled && (!strings.Contains(body, "https://github.com/organizations/") || !strings.Contains(body, "name=\"manifest\"")) { |
| + t.Fatal("manifest form absent") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func githubManifestForm(t *testing.T, body string) (string, string, string) { |
| + t.Helper() |
| + match := regexp.MustCompile(`action="(https://github.com/[^\"]+)"`).FindStringSubmatch(body) |
| + if len(match) != 2 { |
| + t.Fatal("missing external manifest form") |
| + } |
| + action := html.UnescapeString(match[1]) |
| + fields := formFields(t, body, action) |
| + parsed := mustURL(t, action) |
| + return action, fields.Get("manifest"), parsed.Query().Get("state") |
| +} |
| + |
| +func TestGitHubHTTPFlowAndValues(t *testing.T) { |
| + f, g := githubFixture(t, true) |
| + client := signinClient(t, f.server.URL) |
| + signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) |
| + start := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}}) |
| + if start.StatusCode != 200 { |
| + t.Fatalf("start %d", start.StatusCode) |
| + } |
| + if !strings.Contains(start.Header.Get("Content-Security-Policy"), "form-action 'self' https://github.com") { |
| + t.Fatal("manifest CSP absent") |
| + } |
| + _, manifest, state := githubManifestForm(t, githubBody(t, start)) |
| + var m map[string]any |
| + if err := json.Unmarshal([]byte(manifest), &m); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m["public"] != false || m["request_oauth_on_install"] != false || len(m["default_events"].([]any)) != 0 || m["redirect_url"] != testOrigin+"/github/connect/manifest" || m["setup_url"] != testOrigin+"/github/connect/installation" { |
| + t.Fatal("manifest authority or callbacks changed") |
| + } |
| + want := map[string]any{"contents": "write", "pull_requests": "write", "checks": "read", "statuses": "read", "actions": "read", "metadata": "read"} |
| + if !reflect.DeepEqual(m["default_permissions"], want) || m["hook_attributes"].(map[string]any)["active"] != false { |
| + t.Fatal("manifest permissions or webhook widened") |
| + } |
| + seen := []string{} |
| + clean := func(response *http.Response) string { |
| + t.Helper() |
| + if response.StatusCode != 303 { |
| + t.Fatalf("callback status %d", response.StatusCode) |
| + } |
| + location := response.Header.Get("Location") |
| + if !strings.HasPrefix(location, "/conversation/settings/github") || strings.Contains(location, "state=") || strings.Contains(location, "code=") { |
| + t.Fatal("callback URL not clean") |
| + } |
| + if response.Header.Get("Cache-Control") != "no-store" || response.Header.Get("Referrer-Policy") != "no-referrer" { |
| + t.Fatal("callback caching or referrer") |
| + } |
| + seen = append(seen, location, githubBody(t, response)) |
| + return location |
| + } |
| + callback := f.server.URL + "/github/connect/manifest?" + url.Values{"state": {state}, "code": {g.Code}}.Encode() |
| + location := clean(clientGet(t, client, callback)) |
| + var connections []github.Connection |
| + if err := f.db.G.Find(&connections).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(connections) != 1 || connections[0].Confirmed || connections[0].SealedKey == "" { |
| + t.Fatal("conversion activated or failed to seal") |
| + } |
| + install := clientGet(t, client, f.server.URL+location) |
| + if install.StatusCode != 303 { |
| + t.Fatalf("install handoff %d", install.StatusCode) |
| + } |
| + installURL := mustURL(t, install.Header.Get("Location")) |
| + githubBody(t, install) |
| + installState := installURL.Query().Get("state") |
| + if installURL.Host != "github.com" || installState == "" || installState == state { |
| + t.Fatal("invalid installation handoff") |
| + } |
| + clean(clientGet(t, client, f.server.URL+"/github/connect/installation?"+url.Values{"state": {installState}, "installation_id": {"999999"}}.Encode())) |
| + page := clientGet(t, client, f.server.URL+"/conversation/settings/github") |
| + if strings.Contains(page.Header.Get("Content-Security-Policy"), "github.com") { |
| + t.Fatal("CSP exception spread") |
| + } |
| + body := githubBody(t, page) |
| + seen = append(seen, body) |
| + if !strings.Contains(body, "Repositories: 2") || !strings.Contains(body, `action="/github/connect/confirm"`) { |
| + t.Fatal("verified installation confirmation absent") |
| + } |
| + id := connections[0].ID |
| + clean(clientPost(t, client, f.server.URL+"/github/connect/confirm", testOrigin, url.Values{"id": {id}})) |
| + page = clientGet(t, client, f.server.URL+"/conversation/settings/github") |
| + body = githubBody(t, page) |
| + seen = append(seen, body) |
| + if !strings.Contains(body, "GitHub is connected") { |
| + t.Fatal("Connect not reflected") |
| + } |
| + clean(clientGet(t, client, callback)) |
| + if g.Calls("POST", "/app-manifests/"+g.Code+"/conversions") != 1 { |
| + t.Fatal("callback replay converted again") |
| + } |
| + clean(clientPost(t, client, f.server.URL+"/github/connect/disconnect", testOrigin, url.Values{"id": {id}})) |
| + // Search every application table, including audits, reports, frames and prompts. |
| + // Credential boundaries above are the only permitted code/state surfaces. |
| + var tables []string |
| + if err := f.db.G.Raw("SELECT name FROM sqlite_master WHERE type='table'").Scan(&tables).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, table := range tables { |
| + var rows []map[string]any |
| + if err := f.db.G.Table(table).Find(&rows).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, err := json.Marshal(rows) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seen = append(seen, string(raw)) |
| + } |
| + seen = append(seen, f.logs.String()) |
| + forbidden := []string{g.PEM, g.ClientSecret, g.WebhookSecret, g.Token, g.Code, state, installState} |
| + for _, secret := range forbidden { |
| + if secret == "" { |
| + t.Fatal("empty value-search fixture") |
| + } |
| + for _, sink := range seen { |
| + if strings.Contains(sink, secret) { |
| + t.Fatal("credential or redirect secret escaped its boundary") |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestGitHubHTTPAuthority(t *testing.T) { |
| + f, g := githubFixture(t, true) |
| + client := signinClient(t, f.server.URL) |
| + signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) |
| + fields := url.Values{"account": {g.Login}, "account_type": {g.AccountType}} |
| + for _, origin := range []string{"", "https://evil.example"} { |
| + response := clientPost(t, client, f.server.URL+"/github/connect/start", origin, fields) |
| + if response.StatusCode != 403 { |
| + t.Fatalf("CSRF status %d", response.StatusCode) |
| + } |
| + githubBody(t, response) |
| + } |
| + if err := f.db.G.Model(&equipo.Member{}).Where("address = ?", ownerAddress).Update("role", equipo.RoleMember).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, path := range []string{"start", "check", "confirm", "disconnect"} { |
| + response := clientPost(t, client, f.server.URL+"/github/connect/"+path, testOrigin, fields) |
| + if response.StatusCode != 403 { |
| + t.Fatalf("member %s status %d", path, response.StatusCode) |
| + } |
| + githubBody(t, response) |
| + } |
| + page := clientGet(t, client, f.server.URL+"/conversation/settings/github") |
| + if page.StatusCode != 403 { |
| + t.Fatal("member setup visible") |
| + } |
| + githubBody(t, page) |
| + var n int64 |
| + f.db.G.Model(&github.Connection{}).Count(&n) |
| + if n != 0 { |
| + t.Fatal("forbidden Start wrote") |
| + } |
| +} |
| + |
| +func TestGitHubInvalidCallbackCleanURL(t *testing.T) { |
| + f, _ := githubFixture(t, true) |
| + client := signinClient(t, f.server.URL) |
| + for _, path := range []string{"manifest", "installation"} { |
| + response := clientGet(t, client, f.server.URL+"/github/connect/"+path+"?state=unknown-state&code=unknown-code") |
| + if response.StatusCode != 303 || response.Header.Get("Location") != "/conversation/settings/github?failed=1" { |
| + t.Fatalf("unauthenticated callback not cleaned: status %d", response.StatusCode) |
| + } |
| + githubBody(t, response) |
| + } |
| +} |
| + |
| +type githubHTTPTransportFunc func(*http.Request) (*http.Response, error) |
| + |
| +func (f githubHTTPTransportFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| +func TestGitHubCallbackSessionRevokedDuringConversion(t *testing.T) { |
| + var f githubAuthFixture |
| + f, g := githubFixture(t, true, func(r *http.Request) { |
| + if strings.HasSuffix(r.URL.Path, "/conversions") { |
| + if e := f.db.G.Model(&equipo.Member{}).Where("address = ?", ownerAddress).Update("session_epoch", time.Now().Add(time.Minute).Unix()).Error; e != nil { |
| + t.Error(e) |
| + } |
| + } |
| + }) |
| + client := signinClient(t, f.server.URL) |
| + signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) |
| + response := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}}) |
| + _, _, state := githubManifestForm(t, githubBody(t, response)) |
| + response = clientGet(t, client, f.server.URL+"/github/connect/manifest?"+url.Values{"state": {state}, "code": {g.Code}}.Encode()) |
| + githubBody(t, response) |
| + var rows []github.Connection |
| + if e := f.db.G.Find(&rows).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if len(rows) != 1 || rows[0].SealedKey != "" { |
| + t.Fatal("revoked browser session saved an App key") |
| + } |
| +} |
| + |
| +func TestGitHubInventorySessionRevoked(t *testing.T) { |
| + for _, action := range []string{"check", "confirm"} { |
| + t.Run(action, func(t *testing.T) { |
| + var f githubAuthFixture |
| + f, g := githubFixture(t, true, func(r *http.Request) { |
| + if r.URL.Path == "/installation/repositories" { |
| + if e := f.db.G.Model(&equipo.Member{}).Where("address = ?", ownerAddress).Update("session_epoch", time.Now().Add(time.Minute).Unix()).Error; e != nil { |
| + t.Error(e) |
| + } |
| + } |
| + }) |
| + client := signinClient(t, f.server.URL) |
| + signinEmail(t, client, f.server.URL, testOrigin, f.mail, ownerAddress) |
| + response := clientPost(t, client, f.server.URL+"/github/connect/start", testOrigin, url.Values{"account": {g.Login}, "account_type": {g.AccountType}}) |
| + _, _, state := githubManifestForm(t, githubBody(t, response)) |
| + response = clientGet(t, client, f.server.URL+"/github/connect/manifest?"+url.Values{"state": {state}, "code": {g.Code}}.Encode()) |
| + githubBody(t, response) |
| + var c github.Connection |
| + if e := f.db.G.First(&c).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + response = clientPost(t, client, f.server.URL+"/github/connect/"+action, testOrigin, url.Values{"id": {c.ID}}) |
| + githubBody(t, response) |
| + if e := f.db.G.First(&c).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if c.CountKnown || c.Confirmed { |
| + t.Fatal("revoked browser session committed inventory") |
| + } |
| + if g.Calls("DELETE", "/installation/token") != 1 { |
| + t.Fatal("refused inventory retained metadata token") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/equipotest/github_browser_test.go b/internal/equipotest/github_browser_test.go| new file mode 100644 |
| index 00000000..9c0bd18d |
| --- /dev/null |
| +++ b/internal/equipotest/github_browser_test.go |
| @@ -0,0 +1,117 @@ |
| +//go:build browser |
| + |
| +package equipotest |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/browsertest" |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/runner/forge/forgetest" |
| + "amadan.net/rastrillo/rastrillo" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/cdproto/cdp" |
| + "github.com/chromedp/cdproto/network" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +func TestBrowserGitHubManifestCSP(t *testing.T) { |
| + const origin = "https://equipo.example.test" |
| + d, logger := foundationDB(t) |
| + mail := &capturingMailer{} |
| + g := forgetest.NewGitHub(t) |
| + cfg := testConfig(origin) |
| + cfg.AllowLoggedMail = false |
| + cfg.MailConfigured = true |
| + cfg.GitHubEnabled = true |
| + cfg.GitHubTransport = g.Transport() |
| + router, e := equipo.Router(d, cfg, mail, logger) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + handler, closeHandler, e := rastrillo.Handler(rastrillo.Options{Mux: equipo.Mux(router), Logger: logger}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer closeHandler() |
| + var posts atomic.Int32 |
| + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Host == "github.com" { |
| + if r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/settings/apps/new") { |
| + posts.Add(1) |
| + if r.ParseForm() != nil || r.Form.Get("manifest") == "" { |
| + t.Error("manifest POST missing") |
| + } |
| + http.Redirect(w, r, origin+"/github/connect/manifest?"+url.Values{"code": {g.Code}, "state": {r.URL.Query().Get("state")}}.Encode(), 303) |
| + return |
| + } |
| + if strings.HasSuffix(r.URL.Path, "/installations/new") { |
| + http.Redirect(w, r, origin+"/github/connect/installation?"+url.Values{"state": {r.URL.Query().Get("state")}, "installation_id": {"999999"}}.Encode(), 303) |
| + return |
| + } |
| + http.NotFound(w, r) |
| + return |
| + } |
| + handler.ServeHTTP(w, r) |
| + })) |
| + defer server.Close() |
| + client := signinClient(t, server.URL) |
| + client.Transport = server.Client().Transport |
| + signinEmail(t, client, server.URL, origin, mail, ownerAddress) |
| + source, _ := url.Parse(server.URL) |
| + opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.UserDataDir(t.TempDir()), chromedp.Flag("ignore-certificate-errors", true), chromedp.Flag("no-proxy-server", true), chromedp.Flag("host-resolver-rules", "MAP equipo.example.test "+source.Host+", MAP github.com "+source.Host)) |
| + alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...) |
| + defer stop() |
| + ctx, cancel := chromedp.NewContext(alloc) |
| + defer cancel() |
| + ctx, deadline := context.WithTimeout(ctx, 45*time.Second) |
| + defer deadline() |
| + run := func(actions ...chromedp.Action[chromedp.Void]) { |
| + t.Helper() |
| + if err := chromedp.Do(ctx, actions...); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + yes := true |
| + for _, cookie := range client.Jar.Cookies(source) { |
| + run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + _, e := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: origin + "/", Path: "/", Secure: &yes, HTTPOnly: &yes}) |
| + return e |
| + })) |
| + } |
| + run(chromedp.Navigate(origin+"/conversation/settings/github"), browsertest.Wait(`!!document.querySelector('#github-account')`)) |
| + run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + _, e := chromedp.Evaluate[any](fmt.Sprintf(`document.querySelector('#github-account').value=%q`, g.Login))(ctx, target) |
| + return e |
| + }), browsertest.Click("#github-start button"), browsertest.Wait(`!!document.querySelector('input[name="manifest"]')`), browsertest.Click(`form[action^="https://github.com/"] button`), browsertest.Wait(`location.origin==="https://equipo.example.test" && location.pathname==="/conversation/settings/github" && location.search==="" && !!document.querySelector('form[action="/github/connect/confirm"]')`)) |
| + if posts.Load() != 1 { |
| + t.Fatal("manifest POST did not reach GitHub") |
| + } |
| + // A normal Settings document still cannot submit to GitHub. |
| + run(chromedp.Navigate(origin+"/conversation/settings/thinking"), browsertest.Wait(`!!document.querySelector('form')`), chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + _, e := chromedp.Evaluate[any](`(()=>{window.addEventListener('securitypolicyviolation',()=>window.githubBlocked=true,{once:true});const f=document.createElement('form');f.method='post';f.action='https://github.com/organizations/test/settings/apps/new';document.body.append(f);f.submit()})()`)(ctx, target) |
| + return e |
| + })) |
| + run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + current, e := chromedp.Evaluate[string](`location.origin+location.pathname`)(ctx, target) |
| + if e != nil { |
| + return e |
| + } |
| + if current != origin+"/conversation/settings/thinking" { |
| + return fmt.Errorf("unrelated Settings page submitted externally") |
| + } |
| + return nil |
| + })) |
| + run(browsertest.Wait(`window.githubBlocked===true`)) |
| + if posts.Load() != 1 { |
| + t.Fatal("CSP exception spread to other Settings") |
| + } |
| +} |
diff --git a/internal/plan3test/plan3_release_test.go b/internal/plan3test/plan3_release_test.go| index 82300e9b..d2cba223 100644 |
| --- a/internal/plan3test/plan3_release_test.go |
| +++ b/internal/plan3test/plan3_release_test.go |
| @@ -198,13 +198,14 @@ func plan3CopyInventory(t *testing.T) { |
| // Paul, 2026-11-22: Luna verdicts and the controller clarification are this slice's review. |
| acceptedAPIErrors := slices.Contains([]string{"api.repo_not_allowed", "api.card_answered", "api.card_stale", "api.confirmation_required", "api.coordinator_busy", "api.hold_bar", "api.idempotency_conflict", "api.models_not_allowed", "api.not_active", "api.not_askable", "api.not_mergeable", "api.not_retryable", "api.question_ended", "api.runner_offline", "api.task_busy", "api.task_ended", "api.task_merging", "api.turn_ended"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23)") |
| acceptedNativeProjects := slices.Contains([]string{"projects.new_request", "projects.remove_selection"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23)") |
| + acceptedGitHubApp := slices.Contains([]string{"github.title", "github.connect", "github.account", "github.account_type", "github.organization", "github.personal_account", "github.create_app", "github.create_hint", "github.confirm_account", "github.repository_count", "github.confirm", "github.connected", "github.already_connected", "github.disconnect", "github.disconnect_hint", "github.pending", "github.pending_hint", "github.pending_approval", "github.check_again", "github.redirect_expired", "github.pending_expired", "github.setup_failed", "github.app_remains", "github.app_settings", "github.reconnect", "github.reconnect_hint", "github.check_failed", "github.not_connected", "github.suspended", "github.too_many", "github.choose_repositories"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23)") |
| acceptedGitHubEgress := key == "CopyGitHubEgress" && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23)") |
| acceptedForgeSeam := key == "work.reason.proposal_failed" && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23)") |
| acceptedCardNames := slices.Contains([]string{"projects.carried_selection", "projects.remember_name", "projects.name_to_remember", "projects.use_title", "docs/api/equipo-v1.md / Projects and starting a request"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-23)") |
| acceptedProjects := slices.Contains([]string{"projects.amadan", "projects.yours", "projects.can_add", "projects.add_reachable", "projects.names", "projects.names_hint", "projects.details", "projects.title", "projects.description", "projects.save", "projects.context", "projects.found", "projects.selected", "projects.owner_add", "projects.selection_lost", "projects.other", "projects.name_question", "projects.personal_names", "projects.forget_name", "docs/api/equipo-v1.md / Projects and starting a request"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-22)") |
| acceptedAgentAccess := slices.Contains([]string{"copyAgentConfig", "copyAgentForbidden", "copyAgentNotFound", "copyAgentUnavailable", "copyAgentTooLarge", "copyAgentInvalid", "copyAgentMedia", "copyAgentUnauthenticated", "agent.equipo_projects_list", "agent.equipo_tasks_list", "agent.equipo_task_get", "agent.equipo_needs_you", "docs/api/equipo-v1.md / Delegated read-only operations"}, key) && strings.HasSuffix(strings.TrimSuffix(cells[3], " |"), "COPY ACCEPTED BY DELEGATION (Luna, 2026-11-20)") |
| acceptedCopy := strings.TrimSuffix(cells[3], " |") == "COPY ACCEPTED BY DELEGATION (Copy, record-bound) sha256:"+copydesk.Hash(rows[key]) |
| - if !acceptedGitHubEgress && !acceptedForgeSeam && !acceptedAPIErrors && !acceptedNativeProjects && !acceptedInjection && !acceptedMail && !acceptedPush && !acceptedAgentAccess && !acceptedProjects && !acceptedCardNames && !acceptedAccess && !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina && !approvedFailedReplies && !approvedStopReasons { |
| + if !acceptedGitHubApp && !acceptedGitHubEgress && !acceptedForgeSeam && !acceptedAPIErrors && !acceptedNativeProjects && !acceptedInjection && !acceptedMail && !acceptedPush && !acceptedAgentAccess && !acceptedProjects && !acceptedCardNames && !acceptedAccess && !acceptedPlacementEdges && !acceptedPlacement && !acceptedReportActions && !acceptedRoster && !acceptedCopy && !strings.Contains(cells[3], "COPY REVIEW REQUIRED") && !acceptedAll && !acceptedGuide && !acceptedRound2 && !acceptedStarter && !acceptedDelegation && !approvedPublish && !approvedAssistant && !approvedJobs && !approvedOficina && !approvedFailedReplies && !approvedStopReasons { |
| t.Fatal("entry has no copy review status or applicable acceptance", key) |
| } |
| } |
diff --git a/internal/runner/forge/forgetest/github.go b/internal/runner/forge/forgetest/github.go| new file mode 100644 |
| index 00000000..5ef9d972 |
| --- /dev/null |
| +++ b/internal/runner/forge/forgetest/github.go |
| @@ -0,0 +1,262 @@ |
| +package forgetest |
| + |
| +import ( |
| + "crypto" |
| + "crypto/rand" |
| + "crypto/rsa" |
| + "crypto/sha256" |
| + "crypto/x509" |
| + "encoding/base64" |
| + "encoding/json" |
| + "encoding/pem" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// GitHub is a generated-key installation API. It has no write-token route. |
| +// Tests configure fields before a request; the request ledger is synchronized. |
| +type GitHub struct { |
| + Server *httptest.Server |
| + Key *rsa.PrivateKey |
| + PEM string |
| + Code, ClientSecret, WebhookSecret, Token string |
| + AppID, AccountID, InstallationID int64 |
| + Login, AccountType, Selection string |
| + Count int |
| + Suspended, Uninstalled bool |
| + Now time.Time |
| + FailPath string |
| + FailStatus int |
| + FailBody string |
| + FailHeaders http.Header |
| + mu sync.Mutex |
| + calls map[string]int |
| + converted bool |
| + revoked bool |
| + tokenGeneration int |
| + t testing.TB |
| +} |
| + |
| +func NewGitHub(t testing.TB) *GitHub { |
| + t.Helper() |
| + key, err := rsa.GenerateKey(rand.Reader, 2048) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + g := &GitHub{t: t, Key: key, AppID: 101, AccountID: 202, InstallationID: 303, Login: "oficina-test", AccountType: "Organization", Selection: "selected", Count: 2, Now: time.Now().UTC(), calls: map[string]int{}} |
| + g.PEM = string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})) |
| + nonce := func() string { |
| + b := make([]byte, 24) |
| + if _, err := rand.Read(b); err != nil { |
| + t.Fatal(err) |
| + } |
| + return base64.RawURLEncoding.EncodeToString(b) |
| + } |
| + g.Code, g.ClientSecret, g.WebhookSecret, g.Token = nonce(), nonce(), nonce(), "ghs_"+nonce() |
| + g.Server = httptest.NewServer(http.HandlerFunc(g.serve)) |
| + t.Cleanup(g.Server.Close) |
| + return g |
| +} |
| + |
| +func (g *GitHub) Calls(method, path string) int { |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + return g.calls[method+" "+path] |
| +} |
| + |
| +func (g *GitHub) permissions() map[string]string { |
| + return map[string]string{"contents": "write", "pull_requests": "write", "checks": "read", "statuses": "read", "actions": "read", "metadata": "read"} |
| +} |
| +func (g *GitHub) account() map[string]any { |
| + return map[string]any{"id": g.AccountID, "login": g.Login, "type": g.AccountType} |
| +} |
| +func (g *GitHub) app() map[string]any { |
| + return map[string]any{"id": g.AppID, "slug": "equipo-test-app", "owner": g.account(), "permissions": g.permissions(), "events": []string{}} |
| +} |
| +func (g *GitHub) installation() map[string]any { |
| + v := map[string]any{"id": g.InstallationID, "app_id": g.AppID, "account": g.account(), "permissions": g.permissions(), "events": []string{}, "repository_selection": g.Selection, "suspended_at": nil} |
| + if g.Suspended { |
| + v["suspended_at"] = g.Now.Format(time.RFC3339) |
| + } |
| + return v |
| +} |
| +func (g *GitHub) jwt(raw string) bool { |
| + bits := strings.Split(strings.TrimPrefix(raw, "Bearer "), ".") |
| + if len(bits) != 3 { |
| + return false |
| + } |
| + header, e := base64.RawURLEncoding.DecodeString(bits[0]) |
| + if e != nil { |
| + return false |
| + } |
| + var h struct{ Alg string } |
| + if json.Unmarshal(header, &h) != nil || h.Alg != "RS256" { |
| + return false |
| + } |
| + payload, e := base64.RawURLEncoding.DecodeString(bits[1]) |
| + if e != nil { |
| + return false |
| + } |
| + var v struct { |
| + Iss string |
| + Iat, Exp int64 |
| + } |
| + if json.Unmarshal(payload, &v) != nil { |
| + return false |
| + } |
| + if v.Iss != strconv.FormatInt(g.AppID, 10) || v.Iat > g.Now.Unix() || v.Exp <= g.Now.Unix() || v.Exp-g.Now.Unix() > 600 { |
| + return false |
| + } |
| + sig, e := base64.RawURLEncoding.DecodeString(bits[2]) |
| + if e != nil { |
| + return false |
| + } |
| + digest := sha256.Sum256([]byte(bits[0] + "." + bits[1])) |
| + return rsa.VerifyPKCS1v15(&g.Key.PublicKey, crypto.SHA256, digest[:], sig) == nil |
| +} |
| +func (g *GitHub) serve(w http.ResponseWriter, r *http.Request) { |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + g.calls[r.Method+" "+r.URL.Path]++ |
| + w.Header().Set("Content-Type", "application/json") |
| + if r.Header.Get("X-GitHub-Api-Version") != "2022-11-28" || r.Header.Get("Accept") != "application/vnd.github+json" || r.UserAgent() == "" { |
| + w.WriteHeader(400) |
| + return |
| + } |
| + if r.URL.Path == g.FailPath { |
| + for k, v := range g.FailHeaders { |
| + w.Header()[k] = v |
| + } |
| + w.WriteHeader(g.FailStatus) |
| + _, _ = io.WriteString(w, g.FailBody) |
| + return |
| + } |
| + answer := func(status int, v any) { w.WriteHeader(status); _ = json.NewEncoder(w).Encode(v) } |
| + if r.Method == "POST" && r.URL.Path == "/app-manifests/"+g.Code+"/conversions" { |
| + if g.converted || r.Header.Get("Authorization") != "" { |
| + w.WriteHeader(422) |
| + return |
| + } |
| + g.converted = true |
| + v := g.app() |
| + v["pem"], v["client_secret"], v["webhook_secret"] = g.PEM, g.ClientSecret, g.WebhookSecret |
| + answer(201, v) |
| + return |
| + } |
| + if strings.HasPrefix(r.URL.Path, "/app-manifests/") { |
| + w.WriteHeader(404) |
| + return |
| + } |
| + if strings.HasPrefix(r.URL.Path, "/app") && !g.jwt(r.Header.Get("Authorization")) { |
| + w.WriteHeader(401) |
| + return |
| + } |
| + switch { |
| + case r.Method == "GET" && r.URL.Path == "/app": |
| + answer(200, g.app()) |
| + case r.Method == "GET" && r.URL.Path == "/app/installations": |
| + rows := []any{} |
| + if !g.Uninstalled { |
| + rows = append(rows, g.installation()) |
| + } |
| + answer(200, rows) |
| + case r.Method == "GET" && r.URL.Path == fmt.Sprintf("/app/installations/%d", g.InstallationID): |
| + if g.Uninstalled { |
| + w.WriteHeader(404) |
| + return |
| + } |
| + answer(200, g.installation()) |
| + case r.Method == "POST" && r.URL.Path == fmt.Sprintf("/app/installations/%d/access_tokens", g.InstallationID): |
| + var body map[string]json.RawMessage |
| + if json.NewDecoder(r.Body).Decode(&body) != nil || len(body) != 1 { |
| + w.WriteHeader(422) |
| + return |
| + } |
| + var permissions map[string]string |
| + if json.Unmarshal(body["permissions"], &permissions) != nil || len(permissions) != 1 || permissions["metadata"] != "read" { |
| + w.WriteHeader(422) |
| + return |
| + } |
| + if g.Uninstalled || g.Suspended { |
| + w.WriteHeader(403) |
| + return |
| + } |
| + g.revoked = false |
| + g.tokenGeneration++ |
| + if g.tokenGeneration > 1 { |
| + g.Token = "ghs_" + rand.Text() |
| + } |
| + answer(201, map[string]any{"token": g.Token, "expires_at": g.Now.Add(time.Hour).Format(time.RFC3339), "permissions": permissions, "repository_selection": g.Selection}) |
| + case r.URL.Path == "/installation/repositories" && r.Method == "GET": |
| + if g.revoked || r.Header.Get("Authorization") != "Bearer "+g.Token { |
| + w.WriteHeader(401) |
| + return |
| + } |
| + page, _ := strconv.Atoi(r.URL.Query().Get("page")) |
| + if page < 1 { |
| + page = 1 |
| + } |
| + rows := []any{} |
| + for i := (page - 1) * 100; i < page*100 && i < g.Count; i++ { |
| + rows = append(rows, map[string]any{"id": 1000 + i, "full_name": fmt.Sprintf("%s/repo%d", g.Login, i), "owner": g.account(), "permissions": map[string]bool{"admin": false, "maintain": false, "push": false, "triage": false, "pull": false}}) |
| + } |
| + if page*100 < g.Count { |
| + w.Header().Set("Link", fmt.Sprintf(`<https://api.github.com/installation/repositories?per_page=100&page=%d>; rel="next"`, page+1)) |
| + } |
| + etag := fmt.Sprintf(`"inventory-%d-%d-%d"`, g.tokenGeneration, g.Count, page) |
| + w.Header().Set("ETag", etag) |
| + w.Header().Set("Vary", "Authorization") |
| + w.Header().Set("Cache-Control", "private, max-age=60, s-maxage=60") |
| + if r.Header.Get("If-None-Match") == etag { |
| + w.WriteHeader(304) |
| + return |
| + } |
| + answer(200, map[string]any{"total_count": g.Count, "repositories": rows}) |
| + case r.Method == "GET" && r.URL.Path == "/repos/"+g.Login+"/probe/contents/README.md": |
| + if g.revoked || r.Header.Get("Authorization") != "Bearer "+g.Token { |
| + w.WriteHeader(401) |
| + } else { |
| + w.WriteHeader(403) |
| + } |
| + case r.URL.Path == "/installation/token" && r.Method == "DELETE": |
| + if r.Header.Get("Authorization") != "Bearer "+g.Token { |
| + w.WriteHeader(401) |
| + return |
| + } |
| + g.revoked = true |
| + w.WriteHeader(204) |
| + default: |
| + g.t.Error("unexpected GitHub route or verb") |
| + w.WriteHeader(404) |
| + } |
| +} |
| + |
| +type githubTransport struct { |
| + base http.RoundTripper |
| + target *url.URL |
| +} |
| + |
| +func (t githubTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| + if r.URL.Scheme != "https" || r.URL.Host != "api.github.com" { |
| + return nil, fmt.Errorf("unexpected GitHub endpoint") |
| + } |
| + copy := r.Clone(r.Context()) |
| + u := *r.URL |
| + copy.URL = &u |
| + copy.URL.Scheme, copy.URL.Host = t.target.Scheme, t.target.Host |
| + return t.base.RoundTrip(copy) |
| +} |
| + |
| +// Transport preserves the production URL contract and routes only that host to the fake. |
| +func (g *GitHub) Transport() http.RoundTripper { |
| + u, _ := url.Parse(g.Server.URL) |
| + return githubTransport{http.DefaultTransport, u} |
| +} |
diff --git a/internal/runner/thin/github_scan_test.go b/internal/runner/thin/github_scan_test.go| new file mode 100644 |
| index 00000000..e8d5a831 |
| --- /dev/null |
| +++ b/internal/runner/thin/github_scan_test.go |
| @@ -0,0 +1,41 @@ |
| +package thin |
| + |
| +import ( |
| + "github.com/spf13/viper" |
| + "github.com/zricethezav/gitleaks/v8/config" |
| + "github.com/zricethezav/gitleaks/v8/detect" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestGitHubSecretScan(t *testing.T) { |
| + v := viper.New() |
| + v.SetConfigType("toml") |
| + if err := v.ReadConfig(strings.NewReader(previewSecretRules)); err != nil { |
| + t.Fatal(err) |
| + } |
| + var raw config.ViperConfig |
| + if err := v.Unmarshal(&raw); err != nil { |
| + t.Fatal(err) |
| + } |
| + rules, err := raw.Translate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + scanner := detect.NewDetector(rules) |
| + scanner.IgnoreGitleaksAllow = true |
| + cases := map[string]string{} |
| + for _, prefix := range []string{"ghs_", "ghu_", "gho_", "ghr_"} { |
| + cases[prefix] = prefix + strings.Repeat("a", 24) |
| + } |
| + for _, kind := range []string{"", "RSA ", "EC ", "OPENSSH ", "ENCRYPTED "} { |
| + cases["PEM "+kind] = "-----BEGIN " + kind + "PRIVATE KEY" + "-----\ntruncated" |
| + } |
| + for name, secret := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + if len(scanner.DetectString(secret+" // gitleaks:allow\n")) == 0 { |
| + t.Fatal("secret shape admitted") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/thin/preview_security.go b/internal/runner/thin/preview_security.go| index a58d2f32..3f768ffc 100644 |
| --- a/internal/runner/thin/preview_security.go |
| +++ b/internal/runner/thin/preview_security.go |
| @@ -34,6 +34,16 @@ func previewCSP(origin string) string { |
| return value |
| } |
| +const previewSecretRules = `[extend] |
| +useDefault = true |
| +[[rules]] |
| +id = "equipo-github-token" |
| +regex = '''(?:ghs_|ghu_|gho_|ghr_)[A-Za-z0-9_]{20,}''' |
| +[[rules]] |
| +id = "equipo-private-key-header" |
| +regex = '''-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----''' |
| +` |
| + |
| const previewScanner = "github.com/zricethezav/gitleaks/v8@" + release.GitleaksVersion |
| var previewScannerTool = func(c runner.Config) (string, string) { |
| @@ -53,7 +63,7 @@ func (e *Engineer) scanPreview(ctx context.Context, stage string) string { |
| config := filepath.Join(dir, "trusted.toml") |
| ignore := filepath.Join(dir, "empty.ignore") |
| report := filepath.Join(dir, "findings.json") |
| - if os.WriteFile(config, []byte("[extend]\nuseDefault = true\n"), 0600) != nil || os.WriteFile(ignore, nil, 0600) != nil { |
| + if os.WriteFile(config, []byte(previewSecretRules), 0600) != nil || os.WriteFile(ignore, nil, 0600) != nil { |
| return "preview_scanner" |
| } |
| args := func(bin, cfg, ign, rep, files string) []string { |
diff --git a/internal/runnerproto/event_io.go b/internal/runnerproto/event_io.go| index 2b75112a..ad17c82e 100644 |
| --- a/internal/runnerproto/event_io.go |
| +++ b/internal/runnerproto/event_io.go |
| @@ -47,9 +47,12 @@ func WaitReconnect(ctx context.Context, attempt int, leaseDeadline time.Time) er |
| } |
| } |
| -var secretPattern = regexp.MustCompile(`(?i)((?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]+|((?:api[_-]?key|password|secret|token)\s*[=:]\s*)[^\s,"'<>]+|(?:sk-|ghp_|github_pat_)[A-Za-z0-9_-]{8,}`) |
| +var secretPattern = regexp.MustCompile(`(?i)((?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]+|((?:api[_-]?key|password|secret|token)\s*[=:]\s*)[^\s,"'<>]+|(?:sk-|ghp_|ghs_|ghu_|gho_|ghr_|github_pat_)[A-Za-z0-9_-]{8,}`) |
| + |
| +var privateKeyPattern = regexp.MustCompile(`(?s)-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----.*?(?:-----END (?:[A-Z0-9]+ )?PRIVATE KEY-----|$)`) |
| func RedactText(s string, secrets []string) string { |
| + s = privateKeyPattern.ReplaceAllString(s, "***") |
| for _, secret := range secrets { |
| if secret != "" { |
| s = strings.ReplaceAll(s, secret, "***") |
diff --git a/internal/runnerproto/github_redaction_test.go b/internal/runnerproto/github_redaction_test.go| new file mode 100644 |
| index 00000000..03f38abf |
| --- /dev/null |
| +++ b/internal/runnerproto/github_redaction_test.go |
| @@ -0,0 +1,50 @@ |
| +package runnerproto |
| + |
| +import ( |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestGitHubSecretShapes(t *testing.T) { |
| + for _, prefix := range []string{"ghs_", "ghu_", "gho_", "ghr_"} { |
| + t.Run(prefix, func(t *testing.T) { |
| + secret := prefix + strings.Repeat("Ab9z", 12) |
| + if got := RedactText("before "+secret+" after", nil); got != "before *** after" { |
| + t.Fatal("unregistered GitHub token shape was not redacted") |
| + } |
| + raw, _ := json.Marshal(map[string]any{"detail": []string{secret}}) |
| + if strings.Contains(string(RedactJSON(raw, nil)), secret) { |
| + t.Fatal("token escaped nested JSON redaction") |
| + } |
| + }) |
| + } |
| + for _, kind := range []string{"", "RSA ", "EC ", "OPENSSH ", "ENCRYPTED "} { |
| + for _, truncated := range []bool{false, true} { |
| + name := strings.TrimSpace(kind) |
| + if truncated { |
| + name += " truncated" |
| + } |
| + t.Run(name, func(t *testing.T) { |
| + header := strings.Repeat("-", 5) + "BEGIN " + kind + "PRIVATE KEY" + strings.Repeat("-", 5) |
| + body := strings.Repeat("aGVsbG8=", 8) |
| + secret := header + "\n" + body + "\n" |
| + suffix := "" |
| + if !truncated { |
| + secret += strings.Replace(header, "BEGIN", "END", 1) |
| + suffix = " after" |
| + } |
| + if got := RedactText("before "+secret+suffix, nil); got != "before ***"+suffix { |
| + t.Fatal("private key block or truncated body was not redacted") |
| + } |
| + raw, _ := json.Marshal(map[string]string{"detail": secret}) |
| + if got := string(RedactJSON(raw, nil)); strings.Contains(got, body) || strings.Contains(got, "PRIVATE KEY") { |
| + t.Fatal("key escaped JSON redaction") |
| + } |
| + }) |
| + } |
| + } |
| + if got := RedactText("github.com/oficina/probe is a repository", nil); got != "github.com/oficina/probe is a repository" { |
| + t.Fatal("ordinary repository text was removed") |
| + } |
| +} |