From 411e7c50da3c8aedfe4da3c49e6e4a0247907129 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Sat, 28 Nov 2026 22:18:10 -0800 Subject: [PATCH 1/2] feat(github): report deploys to GitHub deployments Report deploy, rollback, resume and abort to a repository's GitHub deployments, so they show in its Environments tab and reach tools that read deployment statuses, wherever ob runs: a laptop, an agent or a GitHub Actions runner. Opt in with spec.github.repository. The commit is decided at plan time and bound into the plan digest. A workload image whose org.opencontainers.image.source label names the repository reports its org.opencontainers.image.revision, in its own GitHub environment named like "production (shop-web)", so a release that ships images built at different commits never claims one commit for all of them. A configuration-only repository reports a clean checkout's commit when the checkout is a clone of that repository. Anything uncertain reports nothing. Commits ride on the deploy's start journal record so a rollback reports the release it restores. Reporting is fail-open. The token is read where ob runs and never reaches the host; a github.com token is never sent to another apiUrl. A deploy is announced only after the host records its start, creates are not retried after GitHub may have acted, and a dead GitHub delays the end of a command by at most 15 seconds. Also: ONEBOX_OPERATOR, and the triggering actor in GitHub Actions, name the operator; github.apiUrl supports GitHub Enterprise; and new guides cover GitHub deployments and deploying from GitHub Actions with either Onebox approval or GitHub required reviewers. Closes #244 Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- .../v1alpha2/application.schema.json | 35 ++ cmd/ob-docgen/main.go | 3 + cmd/ob/commands.go | 8 +- cmd/ob/github.go | 190 +++++++++ cmd/ob/github_test.go | 188 +++++++++ internal/app/constraints.go | 3 + internal/app/jsonschema.go | 4 + internal/app/load_test.go | 41 ++ internal/app/types.go | 10 + internal/app/validate.go | 15 + internal/engine/deploy.go | 7 +- internal/engine/deploy_test.go | 1 + internal/engine/engine.go | 4 + internal/engine/image_source.go | 123 ++++++ internal/engine/image_source_test.go | 28 ++ internal/engine/plan.go | 6 +- internal/ghdeploy/ghdeploy.go | 375 ++++++++++++++++++ internal/ghdeploy/ghdeploy_test.go | 368 +++++++++++++++++ internal/ghdeploy/reporter.go | 239 +++++++++++ internal/gitinfo/revision.go | 50 +++ internal/gitinfo/revision_test.go | 51 +++ internal/journal/journal.go | 75 +++- internal/journal/journal_test.go | 65 +++ internal/onebox/approval_test.go | 23 ++ internal/onebox/execute.go | 24 ++ internal/onebox/execution_types.go | 13 +- internal/onebox/plan_deploy.go | 2 +- internal/onebox/source_commits.go | 194 +++++++++ internal/onebox/source_commits_test.go | 148 +++++++ .../v1alpha2/application.schema.json | 35 ++ .../guides/deploy-from-github-actions.mdx | 249 ++++++++++++ .../docs/docs/guides/github-deployments.mdx | 124 ++++++ .../docs/docs/reference/capabilities.mdx | 6 + .../docs/docs/reference/fields/github.mdx | 30 ++ 35 files changed, 2723 insertions(+), 21 deletions(-) create mode 100644 cmd/ob/github.go create mode 100644 cmd/ob/github_test.go create mode 100644 internal/engine/image_source.go create mode 100644 internal/engine/image_source_test.go create mode 100644 internal/ghdeploy/ghdeploy.go create mode 100644 internal/ghdeploy/ghdeploy_test.go create mode 100644 internal/ghdeploy/reporter.go create mode 100644 internal/onebox/source_commits.go create mode 100644 internal/onebox/source_commits_test.go create mode 100644 site/src/content/docs/docs/guides/deploy-from-github-actions.mdx create mode 100644 site/src/content/docs/docs/guides/github-deployments.mdx create mode 100644 site/src/content/docs/docs/reference/fields/github.mdx diff --git a/README.md b/README.md index 72cfa000..2fb15eec 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ the exact plan you reviewed. | Host access | Agentless SSH, key authentication, and mandatory `known_hosts` verification. An optional one-hop jump host reaches private targets, with both hops verified and the agent never forwarded. | | Runtime ownership | Generated Compose stays inspectable with `ob preview` and can be taken over permanently with `ob eject`. | | Automation | Human output, JSON envelopes, and NDJSON event streams come from the same lifecycle service. | +| GitHub | Deploys, rollbacks, resumes and aborts are reported to GitHub deployments at the commit each image was built from, whether `ob` runs on a laptop, an agent or a GitHub Actions runner. | Workload reconciliation is automatic; it needs no selection flag. Onebox fingerprints the effective runtime contract, including the rendered service, @@ -189,8 +190,10 @@ for agents. - **Operate:** [databases](https://onebox.run/docs/guides/databases), [backups](https://onebox.run/docs/guides/backups), [migrations](https://onebox.run/docs/guides/migrations), - [secrets](https://onebox.run/docs/guides/secrets), and - [rollback](https://onebox.run/docs/guides/rollback) + [secrets](https://onebox.run/docs/guides/secrets), + [rollback](https://onebox.run/docs/guides/rollback), + [GitHub deployments](https://onebox.run/docs/guides/github-deployments), and + [deploying from GitHub Actions](https://onebox.run/docs/guides/deploy-from-github-actions) - **Reference:** [project file](https://onebox.run/docs/reference/project-file), [CLI](https://onebox.run/docs/reference/cli), [errors](https://onebox.run/docs/reference/errors), and diff --git a/api/application/v1alpha2/application.schema.json b/api/application/v1alpha2/application.schema.json index df3c64db..f8c4ce7c 100644 --- a/api/application/v1alpha2/application.schema.json +++ b/api/application/v1alpha2/application.schema.json @@ -767,6 +767,41 @@ "description": "Typed dependencies operated outside Onebox. Their connection projection is trusted, but their lifecycle and backup remain external.", "type": "object" }, + "github": { + "additionalProperties": false, + "description": "Report deploys and rollbacks to a GitHub repository's deployments, so they show in its Environments tab and reach tools that read deployment statuses.", + "properties": { + "apiUrl": { + "default": "https://api.github.com", + "description": "GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. A github.com token is never sent to another host: there the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL.", + "examples": [ + "https://github.example.com/api/v3" + ], + "pattern": "^https?://", + "type": "string" + }, + "repository": { + "description": "GitHub repository, as owner/name, whose deployments record each deploy and rollback. Workload images whose org.opencontainers.image.source label names this repository are reported at their org.opencontainers.image.revision commit; when none does, the clean checkout's commit is reported if the checkout is a clone of this repository. Each image repository is reported in its own GitHub environment, named like production (shop-web); a configuration-only repository is named after the application. Expects owner/name, such as labstack/shop.", + "examples": [ + "labstack/shop" + ], + "pattern": "^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}$", + "type": "string" + }, + "tokenEnv": { + "description": "Local environment-variable name containing a GitHub token with Deployments write access. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects a variable name of letters, digits and underscores, not starting with a digit.", + "examples": [ + "GH_TOKEN" + ], + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "type": "string" + } + }, + "required": [ + "repository" + ], + "type": "object" + }, "hooks": { "additionalProperties": { "anyOf": [ diff --git a/cmd/ob-docgen/main.go b/cmd/ob-docgen/main.go index c6744d74..19cfe59d 100644 --- a/cmd/ob-docgen/main.go +++ b/cmd/ob-docgen/main.go @@ -335,6 +335,9 @@ var blocks = []block{ {Key: "notifications", Title: "notifications", Order: 100, Status: statusShipped, Summary: "Named webhooks that receive selected operation and scheduled-job outcomes.", ReadWhen: []string{"Sending deploy outcomes to Slack, Discord or an incident tool"}}, + {Key: "github", Title: "github", Order: 110, Status: statusShipped, + Summary: "The GitHub repository whose deployments record each deploy and rollback, and the local token used to report them.", + ReadWhen: []string{"Showing deploys in a repository's Environments tab, on pull requests, or to tools that read deployment statuses"}}, {Key: "backupTargets", Slug: "backup-targets", Title: "backupTargets", Order: 200, Status: statusShipped, Summary: "User-owned off-host S3-compatible repositories a protected service writes its backups to. Executable for the postgres driver; every other driver refuses a policy it cannot honour.", ReadWhen: []string{"Declaring where a database's backups go", "Understanding why Onebox refuses a backup target that shares the protected host"}}, diff --git a/cmd/ob/commands.go b/cmd/ob/commands.go index e356caee..dfcae5c8 100644 --- a/cmd/ob/commands.go +++ b/cmd/ob/commands.go @@ -593,11 +593,10 @@ func runMutation(cmd *cobra.Command, g *globalFlags, request onebox.ExecuteReque structured.event(event) } } - result, err := operationsService(cmd, g).Execute(cmd.Context(), request) + result, err := executeAndReport(cmd.Context(), operationsService(cmd, g), cfg, g, request, verb) if err == nil && result.NoOp && request.Kind == onebox.KindDeploy && structured == nil { renderDeployNoOp(newUI(cmd, g), request.Plan.Artifact.HostState.CurrentRelease) } - notifyOperationOutcome(cmd.Context(), cfg, g, verb, result, err) if structured != nil { if outputErr := structured.finish(&result, err); outputErr != nil { if err == nil { @@ -781,15 +780,14 @@ func runDeploy(cmd *cobra.Command, g *globalFlags, planFile, approvalFile, backu approval = &grant } } - result, err := pl.svc.Execute(cmd.Context(), onebox.ExecuteRequest{ + result, err := executeAndReport(cmd.Context(), pl.svc, pl.cfg, g, onebox.ExecuteRequest{ Kind: onebox.KindDeploy, Plan: &pl.plan, Approval: approval, BreakLock: breakLock, NoRollback: g.NoRollback, Redeploy: redeploy, - }) + }, "deploy") if err == nil && result.NoOp { renderDeployNoOp(pl.ui, pl.plan.Artifact.HostState.CurrentRelease) return nil } - notifyOperationOutcome(cmd.Context(), pl.cfg, g, "deploy", result, err) return err } diff --git a/cmd/ob/github.go b/cmd/ob/github.go new file mode 100644 index 00000000..71457d37 --- /dev/null +++ b/cmd/ob/github.go @@ -0,0 +1,190 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "sync" + + "github.com/labstack/onebox/internal/app" + "github.com/labstack/onebox/internal/engine" + "github.com/labstack/onebox/internal/ghdeploy" + "github.com/labstack/onebox/internal/journal" + "github.com/labstack/onebox/internal/onebox" +) + +// githubAPIBase is the API the reports go to. A variable so tests can point it +// at a fake. +var githubAPIBase = ghdeploy.DefaultBaseURL + +// githubReport is the GitHub side of one deploy, rollback, resume or abort. It is fail-open +// like notifications: every problem is a stderr warning and never the verb's +// result. A nil report does nothing. +type githubReport struct { + reporter *ghdeploy.Reporter + kind onebox.OperationKind + meta ghdeploy.Meta + commits map[string]string + + once sync.Once + pending *ghdeploy.Pending +} + +func githubWarn(message string) { + fmt.Fprintf(os.Stderr, "warn: github: %s\n", message) +} + +// newGitHubReport prepares a report for a deploy, rollback, resume or abort when the project +// names a GitHub repository. Other verbs, and projects without a github block, +// get nil. The token is found only when there is something to report, and off +// the operation's own path. +func newGitHubReport(cfg *app.Resolved, g *globalFlags, request onebox.ExecuteRequest) *githubReport { + if cfg == nil || cfg.GitHub == nil { + return nil + } + switch request.Kind { + case onebox.KindDeploy, onebox.KindRollback, onebox.KindResume, onebox.KindAbort: + default: + return nil + } + tokenEnv := cfg.GitHub.TokenEnv + baseURL := githubAPIBase + if cfg.GitHub.APIURL != "" { + baseURL = cfg.GitHub.APIURL + } + report := &githubReport{ + kind: request.Kind, + meta: ghdeploy.Meta{ + Operator: journal.DefaultOperator(), + Runner: onebox.CurrentRunnerProvenance().Version, + }, + reporter: &ghdeploy.Reporter{ + Client: &ghdeploy.Client{ + BaseURL: baseURL, Repository: cfg.GitHub.Repository, + TokenSource: func(ctx context.Context) (string, error) { + return ghdeploy.ResolveToken(ctx, tokenEnv, cfg.GitHub.APIURL) + }, + }, + Environment: g.Env, + App: cfg.Name, + Warn: githubWarn, + }, + } + if request.Kind == onebox.KindDeploy && request.Plan != nil { + report.commits = request.Plan.Artifact.SourceCommits + report.meta.ReleaseID = request.Plan.Operation.ReleaseID + report.meta.Description = "ob deploy " + report.meta.ReleaseID + } + return report +} + +// events wraps an operation's event sink. A deploy is reported from the +// engine's release event, which follows the journal's deploy start: by then +// the lock, preconditions and preflight have passed and a no-op has returned, +// so a deploy refused before it touched the host is never announced. The sink +// is synchronous, so the report is only started here. +func (r *githubReport) events(ctx context.Context, next onebox.EventSink) onebox.EventSink { + if r == nil || r.kind != onebox.KindDeploy { + return next + } + return func(event onebox.OperationEvent) { + if next != nil { + next(event) + } + if event.Kind == onebox.KindDeploy && event.Phase == "release" { + r.once.Do(func() { + if len(r.commits) == 0 { + githubWarn("not reported: the plan names no commit; push and plan from a clean checkout of the repository, or label the images with org.opencontainers.image.source and org.opencontainers.image.revision") + return + } + r.pending = r.reporter.Start(context.WithoutCancel(ctx), r.commits, r.meta) + }) + } + } +} + +// finish posts the outcome. A deploy's deployments get their final status; a +// rollback is recorded now, because the commits it restores are known only +// once it has resolved its target under the lock. +func (r *githubReport) finish(ctx context.Context, result onebox.OperationResult, err error) { + if r == nil { + return + } + ctx = context.WithoutCancel(ctx) + switch r.kind { + case onebox.KindDeploy: + if r.pending == nil { + return + } + state, description := deployOutcome(r.meta.ReleaseID, err) + r.pending.Finish(ctx, state, description) + case onebox.KindRollback: + if err != nil || result.ReleaseID == "" { + return + } + if len(result.SourceCommits) == 0 { + githubWarn("not reported: release " + result.ReleaseID + " recorded no commits; it was deployed before GitHub reporting was configured") + return + } + meta := r.meta + meta.ReleaseID = result.ReleaseID + meta.Description = "ob rollback to " + result.ReleaseID + r.reporter.Record(ctx, result.SourceCommits, meta, ghdeploy.StateSuccess) + case onebox.KindResume: + // The interrupted deploy's deployments get the outcome it finally + // had; one that is now serving is put on record even when the + // interrupted run never reached GitHub. A release that recorded no + // commits was not reported to begin with, and stays quiet. + if len(result.SourceCommits) == 0 || result.EvidenceID == "" { + return + } + meta := r.meta + meta.ReleaseID = result.EvidenceID + state, description := deployOutcome(result.EvidenceID, err) + meta.Description = "ob resume: " + description + r.reporter.Conclude(ctx, result.SourceCommits, meta, state, err == nil) + case onebox.KindAbort: + if err != nil || len(result.SourceCommits) == 0 || result.EvidenceID == "" { + return + } + meta := r.meta + meta.ReleaseID = result.EvidenceID + meta.Description = "ob abort reverted " + result.EvidenceID + r.reporter.Conclude(ctx, result.SourceCommits, meta, ghdeploy.StateFailure, false) + } +} + +// deployOutcome maps a deploy's result to a deployment status. A failure +// after activation leaves the release serving, which GitHub's failure would +// deny, and an interrupted deploy did not fail on its own terms: both are +// errors. +func deployOutcome(releaseID string, err error) (state, description string) { + var postActivation *engine.PostActivationFailedError + switch { + case err == nil: + return ghdeploy.StateSuccess, "ob deploy " + releaseID + " succeeded" + case errors.As(err, &postActivation): + return ghdeploy.StateError, releaseID + " is serving, but the work after activation did not finish" + case errors.Is(err, context.Canceled): + return ghdeploy.StateError, "ob deploy " + releaseID + " was interrupted; inspect with ob status" + default: + return ghdeploy.StateFailure, "ob deploy " + releaseID + " failed; inspect trusted local diagnostics" + } +} + +// executeAndReport runs one canonical operation and reports its outcome to +// notifications and GitHub. Both deploy paths and every other mutation share +// it, so no verb reports differently from another. +func executeAndReport(ctx context.Context, svc *onebox.Service, cfg *app.Resolved, g *globalFlags, request onebox.ExecuteRequest, verb string) (onebox.OperationResult, error) { + report := newGitHubReport(cfg, g, request) + request.Events = report.events(ctx, request.Events) + result, err := svc.Execute(ctx, request) + // Each reporter is bounded on its own; run together, a dead receiver of + // either costs one bound, not the two added. + var wg sync.WaitGroup + wg.Go(func() { notifyOperationOutcome(ctx, cfg, g, verb, result, err) }) + wg.Go(func() { report.finish(ctx, result, err) }) + wg.Wait() + return result, err +} diff --git a/cmd/ob/github_test.go b/cmd/ob/github_test.go new file mode 100644 index 00000000..2d551266 --- /dev/null +++ b/cmd/ob/github_test.go @@ -0,0 +1,188 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/labstack/onebox/internal/app" + "github.com/labstack/onebox/internal/engine" + "github.com/labstack/onebox/internal/ghdeploy" + "github.com/labstack/onebox/internal/onebox" +) + +const testCommit = "0123456789abcdef0123456789abcdef01234567" + +type recordedCall struct { + Path string + Body map[string]any +} + +func fakeGitHubAPI(t *testing.T) *[]recordedCall { + t.Helper() + var mu sync.Mutex + calls := &[]recordedCall{} + id := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + mu.Lock() + *calls = append(*calls, recordedCall{Path: "GET " + r.URL.Path}) + mu.Unlock() + _, _ = w.Write([]byte(`[]`)) + return + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + mu.Lock() + *calls = append(*calls, recordedCall{Path: r.URL.Path, Body: body}) + id++ + next := id + mu.Unlock() + w.WriteHeader(http.StatusCreated) + _, _ = fmt.Fprintf(w, `{"id":%d}`, next) + })) + t.Cleanup(server.Close) + saved := githubAPIBase + githubAPIBase = server.URL + t.Cleanup(func() { githubAPIBase = saved }) + t.Setenv("ONEBOX_TEST_GH", "token") + return calls +} + +func githubConfig() *app.Resolved { + cfg := &app.Resolved{Spec: &app.Spec{}} + cfg.Name = "shop" + cfg.GitHub = &app.GitHub{Repository: "labstack/shop", TokenEnv: "ONEBOX_TEST_GH"} + return cfg +} + +func deployRequest(commits map[string]string) onebox.ExecuteRequest { + plan := &onebox.DeployPlan{} + plan.Operation.ReleaseID = "20261128-120000-0123456" + plan.Artifact.SourceCommits = commits + return onebox.ExecuteRequest{Kind: onebox.KindDeploy, Plan: plan} +} + +func TestADeployIsReportedFromItsFirstExecuteEvent(t *testing.T) { + calls := fakeGitHubAPI(t) + report := newGitHubReport(githubConfig(), &globalFlags{Env: "production"}, deployRequest(map[string]string{"": testCommit})) + var seen []string + sink := report.events(t.Context(), func(e onebox.OperationEvent) { seen = append(seen, e.Phase) }) + for _, phase := range []string{"operation", "stage", "execute", "release", "release"} { + sink(onebox.OperationEvent{Kind: onebox.KindDeploy, Phase: phase}) + } + if len(seen) != 5 { + t.Fatalf("the wrapped sink must see every event, saw %v", seen) + } + report.finish(t.Context(), onebox.OperationResult{}, nil) + if len(*calls) != 3 { + t.Fatalf("calls = %+v, want one create, in_progress and success", *calls) + } + if got := (*calls)[0].Body["ref"]; got != testCommit { + t.Fatalf("ref = %v", got) + } + if got := (*calls)[2].Body["state"]; got != ghdeploy.StateSuccess { + t.Fatalf("final state = %v", got) + } +} + +func TestADeployThatNeverExecutesIsNotReported(t *testing.T) { + calls := fakeGitHubAPI(t) + report := newGitHubReport(githubConfig(), &globalFlags{Env: "production"}, deployRequest(map[string]string{"": testCommit})) + sink := report.events(t.Context(), nil) + sink(onebox.OperationEvent{Kind: onebox.KindDeploy, Phase: "stage"}) + report.finish(t.Context(), onebox.OperationResult{NoOp: true}, nil) + if len(*calls) != 0 { + t.Fatalf("calls = %+v, want none", *calls) + } +} + +func TestADeployWithoutCommitsIsNotReported(t *testing.T) { + calls := fakeGitHubAPI(t) + report := newGitHubReport(githubConfig(), &globalFlags{Env: "production"}, deployRequest(nil)) + report.events(t.Context(), nil)(onebox.OperationEvent{Kind: onebox.KindDeploy, Phase: "release"}) + report.finish(t.Context(), onebox.OperationResult{}, errors.New("boom")) + if len(*calls) != 0 { + t.Fatalf("calls = %+v, want none", *calls) + } +} + +func TestARollbackRecordsTheRestoredCommits(t *testing.T) { + calls := fakeGitHubAPI(t) + report := newGitHubReport(githubConfig(), &globalFlags{Env: "production"}, onebox.ExecuteRequest{Kind: onebox.KindRollback}) + report.finish(t.Context(), onebox.OperationResult{ReleaseID: "prev", SourceCommits: map[string]string{"shop-web": testCommit}}, nil) + if len(*calls) != 2 { + t.Fatalf("calls = %+v, want a create and a success", *calls) + } + if got := (*calls)[0].Body["environment"]; got != "production (shop-web)" { + t.Fatalf("environment = %v", got) + } + if got := (*calls)[0].Body["payload"].(map[string]any)["release_id"]; got != "prev" { + t.Fatalf("release_id = %v", got) + } + for _, unreported := range []onebox.OperationResult{{ReleaseID: "old"}, {}} { + report.finish(t.Context(), unreported, nil) + } + report.finish(t.Context(), onebox.OperationResult{ReleaseID: "prev", SourceCommits: map[string]string{"": testCommit}}, errors.New("failed")) + if len(*calls) != 2 { + t.Fatalf("calls = %+v, want nothing more", *calls) + } +} + +func TestAResumeConcludesAndAnAbortFailsTheInterruptedDeploy(t *testing.T) { + calls := fakeGitHubAPI(t) + for _, tc := range []struct { + kind onebox.OperationKind + state string + }{{onebox.KindResume, ghdeploy.StateSuccess}, {onebox.KindAbort, ghdeploy.StateFailure}} { + *calls = nil + report := newGitHubReport(githubConfig(), &globalFlags{Env: "production"}, onebox.ExecuteRequest{Kind: tc.kind}) + report.finish(t.Context(), onebox.OperationResult{EvidenceID: "R1", SourceCommits: map[string]string{"shop-web": testCommit}}, nil) + if len(*calls) == 0 || (*calls)[0].Path != "/repos/labstack/shop/deployments" && !strings.HasPrefix((*calls)[0].Path, "GET") { + t.Fatalf("%s: calls = %+v", tc.kind, *calls) + } + last := (*calls)[len(*calls)-1] + if tc.kind == onebox.KindResume && last.Body["state"] != tc.state { + t.Fatalf("%s: final state = %v, want %s", tc.kind, last.Body["state"], tc.state) + } + } + *calls = nil + report := newGitHubReport(githubConfig(), &globalFlags{Env: "production"}, onebox.ExecuteRequest{Kind: onebox.KindResume}) + report.finish(t.Context(), onebox.OperationResult{EvidenceID: "R1"}, nil) + if len(*calls) != 0 { + t.Fatalf("a release without recorded commits is not reported: %+v", *calls) + } +} + +func TestOnlyReleaseOperationsReport(t *testing.T) { + for _, kind := range []onebox.OperationKind{onebox.KindJobRun, onebox.KindSecretsPush, onebox.KindBootstrap} { + if newGitHubReport(githubConfig(), &globalFlags{Env: "production"}, onebox.ExecuteRequest{Kind: kind}) != nil { + t.Fatalf("%s must not report", kind) + } + } + if newGitHubReport(&app.Resolved{Spec: &app.Spec{}}, &globalFlags{Env: "production"}, deployRequest(nil)) != nil { + t.Fatal("a project without a github block must not report") + } +} + +func TestDeployOutcomeStates(t *testing.T) { + for _, tc := range []struct { + err error + want string + }{ + {nil, ghdeploy.StateSuccess}, + {errors.New("verify failed"), ghdeploy.StateFailure}, + {fmt.Errorf("deploy: %w", context.Canceled), ghdeploy.StateError}, + {&engine.PostActivationFailedError{ReleaseID: "r", Err: errors.New("x")}, ghdeploy.StateError}, + } { + if got, _ := deployOutcome("r", tc.err); got != tc.want { + t.Fatalf("deployOutcome(%v) = %s, want %s", tc.err, got, tc.want) + } + } +} diff --git a/internal/app/constraints.go b/internal/app/constraints.go index 072fa72e..447d4819 100644 --- a/internal/app/constraints.go +++ b/internal/app/constraints.go @@ -105,6 +105,9 @@ var ( gRegistryHost = grammar{"registry server", regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]*(:[0-9]{1,5})?(/[A-Za-z0-9._/-]*)?$`), "a host with an optional port and path, such as ghcr.io or registry.example.com:5000"} + gGitHubRepository = grammar{"GitHub repository", regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}$`), + "owner/name, such as labstack/shop"} + gRegistryUser = grammar{"registry username", regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._@+-]*$`), "a username of letters, digits and . _ @ + -"} diff --git a/internal/app/jsonschema.go b/internal/app/jsonschema.go index fce4ab66..09a856b2 100644 --- a/internal/app/jsonschema.go +++ b/internal/app/jsonschema.go @@ -605,6 +605,10 @@ var schemaConstraints = []struct { {[]string{"registries", "*", "server"}, pattern(gRegistryHost)}, {[]string{"registries", "*", "username"}, pattern(gRegistryUser)}, {[]string{"registries", "*", "password_env"}, pattern(gEnvName)}, + {[]string{"github", "repository"}, pattern(gGitHubRepository)}, + {[]string{"github", "token_env"}, pattern(gEnvName)}, + {[]string{"github", "api_url"}, pattern(gHTTPURL)}, + {[]string{"github"}, map[string]any{"required": []any{"repository"}}}, {[]string{"notifications", "*", "format"}, enum(eNotifyFormat)}, {[]string{"notifications", "*", "signing_secret_env"}, pattern(gEnvName)}, // Format defaults to text, so a signed notification has to say JSON. diff --git a/internal/app/load_test.go b/internal/app/load_test.go index 9dfa82c0..630264ff 100644 --- a/internal/app/load_test.go +++ b/internal/app/load_test.go @@ -1103,3 +1103,44 @@ spec: t.Fatalf("error = %v, want a refusal at notifications.facet.format", err) } } + +// The github block names the repository deploys are reported to; the token +// stays a variable name, like every other credential in the project file. +func TestGitHubProjectFile(t *testing.T) { + project := func(github string) []byte { + return []byte(`apiVersion: onebox.run/v1alpha2 +kind: Application +metadata: + name: shop +spec: + environments: {production: {server: root@203.0.113.10}} + workloads: + web: {image: nginx} + github: ` + github + ` +`) + } + spec, err := loadFixtureBytes(project(`{repository: labstack/shop, tokenEnv: SHOP_GH_TOKEN, apiUrl: "https://ghe.example.com/api/v3"}`), "ob.yml") + if err != nil { + t.Fatal(err) + } + if spec.GitHub == nil || spec.GitHub.Repository != "labstack/shop" || spec.GitHub.TokenEnv != "SHOP_GH_TOKEN" || spec.GitHub.APIURL != "https://ghe.example.com/api/v3" { + t.Fatalf("github = %+v", spec.GitHub) + } + spec, err = loadFixtureBytes([]byte(strings.Replace(string(project(`{repository: x/y}`)), " github: {repository: x/y}\n", "", 1)), "ob.yml") + if err != nil || spec.GitHub != nil { + t.Fatalf("absent block: github = %+v, err = %v", spec.GitHub, err) + } + for value, path := range map[string]string{ + `{repository: shop}`: "github.repository", + `{repository: "https://github.com/x/y"}`: "github.repository", + `{repository: x/y, tokenEnv: "not a name"}`: "github.tokenEnv", + `{tokenEnv: GH_TOKEN}`: "repository", + `{repository: x/y, token: abc}`: "token", + `{repository: x/y, apiUrl: "http://ghe.example.com/api/v3"}`: "github.apiUrl", + `{repository: x/y, apiUrl: "ghe.example.com"}`: "github.apiUrl", + } { + if _, err := loadFixtureBytes(project(value), "ob.yml"); err == nil || !strings.Contains(err.Error(), path) { + t.Fatalf("github: %s: error = %v, want a refusal naming %s", value, err, path) + } + } +} diff --git a/internal/app/types.go b/internal/app/types.go index 420ec79d..252a8983 100644 --- a/internal/app/types.go +++ b/internal/app/types.go @@ -52,6 +52,7 @@ type Spec struct { Hooks map[string]Command `json:"hooks,omitempty" description:"Lifecycle commands keyed by seam: bootstrap, pre_release, post_release, or post_deploy."` Checks Checks `json:"checks,omitzero" description:"Assertions that must pass before a release becomes current unless marked advisory."` Notifications map[string]Notification `json:"notifications,omitempty" description:"Named webhooks that receive selected operation and scheduled-job outcomes."` + GitHub *GitHub `json:"github,omitempty" description:"Report deploys and rollbacks to a GitHub repository's deployments, so they show in its Environments tab and reach tools that read deployment statuses."` Registries map[string]Registry `json:"registries,omitempty" description:"Named container registries and the environment variables holding their credentials."` Proxy Proxy `json:"proxy" description:"Ownership and configuration of the host ingress proxy."` @@ -523,6 +524,15 @@ type Notification struct { SigningSecretEnv string `json:"signing_secret_env,omitempty" description:"Local environment-variable name containing a Standard Webhooks signing secret (whsec_ followed by base64). When set, each request carries webhook-id, webhook-timestamp and webhook-signature headers, and a send is retried at most three times within 15 seconds on a network error, 429 or 5xx. Requires format JSON. A missing or malformed secret is a warning, never a blocked operation: the command does not send that notification, and a scheduled job keeps signing with the keys its last deploy wrote. Notifications are sent concurrently, so several dead receivers still cost one 15-second bound." example:"ONEBOX_WEBHOOK_SECRET"` } +// GitHub names the repository deploys are reported to. The token stays in the +// operator's environment: it is read where `ob` runs and never reaches a host, +// so scheduled jobs and other host-fired work do not report. +type GitHub struct { + Repository string `json:"repository" description:"GitHub repository, as owner/name, whose deployments record each deploy and rollback. Workload images whose org.opencontainers.image.source label names this repository are reported at their org.opencontainers.image.revision commit; when none does, the clean checkout's commit is reported if the checkout is a clone of this repository. Each image repository is reported in its own GitHub environment, named like production (shop-web); a configuration-only repository is named after the application." example:"labstack/shop"` + APIURL string `json:"api_url,omitempty" description:"GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. A github.com token is never sent to another host: there the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host." default:"https://api.github.com" example:"https://github.example.com/api/v3"` + TokenEnv string `json:"token_env,omitempty" description:"Local environment-variable name containing a GitHub token with Deployments write access. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation." example:"GH_TOKEN"` +} + type Registry struct { Server string `json:"server" description:"Registry hostname, optionally with a port." example:"ghcr.io"` Username string `json:"username,omitempty" description:"Registry login username."` diff --git a/internal/app/validate.go b/internal/app/validate.go index 9d7c741b..3e8169af 100644 --- a/internal/app/validate.go +++ b/internal/app/validate.go @@ -205,6 +205,21 @@ func validateTopLevel(p *Spec) error { "a signed notification sends the JSON payload; set format: JSON beside signingSecretEnv") } } + if p.GitHub != nil { + if err := gGitHubRepository.check("github.repository", p.GitHub.Repository); err != nil { + return err + } + if err := gHTTPURL.checkOptional("github.api_url", p.GitHub.APIURL); err != nil { + return err + } + if p.GitHub.APIURL != "" && !strings.HasPrefix(p.GitHub.APIURL, "https://") { + // The token travels in a header on every request. + return errf("project_invalid", "github.api_url", "", "%q must use https, because every request carries the token", p.GitHub.APIURL) + } + if err := gEnvName.checkOptional("github.token_env", p.GitHub.TokenEnv); err != nil { + return err + } + } for _, name := range sortedKeys(p.Hooks) { // A hook key is either a lifecycle seam the engine invokes, or the name // of a declared job — `hooks: {migrate: {run: ...}}` replaces the command diff --git a/internal/engine/deploy.go b/internal/engine/deploy.go index 700fb043..0785c711 100644 --- a/internal/engine/deploy.go +++ b/internal/engine/deploy.go @@ -160,7 +160,7 @@ func (e *Engine) deployCore(ctx context.Context, releaseID, localStagingDir stri jw := &journal.Writer{ T: e.T, Dir: journal.Dir(e.names()), DeployID: releaseID, Epoch: epoch, - Operator: journal.DefaultOperator(), GitSHA: e.Opts.GitSHA, ConfigHash: e.Opts.ConfigHash, + Operator: journal.DefaultOperator(), GitSHA: e.Opts.GitSHA, SourceCommits: e.Opts.SourceCommits, ConfigHash: e.Opts.ConfigHash, ApprovalDigest: e.Opts.ApprovalDigest, ApprovalClass: e.Opts.ApprovalClass, ApprovedBy: e.Opts.ApprovedBy, ApprovalSource: e.Opts.ApprovalSource, AllowUnknownMigration: e.Opts.AllowUnknownMigration, @@ -176,6 +176,11 @@ func (e *Engine) deployCore(ctx context.Context, releaseID, localStagingDir stri if err := jw.Append(ctx, journal.Record{Phase: "deploy", Event: "start", Detail: "prev=" + prev}); err != nil { return fmt.Errorf("journal deploy start: %w", err) } + // The first point at which this deploy is on the host's record: the lock, + // preconditions and preflight have passed. Reporters that announce a + // deploy outside the host start here, so a refused deploy is never + // announced. + e.progress("release", "started", "") if done == nil { // Persist a safe baseline before transfer. If the runner dies during // upload, no rollback-relevant effect could have started yet; later diff --git a/internal/engine/deploy_test.go b/internal/engine/deploy_test.go index 4021b9af..43802b78 100644 --- a/internal/engine/deploy_test.go +++ b/internal/engine/deploy_test.go @@ -496,6 +496,7 @@ func TestDeployEmitsVerificationAndActivationProgress(t *testing.T) { t.Fatalf("deploy: %v", err) } want := []string{ + "release:started:", "verification:started:", "verification:succeeded:", "activation:started:", diff --git a/internal/engine/engine.go b/internal/engine/engine.go index 0b4bc542..16c5aa7d 100644 --- a/internal/engine/engine.go +++ b/internal/engine/engine.go @@ -46,6 +46,10 @@ type Options struct { // GitSHA and ConfigHash ride into the journal and lock metadata. GitSHA string ConfigHash string + // SourceCommits are the full commits this release ships, keyed by + // component. They ride on a deploy's start record so a later rollback can + // report what it restores. + SourceCommits map[string]string // Approval fields are the exact plan-bound grant accepted by the canonical // execution boundary. They ride on every deploy journal record. ApprovalDigest string diff --git a/internal/engine/image_source.go b/internal/engine/image_source.go new file mode 100644 index 00000000..dea17cc7 --- /dev/null +++ b/internal/engine/image_source.go @@ -0,0 +1,123 @@ +package engine + +import ( + "context" + "encoding/json" + "sort" + "strings" + + "github.com/labstack/onebox/internal/journal" +) + +// The OCI annotation keys a build stamps on an image to say where it came +// from. docker/metadata-action computes both; they reach the image when its +// labels output is passed to the build. Manifest annotations are not read. +const ( + labelImageSource = "org.opencontainers.image.source" + labelImageRevision = "org.opencontainers.image.revision" +) + +// ImageSource is an image's declared provenance: the repository URL and the +// commit it was built from. Either is empty when the image does not say. +// Unknown marks an image whose labels could not be read at all, which is not +// the same as an image that declares nothing. +type ImageSource struct { + Source string + Revision string + Unknown bool +} + +// ImageSources reads the provenance labels of pinned workload images, keyed by +// workload. Every pinned workload is present. An image that cannot be +// inspected, or whose platforms disagree about where they came from, is +// Unknown. It never fails: provenance never decides whether a release ships. +func (e *Engine) ImageSources(ctx context.Context, pins map[string]string) map[string]ImageSource { + out := map[string]ImageSource{} + byRef := map[string]*ImageSource{} + workloads := make([]string, 0, len(pins)) + for workload := range pins { + workloads = append(workloads, workload) + } + sort.Strings(workloads) + for _, workload := range workloads { + ref := pins[workload] + source, seen := byRef[ref] + if !seen { + source = e.inspectImageSource(ctx, ref) + byRef[ref] = source + } + if source != nil { + out[workload] = *source + } else { + out[workload] = ImageSource{Unknown: true} + } + } + return out +} + +func (e *Engine) inspectImageSource(ctx context.Context, ref string) *ImageSource { + res, err := e.T.Run(ctx, "docker buildx imagetools inspect "+q(ref)+" --format '{{json .Image}}'") + if err != nil || res.ExitCode != 0 { + return nil + } + return parseImageSource([]byte(res.Stdout)) +} + +type imageConfig struct { + Config struct { + Labels map[string]string `json:"Labels"` + } `json:"config"` +} + +// parseImageSource accepts both shapes imagetools prints for .Image: one +// image config, or a map of platform to config for an index. An index counts +// only when every platform declares the same provenance. +func parseImageSource(raw []byte) *ImageSource { + var probe map[string]json.RawMessage + if json.Unmarshal(raw, &probe) != nil { + return nil + } + var configs []imageConfig + if _, single := probe["config"]; single { + var c imageConfig + if json.Unmarshal(raw, &c) != nil { + return nil + } + configs = append(configs, c) + } else { + for _, platform := range probe { + var c imageConfig + if json.Unmarshal(platform, &c) != nil { + return nil + } + configs = append(configs, c) + } + } + if len(configs) == 0 { + return nil + } + var found *ImageSource + for _, c := range configs { + s := ImageSource{ + Source: strings.TrimSpace(c.Config.Labels[labelImageSource]), + Revision: strings.TrimSpace(c.Config.Labels[labelImageRevision]), + } + if found == nil { + found = &s + } else if *found != s { + return nil + } + } + return found +} + +// ReleaseSourceCommits returns the source commits a release's own deploy +// recorded, or nil for a release deployed before they were recorded or +// without a github block. +func (e *Engine) ReleaseSourceCommits(ctx context.Context, releaseID string) (map[string]string, error) { + records, err := journal.Read(ctx, e.T, journal.Dir(e.names()), releaseID) + if err != nil { + return nil, err + } + return journal.Summarize(records).SourceCommits, nil +} diff --git a/internal/engine/image_source_test.go b/internal/engine/image_source_test.go new file mode 100644 index 00000000..796facda --- /dev/null +++ b/internal/engine/image_source_test.go @@ -0,0 +1,28 @@ +package engine + +import "testing" + +func TestParseImageSourceReadsSingleAndIndexConfigs(t *testing.T) { + const rev = "0123456789abcdef0123456789abcdef01234567" + labels := `{"org.opencontainers.image.source":"https://github.com/labstack/monk","org.opencontainers.image.revision":"` + rev + `"}` + other := `{"org.opencontainers.image.source":"https://github.com/labstack/monk","org.opencontainers.image.revision":"fedcba9876543210fedcba9876543210fedcba98"}` + for name, tc := range map[string]struct { + raw string + want *ImageSource + }{ + "single": {`{"config":{"Labels":` + labels + `}}`, &ImageSource{Source: "https://github.com/labstack/monk", Revision: rev}}, + "index agrees": {`{"linux/amd64":{"config":{"Labels":` + labels + `}},"linux/arm64":{"config":{"Labels":` + labels + `}}}`, &ImageSource{Source: "https://github.com/labstack/monk", Revision: rev}}, + "index disagrees": {`{"linux/amd64":{"config":{"Labels":` + labels + `}},"linux/arm64":{"config":{"Labels":` + other + `}}}`, nil}, + "no labels": {`{"config":{}}`, &ImageSource{}}, + "not json": {`ERROR: not found`, nil}, + "empty index": {`{}`, nil}, + "platform not image": {`{"linux/amd64":"x"}`, nil}, + } { + t.Run(name, func(t *testing.T) { + got := parseImageSource([]byte(tc.raw)) + if (got == nil) != (tc.want == nil) || (got != nil && *got != *tc.want) { + t.Fatalf("parseImageSource = %+v, want %+v", got, tc.want) + } + }) + } +} diff --git a/internal/engine/plan.go b/internal/engine/plan.go index 41d75d2f..6386e952 100644 --- a/internal/engine/plan.go +++ b/internal/engine/plan.go @@ -47,7 +47,11 @@ type Artifact struct { // digest *after* the render, so re-rendering with the pins produces a // different document than the one this plan bound. Execution reloads with // these and applies the pins afterwards, exactly as planning did. - BuildImages map[string]string `json:"build_images,omitempty"` + BuildImages map[string]string `json:"build_images,omitempty"` + // SourceCommits are the full commits this release ships, keyed by + // component, for reporting outside the host. Planned only for a project + // that reports to GitHub; see onebox.sourceCommits. + SourceCommits map[string]string `json:"source_commits,omitempty"` SecretGeneration string `json:"secret_generation,omitempty"` RenderedCompose string `json:"rendered_compose"` Commands []string `json:"commands"` diff --git a/internal/ghdeploy/ghdeploy.go b/internal/ghdeploy/ghdeploy.go new file mode 100644 index 00000000..3600933b --- /dev/null +++ b/internal/ghdeploy/ghdeploy.go @@ -0,0 +1,375 @@ +// Package ghdeploy reports deploys and rollbacks to a GitHub repository's +// deployments, so they show in its Environments tab and reach every tool that +// reads deployment statuses. +// +// It runs where `ob` runs. The token comes from the operator's environment and +// never travels to a host, which is why host-fired work such as scheduled +// jobs does not report. +// +// Fail-open is the contract, as for notifications: every problem is a warning +// for the caller to print, and no GitHub call can fail, block or slow an +// operation beyond Budget. Warnings never carry the token. +package ghdeploy + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "strings" + "sync" + "time" +) + +// DefaultBaseURL is the GitHub REST API. +const DefaultBaseURL = "https://api.github.com" + +// apiVersion pins the REST API contract the requests are written against. +const apiVersion = "2022-11-28" + +// Attempts and Budget bound one GitHub call, including retries: at most +// Attempts requests, all within Budget. They match signed notifications. +const ( + Attempts = 3 + Budget = 15 * time.Second +) + +// Variables so tests can exercise the bounds without waiting for them. +var ( + attemptTimeout = 5 * time.Second + budget = Budget + backoff = []time.Duration{500 * time.Millisecond, time.Second} +) + +// WebHost is the GitHub host whose repositories an API base URL serves: +// github.com for the public API, SUBDOMAIN.ghe.com for +// https://api.SUBDOMAIN.ghe.com, and the server itself for GitHub Enterprise +// Server's https://HOST/api/v3. +func WebHost(apiURL string) string { + if apiURL == "" { + return "github.com" + } + u, err := url.Parse(apiURL) + if err != nil || u.Host == "" { + return "github.com" + } + host := strings.ToLower(u.Host) + // Only github.com and ghe.com serve their API from an api. subdomain; + // Enterprise Server serves it under /api/v3 on its own host, whatever + // that host is called. + if rest, ok := strings.CutPrefix(host, "api."); ok && (rest == "github.com" || strings.HasSuffix(rest, ".ghe.com")) { + return rest + } + return host +} + +// Client calls the GitHub deployments API for one repository. +type Client struct { + BaseURL string + Repository string + HTTP *http.Client + // Token authenticates every request. When it is empty, TokenSource is + // asked once, on the first request, so finding a token never sits on the + // path of the operation being reported. + Token string + TokenSource func(context.Context) (string, error) + + tokenOnce sync.Once + tokenErr error +} + +// token returns the request token, resolving it once. +func (c *Client) token(ctx context.Context) (string, error) { + c.tokenOnce.Do(func() { + if c.Token == "" && c.TokenSource != nil { + c.Token, c.tokenErr = c.TokenSource(ctx) + } + if c.tokenErr == nil && c.Token == "" { + c.tokenErr = errors.New("no token") + } + }) + return c.Token, c.tokenErr +} + +// Deployment is one deployment to create. Ref is a full commit. +type Deployment struct { + Ref string + Environment string + Production bool + Description string + Payload map[string]string +} + +// APIError is GitHub refusing a request. Message is GitHub's own message, +// which names the problem and never echoes the token. +type APIError struct { + Status int + Message string +} + +func (e *APIError) Error() string { + if e.Message == "" { + return fmt.Sprintf("GitHub returned %d", e.Status) + } + return fmt.Sprintf("GitHub returned %d: %s", e.Status, e.Message) +} + +// CreateDeployment creates a deployment and returns its id. auto_merge is off +// so GitHub never merges the default branch into the ref, and no status +// contexts are required: the operator already chose to deploy this commit, +// and Onebox records that it did rather than second-guessing it. +func (c *Client) CreateDeployment(ctx context.Context, d Deployment) (int64, error) { + body := map[string]any{ + "ref": d.Ref, + "environment": d.Environment, + "auto_merge": false, + "required_contexts": []string{}, + "production_environment": d.Production, + "transient_environment": false, + "description": truncate(d.Description, 140), + "task": "deploy", + } + if len(d.Payload) > 0 { + body["payload"] = d.Payload + } + var created struct { + ID int64 `json:"id"` + } + // Creating is not idempotent: a request GitHub may have accepted is not + // sent again, or the environment would gain a deployment that never gets + // a status. + if err := c.do(ctx, "/repos/"+c.Repository+"/deployments", body, &created, false); err != nil { + return 0, err + } + if created.ID == 0 { + return 0, errors.New("GitHub created no deployment") + } + return created.ID, nil +} + +// CreateStatus posts a deployment status: in_progress, success, failure or +// error. +func (c *Client) CreateStatus(ctx context.Context, id int64, state, description string) error { + body := map[string]any{ + "state": state, + "description": truncate(description, 140), + } + return c.do(ctx, fmt.Sprintf("/repos/%s/deployments/%d/statuses", c.Repository, id), body, nil, true) +} + +// Existing is a deployment as GitHub lists it. +type Existing struct { + ID int64 `json:"id"` + Payload map[string]string `json:"-"` + Raw json.RawMessage `json:"payload"` +} + +// ListDeployments lists the newest deployments of a commit to an environment. +func (c *Client) ListDeployments(ctx context.Context, sha, environment string) ([]Existing, error) { + q := url.Values{"sha": {sha}, "environment": {environment}, "per_page": {"30"}} + var listed []Existing + if err := c.send(ctx, http.MethodGet, "/repos/"+c.Repository+"/deployments?"+q.Encode(), nil, &listed, true); err != nil { + return nil, err + } + for i := range listed { + // A payload Onebox did not write may be any JSON; only an object of + // strings is Onebox's. + var payload map[string]string + if json.Unmarshal(listed[i].Raw, &payload) == nil { + listed[i].Payload = payload + } + } + return listed, nil +} + +// do POSTs with bounded retries. A 429, or a connection that was never made, +// is always retried: GitHub did not act on it. A timeout or 5xx is retried +// only for an idempotent request, because GitHub may have acted before +// failing. Any other refusal will be refused again and is returned at once. +func (c *Client) do(ctx context.Context, path string, body any, out any, idempotent bool) error { + return c.send(ctx, http.MethodPost, path, body, out, idempotent) +} + +// send makes one logical request with the bounded retries described on do. +// A nil body sends none. +func (c *Client) send(ctx context.Context, method, path string, body any, out any, idempotent bool) error { + var raw []byte + if body != nil { + var err error + if raw, err = json.Marshal(body); err != nil { + return err + } + } + token, err := c.token(ctx) + if err != nil { + return err + } + parent := ctx + ctx, cancel := context.WithTimeout(ctx, budget) + defer cancel() + var lastErr error + for attempt := 1; attempt <= Attempts; attempt++ { + retry, err := c.post(ctx, method, token, path, raw, out) + if err == nil { + return nil + } + lastErr = err + if retry == retryIfIdempotent { + retry = retryIf(idempotent) + } + if retry != retryAlways || attempt == Attempts || ctx.Err() != nil { + break + } + select { + case <-ctx.Done(): + case <-time.After(backoff[attempt-1]): + } + if ctx.Err() != nil { + break + } + } + if errors.Is(ctx.Err(), context.DeadlineExceeded) && parent.Err() == nil { + return fmt.Errorf("GitHub did not answer within %s: %w", budget, lastErr) + } + return lastErr +} + +// retryKind says whether a failed attempt may be sent again. +type retryKind int + +const ( + retryNever retryKind = iota + retryAlways + retryIfIdempotent +) + +func retryIf(ok bool) retryKind { + if ok { + return retryAlways + } + return retryNever +} + +func (c *Client) post(ctx context.Context, method, token, path string, body []byte, out any) (retry retryKind, err error) { + base := strings.TrimSuffix(c.BaseURL, "/") + if base == "" { + base = DefaultBaseURL + } + var reader io.Reader + if body != nil { + reader = bytes.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, base+path, reader) + if err != nil { + return retryNever, err + } + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("Authorization", "Bearer "+token) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + req.Header.Set("User-Agent", "onebox") + req.Header.Set("X-GitHub-Api-Version", apiVersion) + client := c.HTTP + if client == nil { + client = &http.Client{Timeout: attemptTimeout} + } + res, err := client.Do(req) + if err != nil { + // A transport error names the API URL, never the token, which + // travels only in a header. A failed dial never reached GitHub. + var opErr *net.OpError + if errors.As(err, &opErr) && opErr.Op == "dial" { + return retryAlways, fmt.Errorf("GitHub request failed: %w", err) + } + return retryIfIdempotent, fmt.Errorf("GitHub request failed: %w", err) + } + defer res.Body.Close() + payload, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10)) + if res.StatusCode < 200 || res.StatusCode > 299 { + var refusal struct { + Message string `json:"message"` + } + _ = json.Unmarshal(payload, &refusal) + apiErr := &APIError{Status: res.StatusCode, Message: truncate(strings.TrimSpace(refusal.Message), 200)} + switch { + case res.StatusCode == http.StatusTooManyRequests, + // GitHub signals a secondary rate limit with 403 as well; like a + // 429, the request was not acted on. + res.StatusCode == http.StatusForbidden && (res.Header.Get("Retry-After") != "" || + strings.Contains(strings.ToLower(apiErr.Message), "rate limit")): + return retryAlways, apiErr + case res.StatusCode >= 500: + return retryIfIdempotent, apiErr + default: + return retryNever, apiErr + } + } + if out != nil { + if err := json.Unmarshal(payload, out); err != nil { + return retryNever, fmt.Errorf("read GitHub response: %w", err) + } + } + return retryNever, nil +} + +// ResolveToken finds the operator's token for the API at apiURL ("" is +// api.github.com). For github.com it is the variable named by tokenEnv, +// otherwise GH_TOKEN, GITHUB_TOKEN, then `gh auth token`. +// +// Any other host is named by the project file, so it never receives a +// github.com token: there it is tokenEnv (which may not name GH_TOKEN or +// GITHUB_TOKEN), otherwise GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, then +// `gh auth token --hostname HOST`, which gh answers only with that host's +// token. Errors describe where it looked, never a value. +func ResolveToken(ctx context.Context, tokenEnv, apiURL string) (string, error) { + host := WebHost(apiURL) + public := host == "github.com" + if tokenEnv != "" { + if !public && (tokenEnv == "GH_TOKEN" || tokenEnv == "GITHUB_TOKEN") { + return "", fmt.Errorf("github.tokenEnv %s holds a github.com token and is never sent to %s; name a variable holding a token for that host", tokenEnv, host) + } + if v := strings.TrimSpace(os.Getenv(tokenEnv)); v != "" { + return v, nil + } + return "", fmt.Errorf("token env var %s is empty; export a token with Deployments write access", tokenEnv) + } + names := []string{"GH_TOKEN", "GITHUB_TOKEN"} + if !public { + names = []string{"GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"} + } + for _, name := range names { + if v := strings.TrimSpace(os.Getenv(name)); v != "" { + return v, nil + } + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + gh := exec.CommandContext(ctx, "gh", "auth", "token", "--hostname", host) + // A helper gh starts can hold stdout open after gh is killed; stop + // waiting for it shortly after the deadline. + gh.WaitDelay = time.Second + out, err := gh.Output() + if v := strings.TrimSpace(string(out)); err == nil && v != "" { + return v, nil + } + return "", fmt.Errorf("no token for %s: set %s, name one with github.tokenEnv, or run `gh auth login --hostname %s`", host, strings.Join(names, " or "), host) +} + +func truncate(s string, n int) string { + if len(s) <= n { + return s + } + cut := n + for cut > 0 && (s[cut]&0xC0) == 0x80 { + cut-- + } + return s[:cut] +} diff --git a/internal/ghdeploy/ghdeploy_test.go b/internal/ghdeploy/ghdeploy_test.go new file mode 100644 index 00000000..51fd9af2 --- /dev/null +++ b/internal/ghdeploy/ghdeploy_test.go @@ -0,0 +1,368 @@ +package ghdeploy + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" +) + +const commit = "0123456789abcdef0123456789abcdef01234567" + +type call struct { + Path string + Auth string + Body map[string]any +} + +type fakeGitHub struct { + mu sync.Mutex + calls []call + nextID int64 + deployments []map[string]any + // respond, when set, overrides the answer to one call. + respond func(path string, body map[string]any) (int, string) +} + +func (f *fakeGitHub) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + f.mu.Lock() + var listed []map[string]any + for _, d := range f.deployments { + if d["sha"] == r.URL.Query().Get("sha") && d["environment"] == r.URL.Query().Get("environment") { + listed = append(listed, d) + } + } + f.calls = append(f.calls, call{Path: "GET " + r.URL.Path, Auth: r.Header.Get("Authorization")}) + f.mu.Unlock() + _ = json.NewEncoder(w).Encode(listed) + return + } + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + f.mu.Lock() + f.calls = append(f.calls, call{Path: r.URL.Path, Auth: r.Header.Get("Authorization"), Body: body}) + f.nextID++ + id := f.nextID + if strings.HasSuffix(r.URL.Path, "/deployments") && f.respond == nil { + f.deployments = append(f.deployments, map[string]any{"id": id, "sha": body["ref"], "environment": body["environment"], "payload": body["payload"]}) + } + respond := f.respond + f.mu.Unlock() + if respond != nil { + if status, msg := respond(r.URL.Path, body); status != 0 { + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"message":"` + msg + `"}`)) + return + } + } + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(map[string]any{"id": id}) +} + +func (f *fakeGitHub) paths() []string { + f.mu.Lock() + defer f.mu.Unlock() + var out []string + for _, c := range f.calls { + out = append(out, c.Path) + } + slices.Sort(out) + return out +} + +func newReporter(t *testing.T, f *fakeGitHub, environment string) (*Reporter, *[]string) { + t.Helper() + server := httptest.NewServer(f) + t.Cleanup(server.Close) + var mu sync.Mutex + warnings := &[]string{} + return &Reporter{ + Client: &Client{BaseURL: server.URL, Token: "secret-token", Repository: "labstack/shop"}, + Environment: environment, + App: "shop", + Warn: func(s string) { + mu.Lock() + defer mu.Unlock() + *warnings = append(*warnings, s) + }, + }, warnings +} + +func TestStartThenFinishCreatesAndMarksEachComponent(t *testing.T) { + f := &fakeGitHub{} + r, warnings := newReporter(t, f, "production") + commits := map[string]string{"monk-web": commit, "monk-server": strings.Repeat("b", 40)} + p := r.Start(t.Context(), commits, Meta{ReleaseID: "20261128-120000-abc1234", Description: "ob deploy"}) + p.Finish(t.Context(), StateSuccess, "ob deploy succeeded") + if len(*warnings) != 0 { + t.Fatalf("warnings: %v", *warnings) + } + f.mu.Lock() + defer f.mu.Unlock() + if len(f.calls) != 6 { + t.Fatalf("calls = %d, want 2 creates + 2 in_progress + 2 success", len(f.calls)) + } + environments := map[string]bool{} + states := map[string]int{} + for _, c := range f.calls { + if c.Auth != "Bearer secret-token" { + t.Fatalf("Authorization = %q", c.Auth) + } + if c.Path == "/repos/labstack/shop/deployments" { + if c.Body["auto_merge"] != false || len(c.Body["required_contexts"].([]any)) != 0 || c.Body["production_environment"] != true { + t.Fatalf("create body = %v", c.Body) + } + if p := c.Body["payload"].(map[string]any); p["release_id"] != "20261128-120000-abc1234" || p["environment"] != "production" || p["commit_source"] != "image" { + t.Fatalf("payload = %v", c.Body["payload"]) + } + environments[c.Body["environment"].(string)] = true + continue + } + states[c.Body["state"].(string)]++ + } + if !environments["production (monk-web)"] || !environments["production (monk-server)"] { + t.Fatalf("environments = %v", environments) + } + if states[StateInProgress] != 2 || states[StateSuccess] != 2 { + t.Fatalf("states = %v", states) + } +} + +func TestAConfigurationOnlyRepositoryIsNamedAfterTheApplication(t *testing.T) { + f := &fakeGitHub{} + r, _ := newReporter(t, f, "staging") + r.Record(t.Context(), map[string]string{"": commit}, Meta{Description: "ob rollback"}, StateSuccess) + f.mu.Lock() + defer f.mu.Unlock() + if got := f.calls[0].Body["environment"]; got != "staging (shop)" { + t.Fatalf("environment = %v", got) + } + payload := f.calls[0].Body["payload"].(map[string]any) + if payload["environment"] != "staging" || payload["component"] != "shop" || payload["commit_source"] != "checkout" { + t.Fatalf("payload = %v", payload) + } + if f.calls[0].Body["production_environment"] != false { + t.Fatalf("staging is not production: %v", f.calls[0].Body) + } + if got := f.calls[1].Body["state"]; got != StateSuccess { + t.Fatalf("state = %v", got) + } +} + +func TestAnUnknownCommitWarnsAndSkipsItsStatuses(t *testing.T) { + f := &fakeGitHub{respond: func(path string, _ map[string]any) (int, string) { + if strings.HasSuffix(path, "/deployments") { + return 422, "No ref found for: " + commit + } + return 0, "" + }} + r, warnings := newReporter(t, f, "production") + r.Start(t.Context(), map[string]string{"": commit}, Meta{}).Finish(t.Context(), StateSuccess, "") + if got := f.paths(); len(got) != 1 { + t.Fatalf("calls = %v, want only the refused create", got) + } + if len(*warnings) != 1 || !strings.Contains((*warnings)[0], "is the commit pushed?") || strings.Contains((*warnings)[0], "secret-token") { + t.Fatalf("warnings = %v", *warnings) + } +} + +func TestServerErrorsAreRetriedOnlyWhereRepeatingIsSafe(t *testing.T) { + saved := backoff + backoff = []time.Duration{time.Millisecond, time.Millisecond} + t.Cleanup(func() { backoff = saved }) + var mu sync.Mutex + creates, statuses := 0, 0 + f := &fakeGitHub{respond: func(path string, _ map[string]any) (int, string) { + mu.Lock() + defer mu.Unlock() + if strings.HasSuffix(path, "/deployments") { + creates++ + if creates == 1 { + // GitHub may have created it before failing: never resent. + return 502, "bad gateway" + } + return 0, "" + } + statuses++ + if statuses < 3 { + return 502, "bad gateway" + } + return 0, "" + }} + r, warnings := newReporter(t, f, "production") + r.Record(t.Context(), map[string]string{"": commit}, Meta{}, StateSuccess) + if creates != 1 || len(*warnings) != 1 { + t.Fatalf("a failed create must not be resent: creates = %d, warnings = %v", creates, *warnings) + } + r.Record(t.Context(), map[string]string{"": commit}, Meta{}, StateSuccess) + if creates != 2 || statuses != 3 || len(*warnings) != 1 { + t.Fatalf("a status is idempotent and retried: creates = %d, statuses = %d, warnings = %v", creates, statuses, *warnings) + } +} + +func TestA429IsRetriedEvenForACreate(t *testing.T) { + saved := backoff + backoff = []time.Duration{time.Millisecond, time.Millisecond} + t.Cleanup(func() { backoff = saved }) + var mu sync.Mutex + creates := 0 + f := &fakeGitHub{respond: func(path string, _ map[string]any) (int, string) { + mu.Lock() + defer mu.Unlock() + if strings.HasSuffix(path, "/deployments") { + creates++ + if creates == 1 { + return 429, "secondary rate limit" + } + } + return 0, "" + }} + r, warnings := newReporter(t, f, "production") + r.Record(t.Context(), map[string]string{"": commit}, Meta{}, StateSuccess) + if creates != 2 || len(*warnings) != 0 { + t.Fatalf("creates = %d, warnings = %v", creates, *warnings) + } +} + +func TestATokenThatCannotBeFoundIsOneWarningAndNoCalls(t *testing.T) { + f := &fakeGitHub{} + r, warnings := newReporter(t, f, "production") + r.Client.Token = "" + r.Client.TokenSource = func(context.Context) (string, error) { return "", errors.New("no token: run gh auth login") } + r.Start(t.Context(), map[string]string{"a": commit, "b": commit}, Meta{}).Finish(t.Context(), StateSuccess, "") + if len(f.paths()) != 0 || len(*warnings) != 1 || !strings.Contains((*warnings)[0], "not reported: no token") { + t.Fatalf("calls = %v, warnings = %v", f.paths(), *warnings) + } +} + +func TestARefusalIsNotRetried(t *testing.T) { + attempts := 0 + f := &fakeGitHub{respond: func(path string, _ map[string]any) (int, string) { + attempts++ + return 403, "Resource not accessible by personal access token" + }} + r, warnings := newReporter(t, f, "production") + r.Record(t.Context(), map[string]string{"": commit}, Meta{}, StateSuccess) + if attempts != 1 || len(*warnings) != 1 || !strings.Contains((*warnings)[0], "403") { + t.Fatalf("attempts = %d, warnings = %v", attempts, *warnings) + } +} + +func TestADeadGitHubCostsAtMostTheBudget(t *testing.T) { + saved := budget + budget = 200 * time.Millisecond + t.Cleanup(func() { budget = saved }) + hang := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-hang: + case <-r.Context().Done(): + } + })) + t.Cleanup(func() { close(hang); server.Close() }) + var mu sync.Mutex + var warned []string + r := &Reporter{Client: &Client{BaseURL: server.URL, Token: "t", Repository: "o/r"}, Environment: "production", + Warn: func(s string) { mu.Lock(); defer mu.Unlock(); warned = append(warned, s) }} + commits := map[string]string{"a": commit, "b": commit, "c": commit} + start := time.Now() + r.Start(context.Background(), commits, Meta{}).Finish(context.Background(), StateSuccess, "") + // Creating and finishing share the budget: the operation waits for one + // bound however many components and calls there are. + if elapsed := time.Since(start); elapsed > budget*3/2 { + t.Fatalf("took %s, budget %s", elapsed, budget) + } + mu.Lock() + warnedAny := len(warned) > 0 + mu.Unlock() + if !warnedAny { + t.Fatal("a dead GitHub must be a warning") + } + start = time.Now() + r.Record(context.Background(), commits, Meta{}, StateSuccess) + if elapsed := time.Since(start); elapsed > budget*3/2 { + t.Fatalf("record took %s, budget %s", elapsed, budget) + } +} + +func TestResolveTokenPrefersTheNamedVariable(t *testing.T) { + t.Setenv("SHOP_GH", "named") + t.Setenv("GH_TOKEN", "gh") + if got, err := ResolveToken(t.Context(), "SHOP_GH", ""); err != nil || got != "named" { + t.Fatalf("ResolveToken = %q, %v", got, err) + } + if got, err := ResolveToken(t.Context(), "", ""); err != nil || got != "gh" { + t.Fatalf("ResolveToken = %q, %v", got, err) + } + t.Setenv("SHOP_GH", "") + if _, err := ResolveToken(t.Context(), "SHOP_GH", ""); err == nil || !strings.Contains(err.Error(), "SHOP_GH") { + t.Fatalf("empty named variable: err = %v", err) + } +} + +func TestAnotherHostNeverReceivesAGitHubComToken(t *testing.T) { + t.Setenv("GH_TOKEN", "github-com-token") + t.Setenv("GITHUB_TOKEN", "github-com-token") + t.Setenv("GH_ENTERPRISE_TOKEN", "") + t.Setenv("GITHUB_ENTERPRISE_TOKEN", "") + t.Setenv("PATH", t.TempDir()) // no gh to fall back to + const evil = "https://api.evil.example" + for _, tokenEnv := range []string{"", "GH_TOKEN", "GITHUB_TOKEN"} { + got, err := ResolveToken(t.Context(), tokenEnv, evil) + if err == nil || got != "" || strings.Contains(err.Error(), "github-com-token") { + t.Fatalf("tokenEnv %q: got %q, err %v", tokenEnv, got, err) + } + } + t.Setenv("GH_ENTERPRISE_TOKEN", "enterprise") + if got, err := ResolveToken(t.Context(), "", "https://ghe.example.com/api/v3"); err != nil || got != "enterprise" { + t.Fatalf("enterprise: %q, %v", got, err) + } +} + +func TestConcludeMarksTheInterruptedRunsDeployments(t *testing.T) { + f := &fakeGitHub{} + r, warnings := newReporter(t, f, "production") + commits := map[string]string{"shop-web": commit} + r.Start(t.Context(), commits, Meta{ReleaseID: "R1"}).Finish(t.Context(), StateError, "interrupted") + r.Record(t.Context(), commits, Meta{ReleaseID: "R0"}, StateSuccess) + before := len(f.calls) + r.Conclude(t.Context(), commits, Meta{ReleaseID: "R1", Description: "ob resume"}, StateSuccess, true) + f.mu.Lock() + defer f.mu.Unlock() + if len(*warnings) != 0 { + t.Fatalf("warnings = %v", *warnings) + } + added := f.calls[before:] + if len(added) != 2 || added[0].Path != "GET /repos/labstack/shop/deployments" || added[1].Path != "/repos/labstack/shop/deployments/1/statuses" { + t.Fatalf("calls = %+v, want a lookup and one status on R1's deployment", added) + } + if added[1].Body["state"] != StateSuccess { + t.Fatalf("state = %v", added[1].Body["state"]) + } +} + +func TestConcludeCreatesAServingReleaseTheInterruptedRunNeverReported(t *testing.T) { + f := &fakeGitHub{} + r, _ := newReporter(t, f, "production") + commits := map[string]string{"shop-web": commit} + r.Conclude(t.Context(), commits, Meta{ReleaseID: "R1"}, StateSuccess, true) + r.Conclude(t.Context(), map[string]string{"shop-api": commit}, Meta{ReleaseID: "R2"}, StateFailure, false) + f.mu.Lock() + defer f.mu.Unlock() + var creates int + for _, c := range f.calls { + if c.Path == "/repos/labstack/shop/deployments" { + creates++ + } + } + if creates != 1 { + t.Fatalf("creates = %d, want only the serving release, not the aborted one", creates) + } +} diff --git a/internal/ghdeploy/reporter.go b/internal/ghdeploy/reporter.go new file mode 100644 index 00000000..39e044a0 --- /dev/null +++ b/internal/ghdeploy/reporter.go @@ -0,0 +1,239 @@ +package ghdeploy + +import ( + "context" + "errors" + "fmt" + "sort" + "sync" +) + +// Deployment states this package posts. +const ( + StateInProgress = "in_progress" + StateSuccess = "success" + StateFailure = "failure" + StateError = "error" +) + +// Reporter reports one operation on one Onebox environment. +type Reporter struct { + Client *Client + // Environment is the Onebox environment and App the application. A + // component's GitHub environment is named after both; see + // EnvironmentName. + Environment string + App string + // Warn receives each problem. It must be safe to call from several + // goroutines. + Warn func(string) +} + +// Meta describes the operation for the deployment's description and payload. +type Meta struct { + ReleaseID string + Operator string + Runner string + Description string +} + +// EnvironmentName is the GitHub environment for a component: the Onebox +// environment with the component beside it, such as "production (shop-web)". +// The whole application ("" component, a configuration-only repository) is +// named after the application. Every name carries a component, as Vercel's +// "Production – project" names do, so a project's names never change when it +// adds an image repository; consumers group on the payload's environment and +// component rather than parsing names. +func EnvironmentName(environment, component, app string) string { + if component == "" { + component = app + } + if component == "" { + return environment + } + return environment + " (" + component + ")" +} + +// Pending is a report whose deployments are being created. Finish posts the +// outcome once they exist. +type Pending struct { + r *Reporter + done chan struct{} + ids map[string]int64 +} + +// Start creates a deployment per component and marks each in progress, +// without waiting: the operation it describes must not wait on GitHub. +func (r *Reporter) Start(ctx context.Context, commits map[string]string, meta Meta) *Pending { + p := &Pending{r: r, done: make(chan struct{}), ids: map[string]int64{}} + go func() { + defer close(p.done) + p.ids = r.create(ctx, commits, meta, StateInProgress) + }() + return p +} + +// Finish posts state to every deployment Start created. Waiting for Start and +// posting share one Budget, so a dead GitHub delays the end of an operation by +// at most Budget however its calls fail. +func (p *Pending) Finish(ctx context.Context, state, description string) { + if p == nil { + return + } + ctx, cancel := context.WithTimeout(ctx, budget) + defer cancel() + select { + case <-p.done: + case <-ctx.Done(): + p.r.warn("", "the deployment was not created within "+budget.String()+"; its outcome is not reported", nil) + return + } + var wg sync.WaitGroup + for component, id := range p.ids { + wg.Go(func() { + if err := p.r.Client.CreateStatus(ctx, id, state, description); err != nil { + p.r.warn(component, "could not mark the deployment "+state, err) + } + }) + } + wg.Wait() +} + +// Record creates a deployment per component already in its final state, for +// an operation whose commits are known only once it has finished. +func (r *Reporter) Record(ctx context.Context, commits map[string]string, meta Meta, state string) { + r.create(ctx, commits, meta, state) +} + +// Conclude posts state to the deployments an earlier run created for +// meta.ReleaseID, found by commit, environment and the payload's release_id: +// `ob resume` finishing a deploy that was interrupted, or `ob abort` +// reverting it. A component with no such deployment is created in its final +// state when create is true, so a resumed release that is now serving is on +// record even if the interrupted run never reached GitHub. +func (r *Reporter) Conclude(ctx context.Context, commits map[string]string, meta Meta, state string, create bool) { + ctx, cancel := context.WithTimeout(ctx, budget) + defer cancel() + if _, err := r.Client.token(ctx); err != nil { + if r.Warn != nil { + r.Warn("not reported: " + err.Error()) + } + return + } + missing := map[string]string{} + var mu sync.Mutex + var wg sync.WaitGroup + for component, commit := range commits { + wg.Go(func() { + listed, err := r.Client.ListDeployments(ctx, commit, EnvironmentName(r.Environment, component, r.App)) + if err != nil { + r.warn(component, "could not find the deployment of "+meta.ReleaseID, err) + return + } + found := false + for _, d := range listed { + if d.Payload["release_id"] != meta.ReleaseID { + continue + } + found = true + if err := r.Client.CreateStatus(ctx, d.ID, state, meta.Description); err != nil { + r.warn(component, "could not mark the deployment "+state, err) + } + } + if !found { + mu.Lock() + missing[component] = commit + mu.Unlock() + } + }) + } + wg.Wait() + if create && len(missing) > 0 && ctx.Err() == nil { + r.create(ctx, missing, meta, state) + } +} + +func (r *Reporter) create(ctx context.Context, commits map[string]string, meta Meta, state string) map[string]int64 { + // One Budget for the whole creation, every component and both calls each. + ctx, cancel := context.WithTimeout(ctx, budget) + defer cancel() + if _, err := r.Client.token(ctx); err != nil { + if r.Warn != nil { + r.Warn("not reported: " + err.Error()) + } + return nil + } + components := make([]string, 0, len(commits)) + for component := range commits { + components = append(components, component) + } + sort.Strings(components) + ids := make([]int64, len(components)) + var wg sync.WaitGroup + for i, component := range components { + wg.Go(func() { + name, source := component, "image" + if component == "" { + name, source = r.App, "checkout" + } + d := Deployment{ + Ref: commits[component], + Environment: EnvironmentName(r.Environment, component, r.App), + Production: r.Environment == "production", + Description: meta.Description, + Payload: map[string]string{ + "app": r.App, "environment": r.Environment, "component": name, + "commit_source": source, "release_id": meta.ReleaseID, + "operator": meta.Operator, "runner": meta.Runner, + }, + } + id, err := r.Client.CreateDeployment(ctx, d) + if err != nil { + r.warnCreate(component, d.Ref, err) + return + } + if err := r.Client.CreateStatus(ctx, id, state, meta.Description); err != nil { + r.warn(component, "could not mark the deployment "+state, err) + } + ids[i] = id + }) + } + wg.Wait() + out := map[string]int64{} + for i, component := range components { + if ids[i] != 0 { + out[component] = ids[i] + } + } + return out +} + +func (r *Reporter) warn(component, what string, err error) { + if r.Warn == nil { + return + } + where := EnvironmentName(r.Environment, component, r.App) + if err == nil { + r.Warn(fmt.Sprintf("%s: %s", where, what)) + return + } + r.Warn(fmt.Sprintf("%s: %s: %v", where, what, err)) +} + +// warnCreate explains a refused creation. GitHub answers 422 for a commit it +// has never seen: one built or deployed from a checkout that was not pushed. +func (r *Reporter) warnCreate(component, ref string, err error) { + what := "could not create a deployment for " + short(ref) + var apiErr *APIError + if errors.As(err, &apiErr) && apiErr.Status == 422 { + what += " (is the commit pushed?)" + } + r.warn(component, what, err) +} + +func short(commit string) string { + if len(commit) > 12 { + return commit[:12] + } + return commit +} diff --git a/internal/gitinfo/revision.go b/internal/gitinfo/revision.go index a7c8e0d5..b3c8afa7 100644 --- a/internal/gitinfo/revision.go +++ b/internal/gitinfo/revision.go @@ -27,3 +27,53 @@ func Revision(ctx context.Context, dir string) string { } return revision } + +// Commit returns HEAD's full object name when the checkout is clean, and "" +// otherwise. It is the claim made to systems outside the host, such as GitHub +// deployments, that the deployed configuration is exactly this commit: a +// dirty tree cannot make that claim, and an unknown state makes no claim. +func Commit(ctx context.Context, dir string) string { + out, err := exec.CommandContext(ctx, "git", "-C", dir, "rev-parse", "--verify", "HEAD").Output() + if err != nil { + return "" + } + commit := strings.TrimSpace(string(out)) + if !fullObjectName(commit) { + return "" + } + status, err := exec.CommandContext(ctx, "git", "--no-optional-locks", "-C", dir, + "status", "--porcelain=v1", "--untracked-files=normal", "--ignore-submodules=none").Output() + if err != nil || len(status) > 0 { + return "" + } + return commit +} + +// fullObjectName accepts a SHA-1 or SHA-256 object name in lower-case hex. +func fullObjectName(s string) bool { + if len(s) != 40 && len(s) != 64 { + return false + } + for _, c := range s { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} + +// RemoteURLs lists the checkout's remote URLs, or nil when it has none or is +// not a checkout. +func RemoteURLs(ctx context.Context, dir string) []string { + out, err := exec.CommandContext(ctx, "git", "-C", dir, "config", "--get-regexp", `^remote\..*\.url$`).Output() + if err != nil { + return nil + } + var urls []string + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { + if _, url, ok := strings.Cut(line, " "); ok && url != "" { + urls = append(urls, url) + } + } + return urls +} diff --git a/internal/gitinfo/revision_test.go b/internal/gitinfo/revision_test.go index 76f52f0e..5ee8f9cf 100644 --- a/internal/gitinfo/revision_test.go +++ b/internal/gitinfo/revision_test.go @@ -4,6 +4,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "testing" ) @@ -64,3 +65,53 @@ func TestRevisionReportsSubmoduleChangesButExcludesIgnoredFiles(t *testing.T) { }) } } + +func TestCommitIsTheFullNameOfACleanHeadOnly(t *testing.T) { + git := func(dir string, args ...string) string { + t.Helper() + out, err := exec.CommandContext(t.Context(), "git", append([]string{"-C", dir}, args...)...).CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v: %s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + dir := t.TempDir() + if got := Commit(t.Context(), dir); got != "" { + t.Fatalf("not a repository: Commit = %q, want empty", got) + } + git(dir, "init") + if err := os.WriteFile(filepath.Join(dir, "ob.yml"), []byte("app: shop\n"), 0o600); err != nil { + t.Fatal(err) + } + if got := Commit(t.Context(), dir); got != "" { + t.Fatalf("no commit yet: Commit = %q, want empty", got) + } + git(dir, "add", ".") + git(dir, "-c", "user.name=Onebox Test", "-c", "user.email=test@example.invalid", "-c", "commit.gpgsign=false", "commit", "-m", "fixture") + want := git(dir, "rev-parse", "HEAD") + if got := Commit(t.Context(), dir); got != want { + t.Fatalf("clean: Commit = %q, want %q", got, want) + } + if err := os.WriteFile(filepath.Join(dir, "ob.yml"), []byte("app: changed\n"), 0o600); err != nil { + t.Fatal(err) + } + if got := Commit(t.Context(), dir); got != "" { + t.Fatalf("dirty: Commit = %q, want empty", got) + } +} + +func TestRemoteURLsListsEveryRemote(t *testing.T) { + dir := t.TempDir() + if got := RemoteURLs(t.Context(), dir); got != nil { + t.Fatalf("not a repository: %v", got) + } + for _, args := range [][]string{{"init"}, {"remote", "add", "origin", "git@github.com:labstack/shop.git"}, {"remote", "add", "fork", "https://github.com/acme/shop.git"}} { + if out, err := exec.CommandContext(t.Context(), "git", append([]string{"-C", dir}, args...)...).CombinedOutput(); err != nil { + t.Fatalf("git %v: %v: %s", args, err, out) + } + } + got := RemoteURLs(t.Context(), dir) + if len(got) != 2 || !slices.Contains(got, "git@github.com:labstack/shop.git") || !slices.Contains(got, "https://github.com/acme/shop.git") { + t.Fatalf("RemoteURLs = %v", got) + } +} diff --git a/internal/journal/journal.go b/internal/journal/journal.go index 52774cbb..cbb4c0e8 100644 --- a/internal/journal/journal.go +++ b/internal/journal/journal.go @@ -52,10 +52,15 @@ type Record struct { // RollbackPolicySafe records that the interrupted deploy's own policy // covers this effect even when it cannot prove a no-op result. Keeping this // on the journal prevents a later config edit from weakening abort safety. - RollbackPolicySafe bool `json:"rollback_policy_safe,omitempty"` - TS string `json:"ts"` - Operator string `json:"operator,omitempty"` - GitSHA string `json:"git_sha,omitempty"` + RollbackPolicySafe bool `json:"rollback_policy_safe,omitempty"` + TS string `json:"ts"` + Operator string `json:"operator,omitempty"` + GitSHA string `json:"git_sha,omitempty"` + // SourceCommits are the full commits a deploy shipped, keyed by component + // ("" for the whole application), recorded on its start. A rollback + // reports them to systems outside the host, which a short or dirty GitSHA + // cannot name. + SourceCommits map[string]string `json:"source_commits,omitempty"` ConfigHash string `json:"config_hash,omitempty"` ApprovalDigest string `json:"approval_digest,omitempty"` ApprovalClass string `json:"approval_class,omitempty"` @@ -105,6 +110,7 @@ type Writer struct { Epoch int Operator string GitSHA string + SourceCommits map[string]string ConfigHash string ApprovalDigest string ApprovalClass string @@ -121,10 +127,50 @@ func Dir(n app.Names) string { return release.PathsFor(n).Base + "/journal" } func file(dir, id string) string { return dir + "/" + id + ".jsonl" } +// DefaultOperator names who is running this operation, for journals, locks, +// approvals and reports. ONEBOX_OPERATOR states it outright, for an agent or a +// pipeline that knows better than the process does. In GitHub Actions the +// account that started the run is the operator, not the runner's local user, +// which is the same machine account for every run. Otherwise it is +// user@host. func DefaultOperator() string { - user := os.Getenv("USER") + // An approval records the operator and refuses one over 256 bytes. + return truncateUTF8(defaultOperator(), 256) +} + +func defaultOperator() string { + if v := operatorName(os.Getenv("ONEBOX_OPERATOR")); v != "" { + return v + } host, _ := os.Hostname() - return user + "@" + host + if os.Getenv("GITHUB_ACTIONS") == "true" { + // The triggering actor is who started this attempt; GITHUB_ACTOR + // stays the first run's on a re-run. + actor := operatorName(os.Getenv("GITHUB_TRIGGERING_ACTOR")) + if actor == "" { + actor = operatorName(os.Getenv("GITHUB_ACTOR")) + } + if actor != "" { + run := operatorName(os.Getenv("GITHUB_RUN_ID")) + if run != "" { + return actor + "@" + host + " (github actions run " + run + ")" + } + return actor + "@" + host + " (github actions)" + } + } + return os.Getenv("USER") + "@" + host +} + +// operatorName keeps an externally supplied name printable and short: it is +// written into durable evidence and printed to terminals. +func operatorName(v string) string { + v = truncateUTF8(strings.TrimSpace(v), 128) + for _, c := range v { + if c < 0x20 || c == 0x7f { + return "" + } + } + return v } // Append writes one record with a sync — the journal survives a host crash @@ -150,6 +196,9 @@ func (w *Writer) Append(ctx context.Context, r Record) error { if r.ConfigHash == "" { r.ConfigHash = w.ConfigHash } + if r.Phase == "deploy" && r.Event == "start" && r.SourceCommits == nil { + r.SourceCommits = w.SourceCommits + } // Durable authorization context belongs on deploy and manual-job starts (so // a crash before the first protected step remains resumable) and on the // explicit migration-backup authorization decision. Avoid copying @@ -381,6 +430,7 @@ type Summary struct { Done map[string]bool // "transfer", "migrate", "job:", "hook:", "release:", DoneGateRecorded Operator string GitSHA string + SourceCommits map[string]string StartedAt string MigrationBackupRequired bool MigrationBackup *MigrationBackupEvidence @@ -501,7 +551,7 @@ func Summarize(recs []Record) Summary { // operation's predecessor to itself, and abort and finalize both // read this field as durable evidence of what came before. if !s.Started { - s.Operator, s.GitSHA, s.StartedAt = r.Operator, r.GitSHA, r.TS + s.Operator, s.GitSHA, s.SourceCommits, s.StartedAt = r.Operator, r.GitSHA, r.SourceCommits, r.TS if v, ok := strings.CutPrefix(r.Detail, "prev="); ok { s.PrevRelease = v } @@ -572,3 +622,14 @@ func recordRollbackSafe(r Record) bool { } func q(s string) string { return shellquote.Quote(s) } + +// truncateUTF8 cuts s to at most n bytes without splitting a character. +func truncateUTF8(s string, n int) string { + if len(s) <= n { + return s + } + for n > 0 && s[n]&0xC0 == 0x80 { + n-- + } + return s[:n] +} diff --git a/internal/journal/journal_test.go b/internal/journal/journal_test.go index 4c3e06bb..76741d53 100644 --- a/internal/journal/journal_test.go +++ b/internal/journal/journal_test.go @@ -3,8 +3,10 @@ package journal import ( "context" "encoding/json" + "os" "strings" "testing" + "unicode/utf8" "github.com/labstack/onebox/internal/transport" @@ -303,3 +305,66 @@ func TestSummarizeMaintenanceRecordsAreNotDeployTerminals(t *testing.T) { t.Fatalf("maintenance journal was reduced as a deployment: %+v", s) } } + +func TestSourceCommitsRideOnlyOnADeployStart(t *testing.T) { + f := &transport.Fake{} + commits := map[string]string{"": "0123456789abcdef0123456789abcdef01234567"} + w := &Writer{T: f, Dir: Dir(app.Names{App: "sample", BasePath: app.DefaultBasePath}), DeployID: "R1", SourceCommits: commits} + for _, r := range []Record{{Phase: "deploy", Event: "start"}, {Phase: "release", Role: "web", Event: "result", Status: "ok"}} { + if err := w.Append(t.Context(), r); err != nil { + t.Fatal(err) + } + } + if !strings.Contains(f.Commands[0], `"source_commits":{"":"0123456789abcdef0123456789abcdef01234567"}`) { + t.Fatalf("deploy start lacks source commits:\n%s", f.Commands[0]) + } + if strings.Contains(f.Commands[1], "source_commits") { + t.Fatalf("a later record repeats source commits:\n%s", f.Commands[1]) + } + s := Summarize([]Record{ + {Phase: "deploy", Event: "start", SourceCommits: commits}, + {Phase: "deploy", Event: "start", SourceCommits: map[string]string{"": "later"}}, + }) + if s.SourceCommits[""] != commits[""] { + t.Fatalf("summary keeps the first start's commits, got %v", s.SourceCommits) + } +} + +func TestDefaultOperatorNamesWhoStartedTheRun(t *testing.T) { + host, _ := os.Hostname() + t.Setenv("USER", "deploy") + t.Setenv("ONEBOX_OPERATOR", "") + t.Setenv("GITHUB_ACTIONS", "") + if got := DefaultOperator(); got != "deploy@"+host { + t.Fatalf("local: %q", got) + } + t.Setenv("GITHUB_ACTIONS", "true") + t.Setenv("GITHUB_ACTOR", "first") + t.Setenv("GITHUB_TRIGGERING_ACTOR", "vishr") + t.Setenv("GITHUB_RUN_ID", "42") + if got := DefaultOperator(); got != "vishr@"+host+" (github actions run 42)" { + t.Fatalf("actions: %q", got) + } + t.Setenv("ONEBOX_OPERATOR", "release-agent") + if got := DefaultOperator(); got != "release-agent" { + t.Fatalf("explicit: %q", got) + } + t.Setenv("ONEBOX_OPERATOR", "bad\nname") + if got := DefaultOperator(); got != "vishr@"+host+" (github actions run 42)" { + t.Fatalf("a control character is refused: %q", got) + } +} + +func TestDefaultOperatorFitsAnApproval(t *testing.T) { + t.Setenv("ONEBOX_OPERATOR", strings.Repeat("é", 200)) + if got := DefaultOperator(); len(got) > 128 || !utf8.ValidString(got) { + t.Fatalf("explicit operator: %d bytes, valid %t", len(got), utf8.ValidString(got)) + } + t.Setenv("ONEBOX_OPERATOR", "") + t.Setenv("GITHUB_ACTIONS", "true") + t.Setenv("GITHUB_TRIGGERING_ACTOR", strings.Repeat("a", 128)) + t.Setenv("GITHUB_RUN_ID", strings.Repeat("9", 128)) + if got := DefaultOperator(); len(got) > 256 { + t.Fatalf("actions operator is %d bytes", len(got)) + } +} diff --git a/internal/onebox/approval_test.go b/internal/onebox/approval_test.go index 2891ac09..0eaff2df 100644 --- a/internal/onebox/approval_test.go +++ b/internal/onebox/approval_test.go @@ -187,3 +187,26 @@ func TestApprovalRejectsUntrustedSourceAndUnsafeOperatorText(t *testing.T) { t.Fatalf("terminal-control operator error = %v", err) } } + +// A deploy from GitHub Actions passes the approval as a workflow_dispatch +// input, and GitHub caps a dispatch's inputs at 65,535 characters in total. +func TestAnApprovalFitsInAWorkflowDispatchInput(t *testing.T) { + base := time.Date(2026, 7, 13, 18, 0, 0, 0, time.UTC) + plan := sealedTestDeployPlan(t, base, base.Add(15*time.Minute)) + createdAt, err := time.Parse(time.RFC3339Nano, plan.Operation.CreatedAt) + if err != nil { + t.Fatal(err) + } + // The longest approver an approval accepts. + approval, err := NewApprovalGrant(&plan, nil, strings.Repeat("o", 256), createdAt.Add(time.Minute)) + if err != nil { + t.Fatal(err) + } + raw, err := json.MarshalIndent(approval, "", " ") + if err != nil { + t.Fatal(err) + } + if len(raw) > 8<<10 { + t.Fatalf("approval is %d bytes; keep it far below the 65,535-character dispatch limit", len(raw)) + } +} diff --git a/internal/onebox/execute.go b/internal/onebox/execute.go index 202694b3..dd6872a0 100644 --- a/internal/onebox/execute.go +++ b/internal/onebox/execute.go @@ -109,6 +109,9 @@ func (s *Service) Execute(ctx context.Context, request ExecuteRequest) (Operatio result.EvidenceID = request.Plan.Operation.ReleaseID }) result.NoOp = noOp + if err == nil && !noOp { + result.SourceCommits = request.Plan.Artifact.SourceCommits + } return finish(err) } if request.Kind == KindJobRun { @@ -158,11 +161,16 @@ func (s *Service) Execute(ctx context.Context, request ExecuteRequest) (Operatio switch request.Kind { case KindResume: result.EvidenceID, err = e.ResumeWithJournalID(ctx) + result.SourceCommits = s.recordedSourceCommits(ctx, lp, e, result.EvidenceID) case KindAbort: result.EvidenceID, err = e.AbortWithJournalID(ctx, request.BreakMigrationGate) + result.SourceCommits = s.recordedSourceCommits(ctx, lp, e, result.EvidenceID) case KindRollback: result.EvidenceID, err = e.RollbackWithJournalID(ctx) result.ReleaseID = result.EvidenceID + if err == nil { + result.SourceCommits = s.recordedSourceCommits(ctx, lp, e, result.ReleaseID) + } case KindBootstrap: result.ReleaseID = operationID result.EvidenceID = operationID @@ -446,6 +454,7 @@ func (s *Service) executeDeploy( options.MigrationBackup = migrationBackupAudit options.WorkloadPlans = engineWorkloadPlans(plan.Operation.Steps) options.ExpectedProxyAction = plan.ProxyAction + options.SourceCommits = plan.Artifact.SourceCommits if request.Approval != nil { options.ApprovalDigest = request.Approval.ApprovalDigest options.ApprovedBy = request.Approval.ApprovedBy @@ -550,3 +559,18 @@ func verifyRemoteDeployBinding(ctx context.Context, e *engine.Engine, plan *Depl } return nil } + +// recordedSourceCommits reads the commits a release's own deploy recorded, for +// a project that reports to GitHub. It is provenance for reporting only: an +// unreadable or malformed journal yields nothing and leaves the operation's +// own result untouched. +func (s *Service) recordedSourceCommits(ctx context.Context, lp *loadedProject, e *engine.Engine, releaseID string) map[string]string { + if lp.resolved.GitHub == nil || releaseID == "" { + return nil + } + commits, err := e.ReleaseSourceCommits(context.WithoutCancel(ctx), releaseID) + if err != nil { + return nil + } + return ValidSourceCommits(commits) +} diff --git a/internal/onebox/execution_types.go b/internal/onebox/execution_types.go index 63d4cea3..d608e10a 100644 --- a/internal/onebox/execution_types.go +++ b/internal/onebox/execution_types.go @@ -392,10 +392,15 @@ type OperationResult struct { ReleaseID string `json:"release_id,omitempty"` // EvidenceID is the engine's release/journal correlation key, not a claim // that a journal append completed. An early failure may leave no evidence. - EvidenceID string `json:"evidence_id,omitempty"` - StartedAt string `json:"started_at"` - FinishedAt string `json:"finished_at"` - NoOp bool `json:"no_op,omitempty"` + EvidenceID string `json:"evidence_id,omitempty"` + StartedAt string `json:"started_at"` + FinishedAt string `json:"finished_at"` + NoOp bool `json:"no_op,omitempty"` + // SourceCommits are the full commits of the release the operation acted + // on, keyed by component: the plan's for a successful deploy, the + // restored release's for a rollback, and the interrupted deploy's for a + // resume or abort. Empty when they are unknown. + SourceCommits map[string]string `json:"source_commits,omitempty"` ApprovalDigest string `json:"approval_digest,omitempty"` BackupReportDigest string `json:"backup_report_digest,omitempty"` MigrationBackupOverrideDigest string `json:"migration_backup_override_digest,omitempty"` diff --git a/internal/onebox/plan_deploy.go b/internal/onebox/plan_deploy.go index f7f1a282..1640d0c0 100644 --- a/internal/onebox/plan_deploy.go +++ b/internal/onebox/plan_deploy.go @@ -195,7 +195,7 @@ func (s *Service) PlanDeploy(ctx context.Context, _ PlanDeployRequest) (DeployPl artifact := engine.Artifact{ ID: releaseID, App: lp.resolved.Name, Env: s.environment, CreatedAt: now, GitSHA: gitSHA, ConfigHash: configDigest, HostState: hostState, - PinnedImages: pins, BuildImages: buildImagesFor(lp, s.images), + PinnedImages: pins, SourceCommits: planSourceCommits(ctx, lp, e, pins), BuildImages: buildImagesFor(lp, s.images), SecretGeneration: secretGeneration, RenderedCompose: string(renderedRedacted), Commands: commands, diff --git a/internal/onebox/source_commits.go b/internal/onebox/source_commits.go new file mode 100644 index 00000000..4ceed0f5 --- /dev/null +++ b/internal/onebox/source_commits.go @@ -0,0 +1,194 @@ +package onebox + +import ( + "context" + "path/filepath" + "strings" + + "github.com/labstack/onebox/internal/app" + "github.com/labstack/onebox/internal/engine" + "github.com/labstack/onebox/internal/ghdeploy" + "github.com/labstack/onebox/internal/gitinfo" +) + +// planSourceCommits decides which commits a release ships, for reporting to +// the configured GitHub repository. Only a project with a github block pays +// for the image inspection. Images are pinned by digest, so their labels, and +// therefore this answer, cannot change between plan and apply. +func planSourceCommits(ctx context.Context, lp *loadedProject, e *engine.Engine, pins map[string]string) map[string]string { + if lp.resolved.GitHub == nil { + return nil + } + dir := filepath.Dir(lp.configPath) + checkout := "" + // The checkout stands for the deployed configuration only when it is a + // clone of the repository being reported to. + repository := repositoryURL(lp.resolved.GitHub) + if checkoutOf(repository, gitinfo.RemoteURLs(ctx, dir)) { + checkout = gitinfo.Commit(ctx, dir) + } + return sourceCommits(repository, e.ImageSources(ctx, pins), pins, checkout) +} + +// sourceCommits keys the commits a release ships by component. +// +// A workload image counts when its org.opencontainers.image.source label +// names the repository and its revision is a full commit. Each such image +// repository is one component, named by its last path element, because a +// project that deploys several images (web at one version, server at another) +// ships several commits and no single one describes it. A single image +// repository is a component too, so a project's names do not change when it +// adds a second. +// +// When no image comes from the repository, the repository holds only the +// configuration, and the clean checkout's commit is what was deployed, under +// the key "". A dirty or unknown checkout reports nothing rather than +// something untrue. +// +// An image repository whose workloads carry different revisions, or no full +// revision, has no one commit and is left out. +func sourceCommits(repository string, sources map[string]engine.ImageSource, pins map[string]string, checkout string) map[string]string { + want := normalizeRepositoryURL(repository) + byComponent := map[string]map[string]bool{} + for workload := range pins { + // An image whose provenance is unknown could be from the repository, + // so neither the checkout fallback nor the components can be trusted. + if source, ok := sources[workload]; !ok || source.Unknown { + return nil + } + } + for workload, source := range sources { + if normalizeRepositoryURL(source.Source) != want { + continue + } + component := imageComponent(pins[workload]) + if component == "" { + continue + } + if byComponent[component] == nil { + byComponent[component] = map[string]bool{} + } + // An image from the repository without a usable revision still + // counts as a component: it rules out the checkout fallback, because + // the checkout says nothing about what that image was built from. + revision := "" + if fullCommit(source.Revision) { + revision = strings.ToLower(source.Revision) + } + byComponent[component][revision] = true + } + if len(byComponent) == 0 { + if checkout == "" { + return nil + } + return map[string]string{"": checkout} + } + out := map[string]string{} + for component, revisions := range byComponent { + if len(revisions) != 1 || revisions[""] { + continue + } + for revision := range revisions { + out[component] = revision + } + } + if len(out) == 0 { + return nil + } + return out +} + +// normalizeRepositoryURL reduces the URL forms a repository is written in, +// https, ssh and scp-like, to host/owner/name. +func normalizeRepositoryURL(raw string) string { + s := strings.ToLower(strings.TrimSpace(raw)) + s = strings.TrimSuffix(strings.TrimSuffix(s, "/"), ".git") + s = strings.TrimPrefix(s, "git+") + for _, scheme := range []string{"https://", "http://", "ssh://", "git://"} { + s = strings.TrimPrefix(s, scheme) + } + if at := strings.Index(s, "@"); at >= 0 && at < strings.IndexAny(s+"/", ":/") { + s = s[at+1:] + } + // scp-like git@github.com:owner/name + if colon := strings.Index(s, ":"); colon >= 0 && !strings.Contains(s[:colon], "/") { + s = s[:colon] + "/" + s[colon+1:] + } + return strings.TrimPrefix(s, "www.") +} + +// repositoryURL is the web URL of the configured repository, on the host its +// API serves. +func repositoryURL(github *app.GitHub) string { + return "https://" + ghdeploy.WebHost(github.APIURL) + "/" + github.Repository +} + +// checkoutOf reports whether any of a checkout's remotes is the repository. +func checkoutOf(repository string, remotes []string) bool { + want := normalizeRepositoryURL(repository) + for _, remote := range remotes { + if normalizeRepositoryURL(remote) == want { + return true + } + } + return false +} + +// ValidSourceCommits keeps a recorded set only when every entry is one this +// package could have produced: a full commit under "" or an image repository +// name. Commits read back from a host are not trusted to be well formed. +func ValidSourceCommits(commits map[string]string) map[string]string { + if len(commits) == 0 { + return nil + } + for component, commit := range commits { + if !fullCommit(commit) || (component != "" && !validComponent(component)) { + return nil + } + } + return commits +} + +// validComponent is the OCI repository name-component alphabet. +func validComponent(s string) bool { + if s == "" || len(s) > 128 { + return false + } + for i, c := range s { + alnum := (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') + if !alnum && (i == 0 || (c != '.' && c != '_' && c != '-')) { + return false + } + } + return true +} + +// imageComponent is an image reference's repository basename: +// ghcr.io/labstack/monk-web:1.2@sha256:... is monk-web. +func imageComponent(ref string) string { + if at := strings.Index(ref, "@"); at >= 0 { + ref = ref[:at] + } + name := ref + if slash := strings.LastIndex(name, "/"); slash >= 0 { + name = name[slash+1:] + } + if colon := strings.Index(name, ":"); colon >= 0 { + name = name[:colon] + } + return name +} + +func fullCommit(s string) bool { + if len(s) != 40 && len(s) != 64 { + return false + } + for _, c := range strings.ToLower(s) { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} + +var _ = app.GitHub{} diff --git a/internal/onebox/source_commits_test.go b/internal/onebox/source_commits_test.go new file mode 100644 index 00000000..efe934b9 --- /dev/null +++ b/internal/onebox/source_commits_test.go @@ -0,0 +1,148 @@ +package onebox + +import ( + "reflect" + "testing" + + "github.com/labstack/onebox/internal/app" + "github.com/labstack/onebox/internal/engine" +) + +func img(source, revision string) engine.ImageSource { + return engine.ImageSource{Source: source, Revision: revision} +} + +func TestSourceCommitsPrefersImagesFromTheRepository(t *testing.T) { + const ( + a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + b = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + checkout = "cccccccccccccccccccccccccccccccccccccccc" + repo = "https://github.com/labstack/monk" + src = "https://github.com/labstack/monk" + docker = "https://github.com/docker-library/docker" + ) + monk := map[string]string{ + "web": "ghcr.io/labstack/monk-web:1@sha256:1", + "server": "ghcr.io/labstack/monk-server:2@sha256:2", + "migrate": "ghcr.io/labstack/monk-server:2@sha256:2", + "tool": "docker:29-cli@sha256:3", + } + single := map[string]string{ + "server": "ghcr.io/labstack/monk-server:2@sha256:2", + "migrate": "ghcr.io/labstack/monk-server:2@sha256:2", + "tool": "docker:29-cli@sha256:3", + } + for name, tc := range map[string]struct { + pins map[string]string + sources map[string]engine.ImageSource + checkout string + want map[string]string + }{ + "one image repository is still a component": { + pins: single, + sources: map[string]engine.ImageSource{"server": img(src, a), "migrate": img(src, a), "tool": img(docker, b)}, + checkout: checkout, + want: map[string]string{"monk-server": a}, + }, + "several image repositories are components": { + pins: monk, + sources: map[string]engine.ImageSource{"web": img(src+".git", b), "server": img("HTTPS://github.com/LabStack/monk/", a), "migrate": img(src, a), "tool": img(docker, b)}, + want: map[string]string{"monk-web": b, "monk-server": a}, + }, + "an image repository at two commits is left out": { + pins: monk, + sources: map[string]engine.ImageSource{"web": img(src, b), "server": img(src, a), "migrate": img(src, b), "tool": img("", "")}, + want: map[string]string{"monk-web": b}, + }, + "no image from the repository falls back to the checkout": { + pins: map[string]string{"tool": "docker:29-cli@sha256:3"}, + sources: map[string]engine.ImageSource{"tool": img(docker, b)}, + checkout: checkout, + want: map[string]string{"": checkout}, + }, + "an image from the repository without a full revision rules out the checkout": { + pins: single, + sources: map[string]engine.ImageSource{"server": img(src, "abc1234"), "migrate": img(src, "abc1234"), "tool": img(docker, b)}, + checkout: checkout, + want: nil, + }, + "an image that could not be read reports nothing": { + pins: single, + sources: map[string]engine.ImageSource{"server": img(src, a), "migrate": img(src, a), "tool": {Unknown: true}}, + checkout: checkout, + want: nil, + }, + "a workload missing from the sources reports nothing": { + pins: monk, + sources: map[string]engine.ImageSource{"server": img(src, a), "migrate": img(src, a), "tool": img(docker, b)}, + checkout: checkout, + want: nil, + }, + "no checkout and no image reports nothing": { + pins: map[string]string{"tool": "docker:29-cli@sha256:3"}, + sources: map[string]engine.ImageSource{"tool": img(docker, b)}, + want: nil, + }, + "the only repository disagreeing with itself reports nothing": { + pins: map[string]string{"server": "ghcr.io/labstack/monk-server:2@sha256:2", "migrate": "ghcr.io/labstack/monk-server:3@sha256:4"}, + sources: map[string]engine.ImageSource{"server": img(src, a), "migrate": img(src, b)}, + checkout: checkout, + want: nil, + }, + } { + t.Run(name, func(t *testing.T) { + if got := sourceCommits(repo, tc.sources, tc.pins, tc.checkout); !reflect.DeepEqual(got, tc.want) { + t.Fatalf("sourceCommits = %v, want %v", got, tc.want) + } + }) + } +} + +func TestCheckoutOfMatchesEveryRemoteForm(t *testing.T) { + for _, remote := range []string{ + "https://github.com/labstack/shop.git", + "git@github.com:labstack/shop.git", + "ssh://git@github.com/LabStack/shop", + "https://github.com/labstack/shop/", + } { + if !checkoutOf("https://github.com/labstack/shop", []string{"https://github.com/acme/fork.git", remote}) { + t.Fatalf("%s is labstack/shop", remote) + } + } + for _, remotes := range [][]string{nil, {"git@github.com:acme/infra.git"}, {"https://gitlab.com/labstack/shop.git"}} { + if checkoutOf("https://github.com/labstack/shop", remotes) { + t.Fatalf("%v is not labstack/shop", remotes) + } + } +} + +func TestValidSourceCommitsRefusesAnythingMalformed(t *testing.T) { + const c = "0123456789abcdef0123456789abcdef01234567" + for _, ok := range []map[string]string{{"": c}, {"monk-web": c, "monk-server": c}} { + if ValidSourceCommits(ok) == nil { + t.Fatalf("%v is valid", ok) + } + } + for _, bad := range []map[string]string{nil, {"": "main"}, {"": c[:12]}, {"Web Server": c}, {"-x": c}, {"monk-web": c, "": "HEAD"}} { + if ValidSourceCommits(bad) != nil { + t.Fatalf("%v must be refused", bad) + } + } +} + +func TestRepositoryURLFollowsTheAPIHost(t *testing.T) { + for apiURL, want := range map[string]string{ + "": "https://github.com/acme/shop", + "https://api.github.com": "https://github.com/acme/shop", + "https://api.acme.ghe.com": "https://acme.ghe.com/acme/shop", + "https://github.example.com/api/v3": "https://github.example.com/acme/shop", + "https://api.corp.example/api/v3": "https://api.corp.example/acme/shop", + } { + if got := repositoryURL(&app.GitHub{Repository: "acme/shop", APIURL: apiURL}); got != want { + t.Fatalf("repositoryURL(%q) = %q, want %q", apiURL, got, want) + } + } + if !checkoutOf(repositoryURL(&app.GitHub{Repository: "acme/shop", APIURL: "https://github.example.com/api/v3"}), []string{"git@github.example.com:acme/shop.git"}) { + t.Fatal("an Enterprise Server remote is a checkout of its repository") + } +} diff --git a/site/public/schemas/application/v1alpha2/application.schema.json b/site/public/schemas/application/v1alpha2/application.schema.json index df3c64db..f8c4ce7c 100644 --- a/site/public/schemas/application/v1alpha2/application.schema.json +++ b/site/public/schemas/application/v1alpha2/application.schema.json @@ -767,6 +767,41 @@ "description": "Typed dependencies operated outside Onebox. Their connection projection is trusted, but their lifecycle and backup remain external.", "type": "object" }, + "github": { + "additionalProperties": false, + "description": "Report deploys and rollbacks to a GitHub repository's deployments, so they show in its Environments tab and reach tools that read deployment statuses.", + "properties": { + "apiUrl": { + "default": "https://api.github.com", + "description": "GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. A github.com token is never sent to another host: there the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL.", + "examples": [ + "https://github.example.com/api/v3" + ], + "pattern": "^https?://", + "type": "string" + }, + "repository": { + "description": "GitHub repository, as owner/name, whose deployments record each deploy and rollback. Workload images whose org.opencontainers.image.source label names this repository are reported at their org.opencontainers.image.revision commit; when none does, the clean checkout's commit is reported if the checkout is a clone of this repository. Each image repository is reported in its own GitHub environment, named like production (shop-web); a configuration-only repository is named after the application. Expects owner/name, such as labstack/shop.", + "examples": [ + "labstack/shop" + ], + "pattern": "^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}$", + "type": "string" + }, + "tokenEnv": { + "description": "Local environment-variable name containing a GitHub token with Deployments write access. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects a variable name of letters, digits and underscores, not starting with a digit.", + "examples": [ + "GH_TOKEN" + ], + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "type": "string" + } + }, + "required": [ + "repository" + ], + "type": "object" + }, "hooks": { "additionalProperties": { "anyOf": [ diff --git a/site/src/content/docs/docs/guides/deploy-from-github-actions.mdx b/site/src/content/docs/docs/guides/deploy-from-github-actions.mdx new file mode 100644 index 00000000..cf58253f --- /dev/null +++ b/site/src/content/docs/docs/guides/deploy-from-github-actions.mdx @@ -0,0 +1,249 @@ +--- +title: Deploy from GitHub Actions +description: "Run ob deploy from a workflow you start with gh workflow run, on a runner that already holds the keys, approved with ob approve or GitHub's reviewers." +summary: How to run ob in GitHub Actions without putting server keys in GitHub, how approval works there, and how the run is recorded. +sidebar: + order: 13 +read_when: + - "Starting deploys with gh workflow run or from the Actions tab" + - "Deciding between a self-hosted and a GitHub-hosted runner for deploys" + - "Approving a workflow deploy, with or without GitHub required reviewers" + - "Working out who can deploy once a runner holds the keys" +--- + +`ob` runs wherever its keys are: a laptop, a dev box, an agent, or a GitHub +Actions runner. The commands are the same in every case. A workflow lets the +people with access start a deploy with `gh workflow run` or the Actions tab, +on a machine that holds the keys, while a human still approves it. + +## Choose the runner by where the keys live + +`ob` needs an SSH identity for the server, the server's key in +`~/.ssh/known_hosts` (it never skips host verification), and whatever decrypts +the project's secrets, such as a SOPS age key. + +| Runner | Keys | Use it when | +| --- | --- | --- | +| Self-hosted, on a machine that already deploys | stay on that machine; nothing is stored in GitHub | the keys must never leave your machines | +| GitHub-hosted | stored as environment secrets and written to the runner for the job | you accept GitHub holding a deploy key | + +On a self-hosted runner the job uses the runner user's `~/.ssh` and agent, so +`ob deploy` behaves as it does in that user's shell. The runner also needs +`git`, `gh`, `jq` and `sha256sum`, which a self-hosted machine does not always have; +GitHub-hosted runners include them. The install step below fetches the +`linux_amd64` build; use `linux_arm64` on an ARM runner. + +## Who can deploy + +A workflow started with `workflow_dispatch` runs the workflow file from the +branch the caller picks. Anyone who can push a branch can therefore run their +own `deploy.yml` on a runner that accepts the repository's jobs. That run need +not contain an approval step at all. + +On a self-hosted runner that holds the keys, everyone with write access to the +repository can reach those keys. An approval gate cannot change that. It stops +mistakes, not people with push access. Limit it with one of these: + +- **Give deploys their own runner.** Never put the keys on a runner that also + builds, tests or releases: every job it runs can read them. A label such as + `deploy` only says where a job asks to run; it does not stop another + workflow asking for it. +- **Restrict the runner.** Put the deploy runner in a runner group that only + this workflow may use, at a protected branch such as `main`, and protect that + branch. Where your plan offers no such restriction, treat repository write + access as deploy access. +- **Keep the keys in GitHub.** Use a GitHub-hosted runner and store the keys as + environment secrets, with the environment's deployment branches limited to + `main`. A run from any other branch cannot read them. + +Never attach a key-holding self-hosted runner to a public repository: a pull +request from a fork can run code on it. + +## Choose the approval gate + +A workflow deploy needs a human gate as much as a terminal deploy does. Pick +one of two; without either, anyone who can start the workflow deploys. + +| Gate | Requires | Onebox policy | +| --- | --- | --- | +| [Onebox approval](#onebox-approval-any-repository), typed at a terminal | nothing beyond Onebox | `requireApproval: true` (the default) | +| [GitHub required reviewers](#github-reviewers) | a public repository with GitHub-hosted runners, or GitHub Enterprise for a private one | `requireApproval: false` | + +GitHub offers required reviewers on private repositories only with GitHub +Enterprise. On Free, Pro and Team, a private repository uses Onebox approval. + +Inputs reach the scripts through `env`, never pasted into them with `${{ }}`, +so an input cannot run as shell. Both workflows below install `ob` the same way and run on a runner labelled +`deploy`: + +```yaml +- name: Install ob + env: + GH_TOKEN: ${{ github.token }} + VERSION: 2026.11.4-alpha + run: | + asset="onebox_${VERSION}_linux_amd64.tar.gz" + gh release download "v${VERSION}" -R labstack/onebox \ + -p "$asset" -p "onebox_${VERSION}_checksums.txt" + grep " ${asset}$" "onebox_${VERSION}_checksums.txt" | sha256sum -c - + tar -xzf "$asset" ob + install -m 0755 ob "$RUNNER_TEMP/ob" + echo "$RUNNER_TEMP" >> "$GITHUB_PATH" +``` + +## Onebox approval: any repository + +`ob approve` records a human confirmation typed at a terminal, and has no flag +to skip it. It reads only the plan file, contacts nothing and needs no keys, +so the plan is made on the runner and approved on your laptop: + +1. A run with no `plan_run` input makes the plan and uploads it. The plan's + Compose is redacted, so the artifact carries no secret values. +2. You download it, review it, and approve it with `ob approve`. +3. A second run receives the plan run's ID and the confirmation, and applies + exactly that plan. A plan expires 15 minutes after it is made, and a host + that drifted in between is refused, as for any saved plan. + +```yaml +name: Deploy +on: + workflow_dispatch: + inputs: + environment: + description: Onebox environment + default: production + plan_run: + description: Run ID of the plan to apply; empty makes a new plan + default: "" + approval: + description: Contents of ob-approval.json from ob approve + default: "" + +permissions: + contents: read + actions: read # download the plan from the plan run + deployments: write # lets ob report the deploy with the job's own token + +concurrency: + group: deploy-${{ inputs.environment }} + cancel-in-progress: false + +jobs: + plan: + if: inputs.plan_run == '' + runs-on: [self-hosted, deploy] + steps: + - uses: actions/checkout@v4 + # Install ob (above) + - env: + ENVIRONMENT: ${{ inputs.environment }} + run: ob plan --env "$ENVIRONMENT" --out ob-plan.json + - uses: actions/upload-artifact@v4 + with: + name: ob-plan + path: ob-plan.json + retention-days: 1 + + apply: + if: inputs.plan_run != '' + runs-on: [self-hosted, deploy] + steps: + # Apply only a plan this workflow made from main, and check out the + # commit it was made from, because the plan binds that configuration. + - id: planned + env: + GH_TOKEN: ${{ github.token }} + PLAN_RUN: ${{ inputs.plan_run }} + run: | + case "$PLAN_RUN" in ''|*[!0-9]*) echo "::error::plan_run must be a run ID"; exit 1 ;; esac + run=$(gh run view "$PLAN_RUN" -R "$GITHUB_REPOSITORY" \ + --json workflowName,event,headBranch,conclusion,headSha) + ok=$(jq -r --arg w "$GITHUB_WORKFLOW" '.workflowName == $w and .event == "workflow_dispatch" and .headBranch == "main" and .conclusion == "success"' <<<"$run") + if [ "$ok" != true ]; then + echo "::error::run $PLAN_RUN is not a successful plan run of this workflow on main"; exit 1 + fi + echo "sha=$(jq -r .headSha <<<"$run")" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@v4 + with: + ref: ${{ steps.planned.outputs.sha }} + # Install ob (above) + - env: + GH_TOKEN: ${{ github.token }} + ENVIRONMENT: ${{ inputs.environment }} + PLAN_RUN: ${{ inputs.plan_run }} + APPROVAL: ${{ inputs.approval }} + run: | + gh run download "$PLAN_RUN" -n ob-plan + printf '%s' "$APPROVAL" > ob-approval.json + ob deploy --env "$ENVIRONMENT" \ + --plan ob-plan.json --approval ob-approval.json +``` + +From a terminal with `ob` installed, no keys needed: + +```sh +gh workflow run deploy.yml -f environment=production +run=$(gh run list -w deploy.yml -L 1 --json databaseId -q '.[0].databaseId') +gh run watch "$run" +gh run download "$run" -n ob-plan +ob approve --plan ob-plan.json # shows the plan; you confirm it +gh workflow run deploy.yml -f environment=production \ + -f plan_run="$run" -f approval="$(cat ob-approval.json)" +``` + +The confirmation is tamper-evident and bound to that one plan, but it is not a +signed identity, and [who can deploy](#who-can-deploy) still decides who could +approve. The apply job checks that the plan came from a successful run of this +workflow on `main`, so a run ID from another workflow or a branch is refused. + +## GitHub reviewers + +With required reviewers on the GitHub environment, the job waits until one +approves, and `ob deploy --yes` applies the plan the job computes. Set +`policy.requireApproval: false` on the Onebox environment so `--yes` is +accepted. Onebox does not read GitHub's approvals, so a terminal deploy to +that environment is not gated by GitHub either: give it to GitHub only if every +deploy to it goes through the workflow. + +```yaml +jobs: + deploy: + runs-on: [self-hosted, deploy] + environment: + name: ${{ inputs.environment }} + # The reviewers still gate the job. ob creates the deployment records, + # at the commits it actually ships, so Actions must not add its own. + deployment: false + steps: + - uses: actions/checkout@v4 + # Install ob (above) + - env: + GH_TOKEN: ${{ github.token }} + ENVIRONMENT: ${{ inputs.environment }} + run: ob deploy --env "$ENVIRONMENT" --yes +``` + +`deployment: false` keeps the reviewers working and stops Actions creating its +own deployment record at the workflow's commit. GitHub refuses to start a job +that combines it with custom deployment protection rules. + +A project whose workloads are built in CI passes the images it resolved, as +`--image web=ghcr.io/acme/shop-web:2026.11.3`, to `ob plan` or `ob deploy` +exactly as it does locally. + +## What the run records + +- **Operator.** In GitHub Actions the journal, the lock and the reports name the + account that started the run, such as `vishr@runner-1 (github actions run + 42)`, not the runner's local user. Set `ONEBOX_OPERATOR` to name it yourself, + for an agent or a pipeline. +- **GitHub deployments.** With a [`github` block](/docs/guides/github-deployments), + `ob` reports the deploy with `GH_TOKEN`. A deployment created with the job's + `GITHUB_TOKEN` does not start other workflows, but webhooks and GitHub Apps + still receive its `deployment_status` events. To start a workflow on those + events, give `ob` a token of its own through `github.tokenEnv`. +- **Notifications** fire as they do for any deploy. + +An interrupted job leaves the deploy where it stopped. Run `ob resume` or +`ob abort` from the same runner or any machine with the keys, and the GitHub +deployment is concluded with the outcome. diff --git a/site/src/content/docs/docs/guides/github-deployments.mdx b/site/src/content/docs/docs/guides/github-deployments.mdx new file mode 100644 index 00000000..889349a4 --- /dev/null +++ b/site/src/content/docs/docs/guides/github-deployments.mdx @@ -0,0 +1,124 @@ +--- +title: Report deploys to GitHub +description: "Show every deploy and rollback in a repository's Environments tab, on pull requests, and to tools that read deployment statuses." +summary: How ob reports deploys and rollbacks to GitHub deployments from wherever it runs, which commit it reports, and what it never does. +sidebar: + order: 12 +read_when: + - "Showing what is live in GitHub without deploying from GitHub Actions" + - "Wiring a tool that reads deployment_status events to Onebox deploys" + - "Working out why a deploy was not reported" +--- + +Hosting platforms tell GitHub when a commit goes live, so pull requests say +"deployed to production" and tools that listen for `deployment_status` events +react. A deploy run from GitHub Actions gets the same through a job's +`environment`. `ob` deploys from a laptop, a dev box or an agent, so it reports +itself. + +```yaml +spec: + github: + repository: labstack/shop +``` + +With this block, `ob deploy` creates a GitHub deployment once the server has +recorded the deploy's start, marks it in progress, and marks it `success`, `failure` +or `error` when it finishes. `ob rollback` records a deployment for the release +it restored. `ob resume` gives an interrupted deploy's deployments their final +outcome, and records the release if the interrupted run never reached GitHub; +`ob abort` marks them `failure`. A no-op deploy, and a deploy refused before it +started, report nothing. + +`ob` reports the same way from a terminal, an agent or a +[GitHub Actions workflow](/docs/guides/deploy-from-github-actions). For GitHub +Enterprise, set `apiUrl` to the API base, such as +`https://github.example.com/api/v3` or `https://api.acme.ghe.com`. A +github.com token is never sent there: `ob` uses `tokenEnv`, then +`GH_ENTERPRISE_TOKEN`, `GITHUB_ENTERPRISE_TOKEN`, or the token `gh` holds for +that host. + +## The token stays where `ob` runs + +`ob` uses the variable named by `tokenEnv`, otherwise `GH_TOKEN`, then +`GITHUB_TOKEN`, then `gh auth token`. With `apiUrl` set for GitHub Enterprise, +the fallbacks are `GH_ENTERPRISE_TOKEN`, `GITHUB_ENTERPRISE_TOKEN`, then +`gh auth token --hostname HOST`. The token needs Deployments write access +to the repository: a fine-grained token with **Deployments: read and write**, +or a classic token with `repo_deployment`. + +The token is never written to the server, the journal or structured output. +That is also why work the server runs on its own, such as scheduled jobs, is +not reported. + +In GitHub Actions, `GH_TOKEN: ${{ github.token }}` with +`permissions: deployments: write` is enough. + +A missing token or a failed GitHub call is a warning on stderr. It never fails +or blocks a deploy, and a GitHub that does not answer delays the end of the +command by at most 15 seconds. + +## Which commit is reported + +GitHub records one commit per deployment, and it must be one GitHub has seen. +`ob` decides which at plan time, so a saved plan reports exactly what was +reviewed: + +1. A workload image whose `org.opencontainers.image.source` label names the + repository is reported at its `org.opencontainers.image.revision`. Images + are pinned by digest, so the labels cannot change between plan and apply. +2. Each image repository is reported in its own GitHub environment, because a + release that ships `shop-web` at one version and `shop-server` at another + has no single commit: `production (shop-web)` and + `production (shop-server)`. +3. When no image comes from the repository, the repository holds only the + configuration. If the checkout is a clean clone of the repository, its + commit is reported, in an environment named after the application, such as + `production (shop)`. + +Anything else reports nothing rather than something untrue: a dirty checkout, +a checkout of another repository, an image whose labels could not be read, an +image from the repository without a full revision, or one image repository +deployed at two commits. That includes third-party images such as a database: +if one cannot be inspected, the release reports nothing, because `ob` cannot +tell that it is not from the repository. A commit that was never pushed is +refused by GitHub and reported as a warning. + +A rollback reports the commits the restored release recorded when it was +deployed. A release deployed before the `github` block was added has none, and +its rollback is not reported. + +### Labelling images + +`docker/metadata-action` computes both labels, but they reach the image only +when its `labels` output is passed to the build, for example +`labels: ${{ steps.meta.outputs.labels }}` on `docker/build-push-action`. `ob` +reads image labels, not manifest annotations. On a `pull_request` build the +revision is GitHub's merge commit unless `DOCKER_METADATA_PR_HEAD_SHA` is +`true`. + +## Reading the deployments + +Every environment name carries a component, as Vercel's +`Production – project` names do, so names stay the same when a project adds an +image repository. A consumer should not match the literal name `production`. +Each deployment's payload says where it belongs: + +| Field | Value | +| --- | --- | +| `environment` | the Onebox environment, such as `production` | +| `component` | the image repository, or the application for a configuration-only repository | +| `commit_source` | `image` or `checkout` | +| `release_id` | the Onebox release | +| `app`, `operator`, `runner` | the application, who deployed, and the `ob` version | + +`production_environment` is set for every component of the `production` +environment. + +## What GitHub does not do here + +Environment protection rules, such as required reviewers and wait timers, are +documented as gating GitHub Actions jobs. They never gate `ob`: approval stays +with Onebox's own plan review and `policy.requireApproval`. If a rule makes +GitHub refuse the report, the refusal is a warning and the deploy is +unaffected. diff --git a/site/src/content/docs/docs/reference/capabilities.mdx b/site/src/content/docs/docs/reference/capabilities.mdx index fd187baf..7bae3c37 100644 --- a/site/src/content/docs/docs/reference/capabilities.mdx +++ b/site/src/content/docs/docs/reference/capabilities.mdx @@ -39,6 +39,12 @@ This page is the reconciliation. Three states: published, and stops it only after the proxy has dropped it. - Locks, fencing, append-only journals, resume, abort, migration gates, status, audit, SOPS secrets, supporting services, proxy operations, notifications. +- GitHub deployments for deploy, rollback, resume and abort, reported from + wherever `ob` runs with the operator's own token. The commit comes from each + workload image's OCI source and revision labels, or from a clean checkout of + a configuration-only repository, and is bound into the plan. See + [GitHub deployments](/docs/guides/github-deployments) and + [Deploy from GitHub Actions](/docs/guides/deploy-from-github-actions). - A canonical, versioned operation graph and one shared Go service for proposals, execution, structured events and operational memory. The CLI is an adapter over it. Observation is the engine's status snapshot, not a method on diff --git a/site/src/content/docs/docs/reference/fields/github.mdx b/site/src/content/docs/docs/reference/fields/github.mdx new file mode 100644 index 00000000..d3a2ae91 --- /dev/null +++ b/site/src/content/docs/docs/reference/fields/github.mdx @@ -0,0 +1,30 @@ +--- +title: "github" +description: "The GitHub repository whose deployments record each deploy and rollback, and the local token used to report them." +summary: "The GitHub repository whose deployments record each deploy and rollback, and the local token used to report them." +status: shipped +generated: true +sidebar: + order: 110 +read_when: + - "Showing deploys in a repository's Environments tab, on pull requests, or to tools that read deployment statuses" +--- + +{/* Generated by cmd/ob-docgen. Do not edit by hand. */} + +This page is generated from the same Go declarations the loader enforces, so it +cannot drift from what `ob validate` accepts. + +## Fields on this page + +`apiUrl` · `repository` · `tokenEnv` + +## Reference + +| Field | Type | Default | What it does | +| --- | --- | --- | --- | +| `apiUrl` | string | `https://api.github.com` | GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. A github.com token is never sent to another host: there the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL. | +| `repository` `*` | string | — | GitHub repository, as owner/name, whose deployments record each deploy and rollback. Workload images whose org.opencontainers.image.source label names this repository are reported at their org.opencontainers.image.revision commit; when none does, the clean checkout's commit is reported if the checkout is a clone of this repository. Each image repository is reported in its own GitHub environment, named like production (shop-web); a configuration-only repository is named after the application. Expects owner/name, such as labstack/shop. | +| `tokenEnv` | string | — | Local environment-variable name containing a GitHub token with Deployments write access. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects a variable name of letters, digits and underscores, not starting with a digit. | + +`*` marks a field that is required within its own object. From b2c0473cd72374a289f9b491dea1b3981c2cad01 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Sat, 28 Nov 2026 22:21:22 -0800 Subject: [PATCH 2/2] fix(github): confirm a project-named API host and token variable A project file named both where a token goes (github.apiUrl) and which variable supplies it (github.tokenEnv), so a hostile project file could send any secret in the operator's environment to a host it chose. A non-default apiUrl now receives a token only when the operator's own ONEBOX_GITHUB_API_URL names the same URL, and tokenEnv must be a GitHub token variable: upper case, containing GH or GITHUB, ending in TOKEN. Co-Authored-By: Claude Opus 5.5 --- .../v1alpha2/application.schema.json | 6 ++-- cmd/ob/github_test.go | 4 +-- internal/app/constraints.go | 3 ++ internal/app/jsonschema.go | 2 +- internal/app/types.go | 4 +-- internal/app/validate.go | 2 +- internal/ghdeploy/ghdeploy.go | 30 ++++++++++++++--- internal/ghdeploy/ghdeploy_test.go | 32 ++++++++++++++----- .../v1alpha2/application.schema.json | 6 ++-- .../docs/docs/guides/github-deployments.mdx | 17 +++++++--- .../docs/docs/reference/fields/github.mdx | 4 +-- 11 files changed, 79 insertions(+), 31 deletions(-) diff --git a/api/application/v1alpha2/application.schema.json b/api/application/v1alpha2/application.schema.json index f8c4ce7c..2c275576 100644 --- a/api/application/v1alpha2/application.schema.json +++ b/api/application/v1alpha2/application.schema.json @@ -773,7 +773,7 @@ "properties": { "apiUrl": { "default": "https://api.github.com", - "description": "GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. A github.com token is never sent to another host: there the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL.", + "description": "GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. Because the project file names the host, ob sends a token there only when the operator's environment confirms the same URL in ONEBOX_GITHUB_API_URL, and never sends it a github.com token: the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL.", "examples": [ "https://github.example.com/api/v3" ], @@ -789,11 +789,11 @@ "type": "string" }, "tokenEnv": { - "description": "Local environment-variable name containing a GitHub token with Deployments write access. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects a variable name of letters, digits and underscores, not starting with a digit.", + "description": "Local environment-variable name containing a GitHub token with Deployments write access; it must contain GH or GITHUB and end in TOKEN, so a project file cannot name some other secret. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects an upper-case variable name containing GH or GITHUB and ending in TOKEN, such as SHOP_GH_TOKEN.", "examples": [ "GH_TOKEN" ], - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "pattern": "^[A-Z0-9_]*(GH|GITHUB)[A-Z0-9_]*TOKEN$", "type": "string" } }, diff --git a/cmd/ob/github_test.go b/cmd/ob/github_test.go index 2d551266..57a20c11 100644 --- a/cmd/ob/github_test.go +++ b/cmd/ob/github_test.go @@ -51,14 +51,14 @@ func fakeGitHubAPI(t *testing.T) *[]recordedCall { saved := githubAPIBase githubAPIBase = server.URL t.Cleanup(func() { githubAPIBase = saved }) - t.Setenv("ONEBOX_TEST_GH", "token") + t.Setenv("ONEBOX_TEST_GH_TOKEN", "token") return calls } func githubConfig() *app.Resolved { cfg := &app.Resolved{Spec: &app.Spec{}} cfg.Name = "shop" - cfg.GitHub = &app.GitHub{Repository: "labstack/shop", TokenEnv: "ONEBOX_TEST_GH"} + cfg.GitHub = &app.GitHub{Repository: "labstack/shop", TokenEnv: "ONEBOX_TEST_GH_TOKEN"} return cfg } diff --git a/internal/app/constraints.go b/internal/app/constraints.go index 447d4819..90244e8a 100644 --- a/internal/app/constraints.go +++ b/internal/app/constraints.go @@ -108,6 +108,9 @@ var ( gGitHubRepository = grammar{"GitHub repository", regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}$`), "owner/name, such as labstack/shop"} + gGitHubTokenEnv = grammar{"GitHub token variable", regexp.MustCompile(`^[A-Z0-9_]*(GH|GITHUB)[A-Z0-9_]*TOKEN$`), + "an upper-case variable name containing GH or GITHUB and ending in TOKEN, such as SHOP_GH_TOKEN"} + gRegistryUser = grammar{"registry username", regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._@+-]*$`), "a username of letters, digits and . _ @ + -"} diff --git a/internal/app/jsonschema.go b/internal/app/jsonschema.go index 09a856b2..83d981b4 100644 --- a/internal/app/jsonschema.go +++ b/internal/app/jsonschema.go @@ -606,7 +606,7 @@ var schemaConstraints = []struct { {[]string{"registries", "*", "username"}, pattern(gRegistryUser)}, {[]string{"registries", "*", "password_env"}, pattern(gEnvName)}, {[]string{"github", "repository"}, pattern(gGitHubRepository)}, - {[]string{"github", "token_env"}, pattern(gEnvName)}, + {[]string{"github", "token_env"}, pattern(gGitHubTokenEnv)}, {[]string{"github", "api_url"}, pattern(gHTTPURL)}, {[]string{"github"}, map[string]any{"required": []any{"repository"}}}, {[]string{"notifications", "*", "format"}, enum(eNotifyFormat)}, diff --git a/internal/app/types.go b/internal/app/types.go index 252a8983..767ac1ef 100644 --- a/internal/app/types.go +++ b/internal/app/types.go @@ -529,8 +529,8 @@ type Notification struct { // so scheduled jobs and other host-fired work do not report. type GitHub struct { Repository string `json:"repository" description:"GitHub repository, as owner/name, whose deployments record each deploy and rollback. Workload images whose org.opencontainers.image.source label names this repository are reported at their org.opencontainers.image.revision commit; when none does, the clean checkout's commit is reported if the checkout is a clone of this repository. Each image repository is reported in its own GitHub environment, named like production (shop-web); a configuration-only repository is named after the application." example:"labstack/shop"` - APIURL string `json:"api_url,omitempty" description:"GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. A github.com token is never sent to another host: there the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host." default:"https://api.github.com" example:"https://github.example.com/api/v3"` - TokenEnv string `json:"token_env,omitempty" description:"Local environment-variable name containing a GitHub token with Deployments write access. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation." example:"GH_TOKEN"` + APIURL string `json:"api_url,omitempty" description:"GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. Because the project file names the host, ob sends a token there only when the operator's environment confirms the same URL in ONEBOX_GITHUB_API_URL, and never sends it a github.com token: the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host." default:"https://api.github.com" example:"https://github.example.com/api/v3"` + TokenEnv string `json:"token_env,omitempty" description:"Local environment-variable name containing a GitHub token with Deployments write access; it must contain GH or GITHUB and end in TOKEN, so a project file cannot name some other secret. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation." example:"GH_TOKEN"` } type Registry struct { diff --git a/internal/app/validate.go b/internal/app/validate.go index 3e8169af..05d0e718 100644 --- a/internal/app/validate.go +++ b/internal/app/validate.go @@ -216,7 +216,7 @@ func validateTopLevel(p *Spec) error { // The token travels in a header on every request. return errf("project_invalid", "github.api_url", "", "%q must use https, because every request carries the token", p.GitHub.APIURL) } - if err := gEnvName.checkOptional("github.token_env", p.GitHub.TokenEnv); err != nil { + if err := gGitHubTokenEnv.checkOptional("github.token_env", p.GitHub.TokenEnv); err != nil { return err } } diff --git a/internal/ghdeploy/ghdeploy.go b/internal/ghdeploy/ghdeploy.go index 3600933b..a9942db3 100644 --- a/internal/ghdeploy/ghdeploy.go +++ b/internal/ghdeploy/ghdeploy.go @@ -23,6 +23,7 @@ import ( "net/url" "os" "os/exec" + "regexp" "strings" "sync" "time" @@ -320,20 +321,39 @@ func (c *Client) post(ctx context.Context, method, token, path string, body []by return retryNever, nil } +// TokenEnvPattern is the shape a github.tokenEnv name must have: a GitHub +// token variable, such as SHOP_GH_TOKEN. The project file names the variable, +// so the pattern keeps it from naming some other secret to send. +var TokenEnvPattern = regexp.MustCompile(`^[A-Z0-9_]*(GH|GITHUB)[A-Z0-9_]*TOKEN$`) + +// ConfirmAPIURLEnv is the operator's confirmation of a non-default API host. +// The project file names the host, so a token is sent there only when the +// operator's own environment names the same URL. +const ConfirmAPIURLEnv = "ONEBOX_GITHUB_API_URL" + // ResolveToken finds the operator's token for the API at apiURL ("" is // api.github.com). For github.com it is the variable named by tokenEnv, // otherwise GH_TOKEN, GITHUB_TOKEN, then `gh auth token`. // -// Any other host is named by the project file, so it never receives a -// github.com token: there it is tokenEnv (which may not name GH_TOKEN or -// GITHUB_TOKEN), otherwise GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, then +// Any other host is named by the project file, so it needs the operator's +// confirmation in ONEBOX_GITHUB_API_URL and never receives a github.com +// token: there it is tokenEnv (which may not name GH_TOKEN or GITHUB_TOKEN), +// otherwise GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, then // `gh auth token --hostname HOST`, which gh answers only with that host's // token. Errors describe where it looked, never a value. func ResolveToken(ctx context.Context, tokenEnv, apiURL string) (string, error) { host := WebHost(apiURL) - public := host == "github.com" + public := apiURL == "" || strings.TrimSuffix(apiURL, "/") == DefaultBaseURL + if !public { + if strings.TrimSuffix(strings.TrimSpace(os.Getenv(ConfirmAPIURLEnv)), "/") != strings.TrimSuffix(apiURL, "/") { + return "", fmt.Errorf("github.apiUrl %s is set by the project file; confirm it by exporting %s=%s", apiURL, ConfirmAPIURLEnv, apiURL) + } + } if tokenEnv != "" { - if !public && (tokenEnv == "GH_TOKEN" || tokenEnv == "GITHUB_TOKEN") { + if !TokenEnvPattern.MatchString(tokenEnv) { + return "", fmt.Errorf("github.tokenEnv %s is not a GitHub token variable; its name must contain GH or GITHUB and end in TOKEN", tokenEnv) + } + if !public && (strings.EqualFold(tokenEnv, "GH_TOKEN") || strings.EqualFold(tokenEnv, "GITHUB_TOKEN")) { return "", fmt.Errorf("github.tokenEnv %s holds a github.com token and is never sent to %s; name a variable holding a token for that host", tokenEnv, host) } if v := strings.TrimSpace(os.Getenv(tokenEnv)); v != "" { diff --git a/internal/ghdeploy/ghdeploy_test.go b/internal/ghdeploy/ghdeploy_test.go index 51fd9af2..c24f1ea3 100644 --- a/internal/ghdeploy/ghdeploy_test.go +++ b/internal/ghdeploy/ghdeploy_test.go @@ -293,16 +293,16 @@ func TestADeadGitHubCostsAtMostTheBudget(t *testing.T) { } func TestResolveTokenPrefersTheNamedVariable(t *testing.T) { - t.Setenv("SHOP_GH", "named") + t.Setenv("SHOP_GH_TOKEN", "named") t.Setenv("GH_TOKEN", "gh") - if got, err := ResolveToken(t.Context(), "SHOP_GH", ""); err != nil || got != "named" { + if got, err := ResolveToken(t.Context(), "SHOP_GH_TOKEN", ""); err != nil || got != "named" { t.Fatalf("ResolveToken = %q, %v", got, err) } if got, err := ResolveToken(t.Context(), "", ""); err != nil || got != "gh" { t.Fatalf("ResolveToken = %q, %v", got, err) } - t.Setenv("SHOP_GH", "") - if _, err := ResolveToken(t.Context(), "SHOP_GH", ""); err == nil || !strings.Contains(err.Error(), "SHOP_GH") { + t.Setenv("SHOP_GH_TOKEN", "") + if _, err := ResolveToken(t.Context(), "SHOP_GH_TOKEN", ""); err == nil || !strings.Contains(err.Error(), "SHOP_GH_TOKEN") { t.Fatalf("empty named variable: err = %v", err) } } @@ -313,15 +313,31 @@ func TestAnotherHostNeverReceivesAGitHubComToken(t *testing.T) { t.Setenv("GH_ENTERPRISE_TOKEN", "") t.Setenv("GITHUB_ENTERPRISE_TOKEN", "") t.Setenv("PATH", t.TempDir()) // no gh to fall back to + t.Setenv("AWS_SECRET_ACCESS_KEY", "aws") + t.Setenv("EVIL_GH_TOKEN", "named") const evil = "https://api.evil.example" - for _, tokenEnv := range []string{"", "GH_TOKEN", "GITHUB_TOKEN"} { + t.Setenv(ConfirmAPIURLEnv, "") + // An unconfirmed host gets nothing, whatever the project file names. + for _, tokenEnv := range []string{"", "EVIL_GH_TOKEN", "AWS_SECRET_ACCESS_KEY"} { + if got, err := ResolveToken(t.Context(), tokenEnv, evil); err == nil || got != "" || !strings.Contains(err.Error(), ConfirmAPIURLEnv) { + t.Fatalf("unconfirmed, tokenEnv %q: got %q, err %v", tokenEnv, got, err) + } + } + t.Setenv(ConfirmAPIURLEnv, evil) + for _, tokenEnv := range []string{"", "GH_TOKEN", "gh_token", "GITHUB_TOKEN", "AWS_SECRET_ACCESS_KEY"} { got, err := ResolveToken(t.Context(), tokenEnv, evil) - if err == nil || got != "" || strings.Contains(err.Error(), "github-com-token") { - t.Fatalf("tokenEnv %q: got %q, err %v", tokenEnv, got, err) + if err == nil || got != "" || strings.Contains(err.Error(), "github-com-token") || strings.Contains(err.Error(), "aws") && !strings.Contains(err.Error(), "AWS") { + t.Fatalf("confirmed, tokenEnv %q: got %q, err %v", tokenEnv, got, err) } } + // Even for github.com, tokenEnv cannot name a secret that is not a token. + if got, err := ResolveToken(t.Context(), "AWS_SECRET_ACCESS_KEY", ""); err == nil || got != "" { + t.Fatalf("github.com, foreign variable: got %q, err %v", got, err) + } + const ghes = "https://ghe.example.com/api/v3" + t.Setenv(ConfirmAPIURLEnv, ghes+"/") t.Setenv("GH_ENTERPRISE_TOKEN", "enterprise") - if got, err := ResolveToken(t.Context(), "", "https://ghe.example.com/api/v3"); err != nil || got != "enterprise" { + if got, err := ResolveToken(t.Context(), "", ghes); err != nil || got != "enterprise" { t.Fatalf("enterprise: %q, %v", got, err) } } diff --git a/site/public/schemas/application/v1alpha2/application.schema.json b/site/public/schemas/application/v1alpha2/application.schema.json index f8c4ce7c..2c275576 100644 --- a/site/public/schemas/application/v1alpha2/application.schema.json +++ b/site/public/schemas/application/v1alpha2/application.schema.json @@ -773,7 +773,7 @@ "properties": { "apiUrl": { "default": "https://api.github.com", - "description": "GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. A github.com token is never sent to another host: there the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL.", + "description": "GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. Because the project file names the host, ob sends a token there only when the operator's environment confirms the same URL in ONEBOX_GITHUB_API_URL, and never sends it a github.com token: the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL.", "examples": [ "https://github.example.com/api/v3" ], @@ -789,11 +789,11 @@ "type": "string" }, "tokenEnv": { - "description": "Local environment-variable name containing a GitHub token with Deployments write access. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects a variable name of letters, digits and underscores, not starting with a digit.", + "description": "Local environment-variable name containing a GitHub token with Deployments write access; it must contain GH or GITHUB and end in TOKEN, so a project file cannot name some other secret. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects an upper-case variable name containing GH or GITHUB and ending in TOKEN, such as SHOP_GH_TOKEN.", "examples": [ "GH_TOKEN" ], - "pattern": "^[A-Za-z_][A-Za-z0-9_]*$", + "pattern": "^[A-Z0-9_]*(GH|GITHUB)[A-Z0-9_]*TOKEN$", "type": "string" } }, diff --git a/site/src/content/docs/docs/guides/github-deployments.mdx b/site/src/content/docs/docs/guides/github-deployments.mdx index 889349a4..b6cb8075 100644 --- a/site/src/content/docs/docs/guides/github-deployments.mdx +++ b/site/src/content/docs/docs/guides/github-deployments.mdx @@ -33,10 +33,19 @@ started, report nothing. `ob` reports the same way from a terminal, an agent or a [GitHub Actions workflow](/docs/guides/deploy-from-github-actions). For GitHub Enterprise, set `apiUrl` to the API base, such as -`https://github.example.com/api/v3` or `https://api.acme.ghe.com`. A -github.com token is never sent there: `ob` uses `tokenEnv`, then -`GH_ENTERPRISE_TOKEN`, `GITHUB_ENTERPRISE_TOKEN`, or the token `gh` holds for -that host. +`https://github.example.com/api/v3` or `https://api.acme.ghe.com`, and confirm +it in your own environment with the same URL: + +```sh +export ONEBOX_GITHUB_API_URL=https://github.example.com/api/v3 +``` + +A project file names the host, so without that confirmation `ob` sends no +token there. A github.com token is never sent to it either: `ob` uses +`tokenEnv`, then `GH_ENTERPRISE_TOKEN`, `GITHUB_ENTERPRISE_TOKEN`, or the token +`gh` holds for that host. For the same reason `tokenEnv` must name a GitHub +token variable, containing `GH` or `GITHUB` and ending in `TOKEN`, such as +`SHOP_GH_TOKEN`. ## The token stays where `ob` runs diff --git a/site/src/content/docs/docs/reference/fields/github.mdx b/site/src/content/docs/docs/reference/fields/github.mdx index d3a2ae91..636ebba8 100644 --- a/site/src/content/docs/docs/reference/fields/github.mdx +++ b/site/src/content/docs/docs/reference/fields/github.mdx @@ -23,8 +23,8 @@ cannot drift from what `ob validate` accepts. | Field | Type | Default | What it does | | --- | --- | --- | --- | -| `apiUrl` | string | `https://api.github.com` | GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. A github.com token is never sent to another host: there the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL. | +| `apiUrl` | string | `https://api.github.com` | GitHub REST API base URL for GitHub Enterprise Server (https://HOST/api/v3) or GitHub Enterprise Cloud with data residency (https://api.SUBDOMAIN.ghe.com). Image source labels and checkout remotes are matched against the same host. Because the project file names the host, ob sends a token there only when the operator's environment confirms the same URL in ONEBOX_GITHUB_API_URL, and never sends it a github.com token: the token comes from tokenEnv, GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN, or gh auth token --hostname for that host. Expects an http or https URL. | | `repository` `*` | string | — | GitHub repository, as owner/name, whose deployments record each deploy and rollback. Workload images whose org.opencontainers.image.source label names this repository are reported at their org.opencontainers.image.revision commit; when none does, the clean checkout's commit is reported if the checkout is a clone of this repository. Each image repository is reported in its own GitHub environment, named like production (shop-web); a configuration-only repository is named after the application. Expects owner/name, such as labstack/shop. | -| `tokenEnv` | string | — | Local environment-variable name containing a GitHub token with Deployments write access. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects a variable name of letters, digits and underscores, not starting with a digit. | +| `tokenEnv` | string | — | Local environment-variable name containing a GitHub token with Deployments write access; it must contain GH or GITHUB and end in TOKEN, so a project file cannot name some other secret. When unset, GH_TOKEN, then GITHUB_TOKEN, then gh auth token is used. A missing token or a failed GitHub call is a warning, never a blocked operation. Expects an upper-case variable name containing GH or GITHUB and ending in TOKEN, such as SHOP_GH_TOKEN. | `*` marks a field that is required within its own object.