From 92b820b234283988869bffc05f5138810a729369 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Sat, 5 Dec 2026 21:41:34 +0000 Subject: [PATCH] Select delivery credentials by execution context --- cmd/releasekit/destination_test.go | 2 +- cmd/releasekit/internal/cli/config.go | 34 +++++-- cmd/releasekit/internal/cli/config_test.go | 18 ++++ cmd/releasekit/internal/cli/credentials.go | 65 +++++++++++++ cmd/releasekit/main.go | 32 ++----- cmd/releasekit/main_test.go | 32 +++++-- .../multi_module_woodpecker_test.go | 2 +- cmd/releasekit/release_wrapper_test.go | 10 +- .../releasekit_delivery_workflow_test.go | 13 ++- cmd/releasekit/token_file_test.go | 93 ++++++++++--------- docs/cli.md | 6 +- docs/config.md | 29 +++--- docs/consumers/delivery.md | 23 +++-- docs/release.md | 4 +- docs/roadmap/implementation.md | 7 ++ examples/multi-module/README.md | 3 +- examples/multi-module/woodpecker.yml | 1 + examples/releasekit-binary.json | 15 ++- examples/releasekit.json | 9 +- .../woodpecker/releasekit-source-delivery.yml | 1 + examples/woodpecker/tag-delivery.yml | 1 + releasekit.json | 14 ++- 22 files changed, 287 insertions(+), 127 deletions(-) create mode 100644 cmd/releasekit/internal/cli/credentials.go diff --git a/cmd/releasekit/destination_test.go b/cmd/releasekit/destination_test.go index f155bb4..818b876 100644 --- a/cmd/releasekit/destination_test.go +++ b/cmd/releasekit/destination_test.go @@ -23,7 +23,7 @@ func TestInvalidDeliveryDestinationStopsBeforePreparation(t *testing.T) { http.Error(w, "unexpected request", http.StatusInternalServerError) })) defer server.Close() - destination := &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN"} + destination := &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}} switch setting { case "URL": destination.BaseURL = "ssh://forge.example" diff --git a/cmd/releasekit/internal/cli/config.go b/cmd/releasekit/internal/cli/config.go index 7d3b109..457a44d 100644 --- a/cmd/releasekit/internal/cli/config.go +++ b/cmd/releasekit/internal/cli/config.go @@ -264,12 +264,26 @@ type GoValidationSettings struct { // DeliverySettings selects the hosted forge release destination. type DeliverySettings struct { - Forge string `json:"forge,omitempty"` - BaseURL string `json:"base_url"` - Owner string `json:"owner"` - Repository string `json:"repository"` - TokenEnv string `json:"token_env,omitempty"` - TokenFile string `json:"token_file,omitempty"` + Forge string `json:"forge,omitempty"` + BaseURL string `json:"base_url"` + Owner string `json:"owner"` + Repository string `json:"repository"` + Credentials *DeliveryCredentials `json:"credentials,omitempty"` + LegacyTokenEnv json.RawMessage `json:"token_env,omitempty"` + LegacyTokenFile json.RawMessage `json:"token_file,omitempty"` +} + +type DeliveryCredentials struct { + Local *LocalCredential `json:"local,omitempty"` + CI *CICredential `json:"ci,omitempty"` +} + +type LocalCredential struct { + TokenFile string `json:"token_file"` +} + +type CICredential struct { + TokenEnvironmentVariable string `json:"token_environment_variable,omitempty"` } // BuildSettings selects the Go application package, artifact name, and targets. @@ -316,6 +330,14 @@ func LoadSettings(repoDir, configPath string) (Settings, error) { if strings.TrimSpace(settings.Product) == "" { return Settings{}, fmt.Errorf("profile %q: product is required", configPath) } + if delivery := settings.Delivery; delivery != nil { + if delivery.LegacyTokenFile != nil { + return Settings{}, fmt.Errorf("profile %q: delivery.token_file has moved to delivery.credentials.local.token_file", configPath) + } + if delivery.LegacyTokenEnv != nil { + return Settings{}, fmt.Errorf("profile %q: delivery.token_env has moved to delivery.credentials.ci.token_environment_variable", configPath) + } + } if source := settings.SourceSpec(); source != nil { _, err := releaseidentity.NormalizeSource(settings.ModuleDir, source) if err != nil { diff --git a/cmd/releasekit/internal/cli/config_test.go b/cmd/releasekit/internal/cli/config_test.go index 15ecd4c..cf5ba61 100644 --- a/cmd/releasekit/internal/cli/config_test.go +++ b/cmd/releasekit/internal/cli/config_test.go @@ -157,6 +157,24 @@ func TestLoadSettingsResolvesPathsAndPreservesArguments(t *testing.T) { } } +func TestLoadSettingsReportsObsoleteDeliveryCredentials(t *testing.T) { + for _, test := range []struct{ field, replacement string }{ + {"token_file", "delivery.credentials.local.token_file"}, + {"token_env", "delivery.credentials.ci.token_environment_variable"}, + } { + t.Run(test.field, func(t *testing.T) { + repo := t.TempDir() + profile := `{"product":"Example","delivery":{"` + test.field + `":null}}` + if err := os.WriteFile(filepath.Join(repo, "releasekit.json"), []byte(profile), 0600); err != nil { + t.Fatal(err) + } + if _, err := LoadSettings(repo, ""); err == nil || !strings.Contains(err.Error(), test.replacement) { + t.Fatalf("legacy field error = %v, want migration to %s", err, test.replacement) + } + }) + } +} + func TestLoadSettingsDefaultsRemoteAndConfigPath(t *testing.T) { repoDir := t.TempDir() contents := `{"product":"Example"}` diff --git a/cmd/releasekit/internal/cli/credentials.go b/cmd/releasekit/internal/cli/credentials.go new file mode 100644 index 0000000..318ef89 --- /dev/null +++ b/cmd/releasekit/internal/cli/credentials.go @@ -0,0 +1,65 @@ +package cli + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "go.maximumdirect.net/releasekit/internal/git" +) + +type CredentialContext string + +const ( + LocalCredentials CredentialContext = "local" + CICredentials CredentialContext = "ci" +) + +// CredentialSource identifies the selected source without exposing its token. +type CredentialSource struct { + Context CredentialContext + Source string +} + +// ResolveDeliveryCredential reads only the credential selected by context. +func ResolveDeliveryCredential(repositoryDir string, credentials *DeliveryCredentials, context CredentialContext) (string, CredentialSource, error) { + source := CredentialSource{Context: context} + switch context { + case LocalCredentials: + if credentials == nil || credentials.Local == nil || strings.TrimSpace(credentials.Local.TokenFile) == "" { + return "", source, errors.New("local delivery requires delivery.credentials.local.token_file") + } + name := credentials.Local.TokenFile + if !filepath.IsAbs(name) { + name = filepath.Join(repositoryDir, name) + } + source.Source = git.DisplayDiagnostic(name) + contents, err := os.ReadFile(name) + if err != nil { + return "", source, fmt.Errorf("read local delivery token file: %s", git.DisplayDiagnostic(err.Error())) + } + token := strings.TrimSpace(string(contents)) + if token == "" { + return "", source, fmt.Errorf("local delivery token file %q is empty or blank", source.Source) + } + return token, source, nil + case CICredentials: + if credentials == nil || credentials.CI == nil { + return "", source, errors.New("CI delivery requires delivery.credentials.ci") + } + name := credentials.CI.TokenEnvironmentVariable + if strings.TrimSpace(name) == "" { + name = "RELEASEKIT_DELIVERY_TOKEN" + } + source.Source = name + token, ok := os.LookupEnv(name) + if !ok || strings.TrimSpace(token) == "" { + return "", source, fmt.Errorf("CI delivery requires a non-empty token in environment variable %s", git.DisplayDiagnostic(name)) + } + return strings.TrimSpace(token), source, nil + default: + return "", source, errors.New("unknown delivery credential context") + } +} diff --git a/cmd/releasekit/main.go b/cmd/releasekit/main.go index 3386393..cb653c7 100644 --- a/cmd/releasekit/main.go +++ b/cmd/releasekit/main.go @@ -437,7 +437,7 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder fmt.Fprintln(stderr, "build targets require Go capability") return 2 } - destination, status := deliveryDestination(invocation.Repository, settings, stderr) + destination, status := deliveryDestination(invocation.Repository, settings, cli.CICredentials, stderr) if status != 0 { return status } @@ -460,14 +460,14 @@ func runCIDelivery(ctx context.Context, invocation cli.Invocation, stdout, stder // deliverWithSettings adapts prepared CLI state to the public delivery facade. // CI entry points can reuse it after preparing the checkout and loading its profile. func deliverWithSettings(ctx context.Context, invocation cli.Invocation, settings cli.Settings, stdout, stderr io.Writer) int { - destination, status := deliveryDestination(invocation.Repository, settings, stderr) + destination, status := deliveryDestination(invocation.Repository, settings, cli.LocalCredentials, stderr) if status != 0 { return status } return deliverWithDestination(ctx, invocation, settings, destination, stdout, stderr) } -func deliveryDestination(repositoryDir string, settings cli.Settings, stderr io.Writer) (releasekit.DeliveryDestination, int) { +func deliveryDestination(repositoryDir string, settings cli.Settings, context cli.CredentialContext, stderr io.Writer) (releasekit.DeliveryDestination, int) { delivery := settings.Delivery if delivery == nil { fmt.Fprintln(stderr, "deliver requires an explicit delivery.forge selection in the profile") @@ -486,29 +486,9 @@ func deliveryDestination(repositoryDir string, settings cli.Settings, stderr io. fmt.Fprintln(stderr, "deliver requires base_url, owner, and repository in the profile delivery settings") return releasekit.DeliveryDestination{}, 2 } - tokenEnv := delivery.TokenEnv - if strings.TrimSpace(tokenEnv) == "" { - tokenEnv = "RELEASEKIT_GITEA_TOKEN" - } - token, ok := os.LookupEnv(tokenEnv) - if (!ok || strings.TrimSpace(token) == "") && delivery.TokenFile != "" { - name := delivery.TokenFile - if !filepath.IsAbs(name) { - name = filepath.Join(repositoryDir, name) - } - contents, err := os.ReadFile(name) - if err != nil { - fmt.Fprintf(stderr, "read delivery token file: %v\n", err) - return releasekit.DeliveryDestination{}, 2 - } - token = strings.TrimSpace(string(contents)) - if token == "" { - fmt.Fprintln(stderr, "delivery token file is empty or blank") - return releasekit.DeliveryDestination{}, 2 - } - } - if strings.TrimSpace(token) == "" { - fmt.Fprintf(stderr, "deliver requires a non-empty token in environment variable %s\n", tokenEnv) + token, _, err := cli.ResolveDeliveryCredential(repositoryDir, delivery.Credentials, context) + if err != nil { + fmt.Fprintln(stderr, err) return releasekit.DeliveryDestination{}, 2 } return releasekit.DeliveryDestination{Forge: releasekit.ForgeGitea, BaseURL: delivery.BaseURL, Owner: delivery.Owner, Repository: delivery.Repository, Token: token}, 0 diff --git a/cmd/releasekit/main_test.go b/cmd/releasekit/main_test.go index fafe484..041292e 100644 --- a/cmd/releasekit/main_test.go +++ b/cmd/releasekit/main_test.go @@ -1212,13 +1212,13 @@ func TestDeliverRequiresCredentialBeforeRemoteRequests(t *testing.T) { state := &deliveryServerState{} server := newDeliveryServer(t, state) defer server.Close() - writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}) + writeDeliveryProfile(t, repository, cli.Settings{Product: "Example Product", Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{}}}}) state.update(func(state *deliveryServerData) { state.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) cliGitRun(t, repository, "tag", "v1.2.3") - t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "") + t.Setenv("RELEASEKIT_TEST_DELIVERY_TOKEN", "ambient-token") var stdout, stderr bytes.Buffer status := run(context.Background(), []string{"deliver", "--repo", repository, "v1.2.3"}, &stdout, &stderr) - if status != 2 || state.snapshot().apiRequests != 0 || !strings.Contains(stderr.String(), "RELEASEKIT_TEST_DELIVERY_TOKEN") { + if status != 2 || state.snapshot().apiRequests != 0 || !strings.Contains(stderr.String(), "delivery.credentials.local.token_file") { t.Fatalf("missing credential status=%d requests=%d stdout=%q stderr=%q", status, state.snapshot().apiRequests, stdout.String(), stderr.String()) } } @@ -1235,7 +1235,7 @@ func TestDeliverRejectsMissingBlankAndUnsupportedForgeBeforeTokenOrBuild(t *test Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Delivery: &cli.DeliverySettings{ Forge: forge, BaseURL: server.URL, Owner: "owner", Repository: "example", - TokenFile: filepath.Join(repository, "missing-token"), + Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: filepath.Join(repository, "missing-token")}}, }, }) state.update(func(data *deliveryServerData) { data.commit = cliGitOutput(t, repository, "rev-parse", "HEAD") }) @@ -1273,7 +1273,7 @@ func TestCIDeliverRejectsUnsupportedForgeBeforeTokenOrDependencyPreparation(t *t Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Delivery: &cli.DeliverySettings{ Forge: "unsupported", BaseURL: server.URL, Owner: "owner", Repository: "example", - TokenFile: filepath.Join(repository, "missing-token"), + Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: filepath.Join(repository, "missing-token")}}, }, }) expectedCommit := pushTaggedCLIRepository(t, repository) @@ -1325,7 +1325,7 @@ func TestCIDeliverPageOnlyReportsUnavailablePreflightWithStatusOne(t *testing.T) writeDeliveryProfile(t, repository, cli.Settings{ Product: "Example Product", Delivery: &cli.DeliverySettings{ - Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN", + Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}, }, }) expectedCommit := pushTaggedCLIRepository(t, repository) @@ -1367,7 +1367,7 @@ func TestDeliverUnavailablePreflightStopsBeforeManagedBuild(t *testing.T) { Product: "Example Product", Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Delivery: &cli.DeliverySettings{ - Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN", + Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}, }, }) cliGitRun(t, repository, "tag", "v1.2.3") @@ -1419,7 +1419,7 @@ func TestCIDeliverUnavailablePreflightStopsBeforeDependencyPreparation(t *testin Product: "Example Product", Build: &cli.BuildSettings{MainPackage: ".", BinaryName: "helper", Targets: []string{"linux/amd64"}}, Delivery: &cli.DeliverySettings{ - Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_TEST_DELIVERY_TOKEN", + Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_DELIVERY_TOKEN"}}, }, }) expectedCommit := pushTaggedCLIRepository(t, repository) @@ -1751,6 +1751,22 @@ func writeDeliveryProfile(t *testing.T, repository string, settings cli.Settings func writeDeliveryProfileAt(t *testing.T, repository, name string, settings cli.Settings) { t.Helper() + if settings.Delivery != nil { + if settings.Delivery.Credentials == nil { + settings.Delivery.Credentials = &cli.DeliveryCredentials{} + } + credentials := settings.Delivery.Credentials + if credentials.Local == nil { + path := filepath.Join(t.TempDir(), "token") + if err := os.WriteFile(path, []byte("fixture-token"), 0o600); err != nil { + t.Fatal(err) + } + credentials.Local = &cli.LocalCredential{TokenFile: path} + } + if credentials.CI == nil { + credentials.CI = &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"} + } + } contents, err := json.Marshal(settings) if err != nil { t.Fatal(err) diff --git a/cmd/releasekit/multi_module_woodpecker_test.go b/cmd/releasekit/multi_module_woodpecker_test.go index 995178f..68c0db6 100644 --- a/cmd/releasekit/multi_module_woodpecker_test.go +++ b/cmd/releasekit/multi_module_woodpecker_test.go @@ -388,7 +388,7 @@ func workflowModuleFile(module, version string) string { } func workflowDeliverySettings(baseURL string) *cli.DeliverySettings { - return &cli.DeliverySettings{Forge: "gitea", BaseURL: baseURL, Owner: "owner", Repository: "example", TokenEnv: "RELEASEKIT_GITEA_TOKEN"} + return &cli.DeliverySettings{Forge: "gitea", BaseURL: baseURL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}}} } func writeMappedProfile(t *testing.T, repository, name string, settings cli.Settings) { diff --git a/cmd/releasekit/release_wrapper_test.go b/cmd/releasekit/release_wrapper_test.go index f7ed6f3..c5c8c92 100644 --- a/cmd/releasekit/release_wrapper_test.go +++ b/cmd/releasekit/release_wrapper_test.go @@ -79,11 +79,11 @@ func TestReleaseCandidate(t *testing.T) { "product": "ReleaseKit", "checks": []map[string]any{{"args": []string{"sh", "-c", "if [ -n \"$RELEASEKIT_TEST_ARM_GIT_SHIM\" ]; then : > \"$RELEASEKIT_TEST_ARM_GIT_SHIM\"; fi"}}}, "delivery": map[string]any{ - "forge": "gitea", - "base_url": "https://forge.maximumdirect.net", - "owner": "base-layer", - "repository": "releasekit", - "token_env": "RELEASEKIT_GITEA_TOKEN", + "forge": "gitea", + "base_url": "https://forge.maximumdirect.net", + "owner": "base-layer", + "repository": "releasekit", + "credentials": map[string]any{"ci": map[string]string{"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}}, }, } content, _ := json.Marshal(profile) diff --git a/cmd/releasekit/releasekit_delivery_workflow_test.go b/cmd/releasekit/releasekit_delivery_workflow_test.go index 2aae7be..24cb03c 100644 --- a/cmd/releasekit/releasekit_delivery_workflow_test.go +++ b/cmd/releasekit/releasekit_delivery_workflow_test.go @@ -24,7 +24,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) { if profile.Build != nil && len(profile.Build.Targets) != 0 { t.Fatalf("ReleaseKit profile declares binary targets: %#v", profile.Build.Targets) } - if profile.Delivery == nil || profile.Delivery.BaseURL != "https://forge.maximumdirect.net" || profile.Delivery.Owner != "base-layer" || profile.Delivery.Repository != "releasekit" || profile.Delivery.TokenEnv != "RELEASEKIT_GITEA_TOKEN" { + if profile.Delivery == nil || profile.Delivery.BaseURL != "https://forge.maximumdirect.net" || profile.Delivery.Owner != "base-layer" || profile.Delivery.Repository != "releasekit" || profile.Delivery.Credentials == nil || profile.Delivery.Credentials.CI == nil || profile.Delivery.Credentials.CI.TokenEnvironmentVariable != "RELEASEKIT_GITEA_TOKEN" { t.Fatalf("ReleaseKit delivery profile = %#v", profile.Delivery) } repository := filepath.Join(t.TempDir(), "tagged ReleaseKit") @@ -34,6 +34,15 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) { } cliGitRun(t, repository, "config", "user.name", "ReleaseKit Test") cliGitRun(t, repository, "config", "user.email", "releasekit@example.test") + // The workflow builds the tagged CLI, including changes under test that may + // not yet be committed in the repository from which this fixture was cloned. + for _, name := range []string{"cmd/releasekit/main.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go"} { + contents, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(name))) + if err != nil { + t.Fatal(err) + } + writeRepositoryFile(t, repository, name, string(contents)) + } const version = "v1.2.3" note := "# ReleaseKit v1.2.3\n\nSource-only delivery fixture.\n\n" + @@ -47,7 +56,7 @@ func TestReleaseKitSourceDeliveryWorkflowFromTaggedCheckout(t *testing.T) { if err := os.WriteFile(notePath, []byte(note), 0o600); err != nil { t.Fatal(err) } - cliGitRun(t, repository, "add", "docs/releases/"+version+".md") + cliGitRun(t, repository, "add", "docs/releases/"+version+".md", "cmd/releasekit/main.go", "cmd/releasekit/internal/cli/config.go", "cmd/releasekit/internal/cli/credentials.go") cliGitRun(t, repository, "commit", "-m", "prepare source-only delivery") state := &deliveryServerState{data: deliveryServerData{product: "ReleaseKit"}} diff --git a/cmd/releasekit/token_file_test.go b/cmd/releasekit/token_file_test.go index fc60b0b..e1f6bdb 100644 --- a/cmd/releasekit/token_file_test.go +++ b/cmd/releasekit/token_file_test.go @@ -11,45 +11,48 @@ import ( "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli" ) -func TestDeliveryTokenFileSelection(t *testing.T) { +func TestDeliveryCredentialSelection(t *testing.T) { + repository := t.TempDir() + path := filepath.Join(repository, "token") + if err := os.WriteFile(path, []byte(" file-secret \n"), 0600); err != nil { + t.Fatal(err) + } + t.Setenv("RELEASEKIT_TEST_TOKEN", " ambient-secret ") + credentials := &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: "token"}, CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_TEST_TOKEN"}} for _, test := range []struct { - name, env, contents, file, want string - status int - }{ - {name: "relative file", contents: "fixture-token\n", file: "token", want: "fixture-token"}, - {name: "absolute file", contents: "fixture-token\n", file: "absolute", want: "fixture-token"}, - {name: "environment overrides missing file", env: "env-token", file: "missing", want: "env-token"}, - {name: "blank environment falls back", env: " \t", contents: "fixture-token\n", file: "token", want: "fixture-token"}, - {name: "missing file", file: "missing", status: 2}, - {name: "blank file", contents: " \n\t", file: "token", status: 2}, - {name: "empty file", file: "token", status: 2}, - {name: "unreadable as file", file: ".", status: 2}, - {name: "no credential", status: 2}, - } { - t.Run(test.name, func(t *testing.T) { - repository := t.TempDir() - if err := os.WriteFile(filepath.Join(repository, "token"), []byte(test.contents), 0o600); err != nil { - t.Fatal(err) - } - name := test.file - if name == "absolute" { - name = filepath.Join(repository, "token") - } - t.Setenv("RELEASEKIT_TEST_TOKEN", test.env) - var stderr bytes.Buffer - destination, status := deliveryDestination(repository, cli.Settings{Delivery: &cli.DeliverySettings{Forge: "gitea", - BaseURL: "https://gitea.example", Owner: "owner", Repository: "example", - TokenEnv: "RELEASEKIT_TEST_TOKEN", TokenFile: name, - }}, &stderr) - if status != test.status || destination.Token != test.want { - t.Fatalf("status=%d token matches=%t, want status=%d; diagnostics=%s", status, destination.Token == test.want, test.status, &stderr) - } - for _, secret := range []string{"fixture-token", "env-token"} { - if strings.Contains(stderr.String(), secret) { - t.Fatal("diagnostics exposed a token") - } - } - }) + context cli.CredentialContext + want string + }{{cli.LocalCredentials, "file-secret"}, {cli.CICredentials, "ambient-secret"}} { + token, source, err := cli.ResolveDeliveryCredential(repository, credentials, test.context) + if err != nil || token != test.want || source.Context != test.context { + t.Fatalf("context=%s token matches=%t source=%+v error=%v", test.context, token == test.want, source, err) + } + } + credentials.Local.TokenFile = "missing" + if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.LocalCredentials); err == nil || strings.Contains(err.Error(), "ambient-secret") { + t.Fatalf("missing local file error = %v", err) + } + if token, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.CICredentials); err != nil || token != "ambient-secret" { + t.Fatalf("CI credential with missing local file: token matches=%t error=%v", token == "ambient-secret", err) + } + credentials.Local.TokenFile = path + if err := os.WriteFile(path, []byte(" \t\n"), 0600); err != nil { + t.Fatal(err) + } + if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.LocalCredentials); err == nil { + t.Fatal("accepted blank file") + } + t.Setenv("RELEASEKIT_DELIVERY_TOKEN", "default-secret") + token, _, err := cli.ResolveDeliveryCredential(repository, &cli.DeliveryCredentials{CI: &cli.CICredential{}}, cli.CICredentials) + if err != nil || token != "default-secret" { + t.Fatalf("default CI credential matches=%t error=%v", token == "default-secret", err) + } + if _, _, err := cli.ResolveDeliveryCredential(repository, &cli.DeliveryCredentials{}, cli.CICredentials); err == nil { + t.Fatal("accepted missing CI declaration") + } + t.Setenv("RELEASEKIT_TEST_TOKEN", " ") + if _, _, err := cli.ResolveDeliveryCredential(repository, credentials, cli.CICredentials); err == nil { + t.Fatal("accepted blank CI token") } } @@ -58,7 +61,7 @@ func TestCheckReadsForbiddenFilesSelectionFromProfile(t *testing.T) { writeDeliveryProfile(t, repository, cli.Settings{ Product: "Example Product", Validation: &cli.ValidationSettings{ForbiddenFiles: []string{"token-file"}}, - Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: "https://gitea.example", Owner: "owner", Repository: "example", TokenFile: "missing-token-file"}, + Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: "https://gitea.example", Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: "missing-token-file"}}}, }) writeRepositoryFile(t, repository, "token-file", "fixture-secret\n") cliGitRun(t, repository, "add", "token-file") @@ -73,7 +76,7 @@ func TestCheckReadsForbiddenFilesSelectionFromProfile(t *testing.T) { } } -func TestDeliverAndCIDeliverReadTokenFileFromRepositoryRoot(t *testing.T) { +func TestDeliverAndCIDeliverSelectContextCredentials(t *testing.T) { for _, command := range []string{"deliver", "ci-deliver"} { t.Run(command, func(t *testing.T) { repository := newCLIRepository(t) @@ -82,15 +85,19 @@ func TestDeliverAndCIDeliverReadTokenFileFromRepositoryRoot(t *testing.T) { defer server.Close() writeDeliveryProfile(t, repository, cli.Settings{ Product: "Example Product", - Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", TokenFile: ".releasekit/token"}, + Delivery: &cli.DeliverySettings{Forge: "gitea", BaseURL: server.URL, Owner: "owner", Repository: "example", Credentials: &cli.DeliveryCredentials{Local: &cli.LocalCredential{TokenFile: ".releasekit/token"}, CI: &cli.CICredential{TokenEnvironmentVariable: "RELEASEKIT_GITEA_TOKEN"}}}, }) writeRepositoryFile(t, repository, ".gitignore", ".releasekit/\n") cliGitRun(t, repository, "add", ".gitignore") cliGitRun(t, repository, "commit", "-m", "ignore local delivery credentials") commit := pushTaggedCLIRepository(t, repository) state.update(func(data *deliveryServerData) { data.commit = commit }) - writeRepositoryFile(t, repository, ".releasekit/token", "fixture-token\n") - t.Setenv("RELEASEKIT_GITEA_TOKEN", "") + if command == "deliver" { + writeRepositoryFile(t, repository, ".releasekit/token", "fixture-token\n") + } else if err := os.MkdirAll(filepath.Join(repository, ".releasekit"), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("RELEASEKIT_GITEA_TOKEN", "fixture-token") var stdout, stderr bytes.Buffer args := []string{command, "--repo", filepath.Join(repository, ".releasekit")} if command == "ci-deliver" { diff --git a/docs/cli.md b/docs/cli.md index e706fde..653399a 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -249,8 +249,8 @@ go run ./cmd/releasekit deliver [--repo DIR] [--config FILE] [--assets DIR] VERS ``` `deliver` requires a `delivery` profile object with an explicit -`"forge": "gitea"` selection and a token loaded from its configured environment -variable or token file. The destination URL does not select a forge. Selection +`"forge": "gitea"` selection and a token loaded from its configured local +credential file. The destination URL does not select a forge. Selection errors are reported before token access or delivery work. Credential selection and errors are defined in the [configuration reference](config.md). It verifies the local tag, clean tagged checkout, hosted tag, and committed release note, @@ -323,7 +323,7 @@ In either mode, it loads the profile from the verified source. The optional selected directory against the profile. The command compares the selected source's derived release tag with the full event tag before forge access or dependency preparation, then validates explicit forge selection and resolves -the configured token. For binary profiles, it performs a read-only repository +the configured CI environment token. For binary profiles, it performs a read-only repository preflight before downloading application dependencies; delivery performs a fresh check after dependency preparation. Source-only profiles rely on delivery's automatic preflight and skip dependency diff --git a/docs/config.md b/docs/config.md index 8ac3186..f048e48 100644 --- a/docs/config.md +++ b/docs/config.md @@ -178,20 +178,23 @@ requirements still apply to candidate operations. An ignore rule alone does not remove a previously committed file from the candidate. The `delivery` object contains `forge`, `base_url`, `owner`, `repository`, and -optional `token_env` and `token_file`. A delivery request must set `forge` to -`"gitea"`; omission, an empty or whitespace-only value, and unsupported values -are errors when `deliver` or `ci-deliver` is requested. The URL does not select -the forge. These semantic checks run only for delivery, so `check`, `publish`, -and `build` do not require a delivery object, selection, or credentials. +context-specific `credentials`. A delivery request must set `forge` to +`"gitea"`; a missing or unsupported selection is an error for delivery. These +requirements do not apply to `check`, `publish`, or `build`. -`token_env` names the environment variable containing the Gitea token and -defaults to `RELEASEKIT_GITEA_TOKEN`. A nonblank environment value takes -precedence. When it is unset or blank, `token_file` selects a plain -token-containing file; relative paths resolve from the Git repository root, -and absolute paths are used as supplied. The CLI trims leading and trailing -whitespace from file contents. An unreadable or blank file, or the absence of -both credential sources, returns status 2. Omission of `token_file` retains -environment-only loading. +`delivery.credentials.local.token_file` selects the local delivery token file. +Relative paths resolve from the Git repository root; absolute paths are used as +supplied. `delivery.credentials.ci.token_environment_variable` selects the job +environment variable, defaulting to `RELEASEKIT_DELIVERY_TOKEN` when the `ci` +object is present without a name. `deliver` requires local credentials and +`ci-deliver` requires CI credentials. Neither context falls back to the other. +Missing, unreadable, or blank selected credentials fail with status 2. Token +contents are trimmed. The obsolete `delivery.token_file` and `delivery.token_env` +fields must be moved to their corresponding context-specific locations. + +Ignore the local token file in Git. Optionally select the same path in +`validation.forbidden_files` to reject candidates that include it; an ignore +rule does not remove an already tracked file. After resolving the token, delivery performs an authenticated, read-only repository access check. Invalid destination settings, missing or rejected diff --git a/docs/consumers/delivery.md b/docs/consumers/delivery.md index 2663721..d2e84c0 100644 --- a/docs/consumers/delivery.md +++ b/docs/consumers/delivery.md @@ -75,7 +75,10 @@ Add a Gitea destination to the profile: "base_url": "https://gitea.example", "owner": "example", "repository": "example", - "token_env": "RELEASEKIT_GITEA_TOKEN" + "credentials": { + "local": {"token_file": ".releasekit/gitea-token"}, + "ci": {"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"} + } } } ``` @@ -84,11 +87,11 @@ Fetch and check out the immutable tag, then deliver it: ```sh git checkout --detach v1.2.3 -RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver v1.2.3 +releasekit deliver v1.2.3 ``` -The CLI resolves the token for delivery using the configured environment -variable or token file. It verifies the local checkout and hosted tag before +The CLI resolves the local token file for `deliver` and the CI environment +variable for `ci-deliver`. It verifies the local checkout and hosted tag before creating or accepting a hosted release page. The full checked-in note is the hosted body. A retry accepts an identical page and matching attachments, adds only missing assets, and reports conflicts without replacing content. @@ -107,15 +110,15 @@ as `.releasekit/gitea-token` and configure: "base_url": "https://gitea.example", "owner": "example", "repository": "example", - "token_file": ".releasekit/gitea-token" + "credentials": {"local": {"token_file": ".releasekit/gitea-token"}} } } ``` Add `.releasekit/` to the consumer's ignore rules and use owner-only file permissions for the saved token. Then run `releasekit deliver v1.2.3` from the -tagged checkout. CI can continue supplying the environment token. See the -[configuration reference](../config.md) for precedence, path resolution, and the +tagged checkout. CI supplies the variable selected in its own credential declaration. See the +[configuration reference](../config.md) for context selection, path resolution, and the optional candidate check. The validator checks the selected committed paths; it does not scan for secrets in other files or past commits. For nested modules, the note comes from that module's committed @@ -132,15 +135,15 @@ separate credentials between build and delivery, use two invocations: ```sh releasekit build --output dist v1.2.3 -RELEASEKIT_GITEA_TOKEN="$GITEA_TOKEN" releasekit deliver --assets dist v1.2.3 +releasekit deliver --assets dist v1.2.3 ``` The build command does not need delivery credentials. The `--assets DIR` directory must contain the private `.releasekit-build.json` receipt created by `build`. ReleaseKit checks its schema, repository, commit, source selection, identity kind, version, module directory and path, full tag, normalized build -settings, and artifact declarations. Old receipts must be regenerated with the updated `build` -command. Delivery verifies the artifact bytes and sizes after read-only +settings, and artifact declarations. Old receipts must be regenerated with the +updated `build` command. Delivery verifies the artifact bytes and sizes after read-only preflight and before any hosted write; caller-owned files remain available for retries. See the [receipt format](../integrations/build-receipts.md) for its identity and compatibility rules. diff --git a/docs/release.md b/docs/release.md index 1107e13..d54af84 100644 --- a/docs/release.md +++ b/docs/release.md @@ -17,8 +17,8 @@ succeeded. CI and consumer installation are not completion checks. For local hosted-page delivery, save a Gitea personal access token in `.releasekit/gitea-token` with owner-only file permissions. The file contains -only the token. ReleaseKit's profile selects this file as a fallback to -`RELEASEKIT_GITEA_TOKEN`; `.releasekit/` is already ignored. Its optional +only the token. ReleaseKit's profile selects this file for local delivery and +`RELEASEKIT_GITEA_TOKEN` for CI; `.releasekit/` is already ignored. Its optional `validation.forbidden_files` selection checks that this path is absent from the committed candidate. Source publication requires no delivery token. The [configuration reference](config.md) owns credential selection and validator diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index a113b09..c7808a4 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -268,6 +268,13 @@ after the launcher has exited. Use isolated synthetic module caches. ## Stage 6: Select local and CI credentials explicitly +**Completed:** Local delivery reads its declared token file and CI delivery +reads its declared environment variable without cross-context fallback. Legacy +flat settings receive migration guidance, and maintained profiles and workflows +use the new declarations. Context selection, missing credentials, tagged CI +workflow fixtures, the offline `go test ./...` suite, and +`go run ./internal/apicheck` pass. + **Work:** replace flat delivery credential configuration and share CLI loading. 1. Adopt `delivery.credentials.local.token_file` and diff --git a/examples/multi-module/README.md b/examples/multi-module/README.md index b3b407e..f921fbb 100644 --- a/examples/multi-module/README.md +++ b/examples/multi-module/README.md @@ -94,7 +94,8 @@ path. It passes `ci-deliver --prepared`, the mapped profile, and the expected physical module to the tool. The `core-v2` profile demonstrates binary delivery; the other profiles are page-only. Before enabling the workflow, configure each selected profile's -`delivery` object with `"forge": "gitea"`, its `base_url`, owner, and repository, +`delivery` object with `"forge": "gitea"`, its `base_url`, owner, repository, +and `"credentials": {"ci": {"token_environment_variable": "RELEASEKIT_GITEA_TOKEN"}}`, then add the Woodpecker repository secret `releasekit_gitea_token`; the workflow exposes it as `RELEASEKIT_GITEA_TOKEN` only in the delivery step. diff --git a/examples/multi-module/woodpecker.yml b/examples/multi-module/woodpecker.yml index 44a1ef5..f9f1bb8 100644 --- a/examples/multi-module/woodpecker.yml +++ b/examples/multi-module/woodpecker.yml @@ -10,6 +10,7 @@ steps: - name: deliver image: golang:1.27.4-bookworm environment: + # Woodpecker stores releasekit_gitea_token and injects it under this job variable. RELEASEKIT_GITEA_TOKEN: from_secret: releasekit_gitea_token commands: diff --git a/examples/releasekit-binary.json b/examples/releasekit-binary.json index 6656ff5..cd1332f 100644 --- a/examples/releasekit-binary.json +++ b/examples/releasekit-binary.json @@ -4,13 +4,24 @@ "build": { "main_package": "./cmd/example", "binary_name": "example", - "targets": ["linux/amd64", "linux/arm64", "darwin/arm64"] + "targets": [ + "linux/amd64", + "linux/arm64", + "darwin/arm64" + ] }, "delivery": { "forge": "gitea", "base_url": "https://gitea.example", "owner": "example", "repository": "example", - "token_env": "RELEASEKIT_GITEA_TOKEN" + "credentials": { + "local": { + "token_file": ".releasekit/gitea-token" + }, + "ci": { + "token_environment_variable": "RELEASEKIT_GITEA_TOKEN" + } + } } } diff --git a/examples/releasekit.json b/examples/releasekit.json index 20ebaac..f721039 100644 --- a/examples/releasekit.json +++ b/examples/releasekit.json @@ -6,6 +6,13 @@ "base_url": "https://gitea.example", "owner": "example", "repository": "example", - "token_env": "RELEASEKIT_GITEA_TOKEN" + "credentials": { + "local": { + "token_file": ".releasekit/gitea-token" + }, + "ci": { + "token_environment_variable": "RELEASEKIT_GITEA_TOKEN" + } + } } } diff --git a/examples/woodpecker/releasekit-source-delivery.yml b/examples/woodpecker/releasekit-source-delivery.yml index e6be3e8..aa6ce41 100644 --- a/examples/woodpecker/releasekit-source-delivery.yml +++ b/examples/woodpecker/releasekit-source-delivery.yml @@ -6,6 +6,7 @@ steps: - name: deliver image: golang:1.27.4-bookworm environment: + # Woodpecker stores releasekit_gitea_token and injects it under this job variable. RELEASEKIT_GITEA_TOKEN: from_secret: releasekit_gitea_token commands: diff --git a/examples/woodpecker/tag-delivery.yml b/examples/woodpecker/tag-delivery.yml index 946e84b..df7379e 100644 --- a/examples/woodpecker/tag-delivery.yml +++ b/examples/woodpecker/tag-delivery.yml @@ -10,6 +10,7 @@ steps: - name: deliver image: ${GO_IMAGE} environment: + # Woodpecker stores releasekit_gitea_token and injects it under this job variable. RELEASEKIT_GITEA_TOKEN: from_secret: releasekit_gitea_token commands: diff --git a/releasekit.json b/releasekit.json index 2070c32..7d5ef8f 100644 --- a/releasekit.json +++ b/releasekit.json @@ -2,14 +2,22 @@ "product": "ReleaseKit", "remote": "origin", "validation": { - "forbidden_files": [".releasekit/gitea-token"] + "forbidden_files": [ + ".releasekit/gitea-token" + ] }, "delivery": { "forge": "gitea", "base_url": "https://forge.maximumdirect.net", "owner": "base-layer", "repository": "releasekit", - "token_env": "RELEASEKIT_GITEA_TOKEN", - "token_file": ".releasekit/gitea-token" + "credentials": { + "local": { + "token_file": ".releasekit/gitea-token" + }, + "ci": { + "token_environment_variable": "RELEASEKIT_GITEA_TOKEN" + } + } } }