From 6bed9e46931be4fa701799604b11ed6d3f98247c Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 23:01:37 +0100 Subject: [PATCH 1/3] fix(cli): use the run's organization after attestation init After `attestation init --org org-a`, the commands add, push, status, and reset sent the organization of the repository `.chainloop.yml` before the organization stored in the local attestation state. When the file named another organization, they failed with "workflow run not found". The local attestation state now comes before the repository config: --org > CHAINLOOP_ORGANIZATION > local attestation state > .chainloop.yml > saved CLI default. init keeps reading the repository config, and remote state does not change. When the file names a different organization than the local state, the CLI logs which one it uses. The API token check applies to the repository organization only when that organization is used. This is within R-003 and R-004 of spec issue-3063-attestation-repo-config. Records the decision as ATT-006, which partly replaces ATT-001 and ATT-004. Closes #3861 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: f8788f1a-57ad-450c-a7cf-229ee5f1e2d9 --- app/cli/cmd/attestation.go | 59 +++++++++++++-------- app/cli/cmd/attestation_test.go | 76 +++++++++++++++++++++++---- docs/decisions/attestation-process.md | 12 ++++- 3 files changed, 115 insertions(+), 32 deletions(-) diff --git a/app/cli/cmd/attestation.go b/app/cli/cmd/attestation.go index a80288b33..f54f8e567 100644 --- a/app/cli/cmd/attestation.go +++ b/app/cli/cmd/attestation.go @@ -107,41 +107,58 @@ func organizationExplicitlySelected(cmd *cobra.Command) bool { return (orgFlag != nil && orgFlag.Changed) || os.Getenv(CalculateEnvVarName(confOptions.organization.viperKey)) != "" } +// resolveAttestationOrganization selects the organization of an attestation +// command when --org and CHAINLOOP_ORGANIZATION are not set. After init, the +// organization in the local attestation state wins, because it records where +// the run lives. Then the organization in the repository config applies, and +// last the saved CLI default. func resolveAttestationOrganization(cmd *cobra.Command) error { if organizationExplicitlySelected(cmd) { return nil } - if repositoryOrganizationCommands[cmd.Name()] { - cfg, path, err := repositoryconfig.LoadChainloopYML(".") - if err == nil && cfg.Organization != "" { - authToken, _, err := loadAuthToken(cmd) - if err != nil { - return err - } - if tokenOrg := internaltoken.MismatchedOrganization(authToken, cfg.Organization); tokenOrg != "" { - return fmt.Errorf("credentials belong to organization %q but %q is configured in %s: use an API token for %q or remove organization from %s", tokenOrg, cfg.Organization, path, cfg.Organization, path) - } + var localOrg string + if cmd.Name() != "init" && !useAttestationRemoteState { + localOrg = orgFromLocalState(attestationLocalStatePath) + } - setAttestationOrganization(cmd, cfg.Organization, path) - if saved := viper.GetString(confOptions.organization.viperKey); saved != cfg.Organization { - logger.Info().Str("organization", cfg.Organization).Str("file", path).Msg("using organization from repository config") - } - return nil - } + var repoOrg, path string + if repositoryOrganizationCommands[cmd.Name()] { + cfg, cfgPath, err := repositoryconfig.LoadChainloopYML(".") + switch { + case err == nil: + repoOrg, path = cfg.Organization, cfgPath // A missing .chainloop.yml is the common case, not a problem. - if err != nil && !errors.Is(err, repositoryconfig.ErrChainloopYMLNotFound) { + case !errors.Is(err, repositoryconfig.ErrChainloopYMLNotFound): logger.Warn().Err(err).Msg("failed to load repository organization") } } - // Preserve the existing local-state fallback for commands other than init. - if cmd.Name() != "init" && !useAttestationRemoteState { - if org := orgFromLocalState(attestationLocalStatePath); org != "" { - setAttestationOrganization(cmd, org, "") + if localOrg != "" { + if repoOrg != "" && repoOrg != localOrg { + logger.Info().Str("organization", localOrg).Str("repositoryOrganization", repoOrg).Str("file", path). + Msg("using organization of the attestation in progress instead of the repository config") } + setAttestationOrganization(cmd, localOrg, "") + return nil + } + + if repoOrg == "" { + return nil } + authToken, _, err := loadAuthToken(cmd) + if err != nil { + return err + } + if tokenOrg := internaltoken.MismatchedOrganization(authToken, repoOrg); tokenOrg != "" { + return fmt.Errorf("credentials belong to organization %q but %q is configured in %s: use an API token for %q or remove organization from %s", tokenOrg, repoOrg, path, repoOrg, path) + } + + setAttestationOrganization(cmd, repoOrg, path) + if saved := viper.GetString(confOptions.organization.viperKey); saved != repoOrg { + logger.Info().Str("organization", repoOrg).Str("file", path).Msg("using organization from repository config") + } return nil } diff --git a/app/cli/cmd/attestation_test.go b/app/cli/cmd/attestation_test.go index b6f8262dd..ed80e34cb 100644 --- a/app/cli/cmd/attestation_test.go +++ b/app/cli/cmd/attestation_test.go @@ -17,6 +17,7 @@ package cmd import ( "bytes" + "cmp" "os" "path/filepath" "strings" @@ -138,6 +139,7 @@ func TestAttestationRepositoryOrganizationCommands(t *testing.T) { func TestAttestationOrganizationPrecedence(t *testing.T) { for _, tc := range []struct { name string + command string flag string environment string repository string @@ -146,9 +148,14 @@ func TestAttestationOrganizationPrecedence(t *testing.T) { }{ {name: "flag", flag: "flag-org", environment: "environment-org", repository: "repository-org", local: "local-org", want: "flag-org"}, {name: "environment", environment: "environment-org", repository: "repository-org", local: "local-org", want: "environment-org"}, - {name: "repository", repository: "repository-org", local: "local-org", want: "repository-org"}, + // The local state records the organization of the run that init created, + // so it wins over the repository config (#3861). + {name: "local state over repository", repository: "repository-org", local: "local-org", want: "local-org"}, + {name: "repository", repository: "repository-org", want: "repository-org"}, {name: "local state", local: "local-org", want: "local-org"}, {name: "saved default", want: "saved-org"}, + {name: "init flag over repository", command: "init", flag: "flag-org", repository: "repository-org", want: "flag-org"}, + {name: "init repository ignores local state", command: "init", repository: "repository-org", local: "local-org", want: "repository-org"}, } { t.Run(tc.name, func(t *testing.T) { dir := t.TempDir() @@ -157,7 +164,7 @@ func TestAttestationOrganizationPrecedence(t *testing.T) { } t.Chdir(dir) - root, cmd := newAttestationOrganizationTestCommand(t, "status", "saved-org") + root, cmd := newAttestationOrganizationTestCommand(t, cmp.Or(tc.command, "status"), "saved-org") t.Setenv(CalculateEnvVarName(confOptions.organization.viperKey), tc.environment) if tc.flag != "" { require.NoError(t, root.PersistentFlags().Set(confOptions.organization.flagName, tc.flag)) @@ -201,10 +208,7 @@ func TestAttestationRepositoryOrganizationTokenMismatchStopsBeforeRootPreRun(t * return nil } - claims := jwt.MapClaims{"aud": "api-token-auth.chainloop", "jti": "token-id", "org_name": "token-org"} - rawToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte("secret")) - require.NoError(t, err) - apiToken = rawToken + apiToken = testAPIToken(t, jwt.MapClaims{"org_name": "token-org"}) err = cmd.Parent().PersistentPreRunE(cmd, nil) require.Error(t, err) @@ -228,10 +232,7 @@ func TestAttestationRepositoryOrganizationAllowsInstanceAdminToken(t *testing.T) return nil } - claims := jwt.MapClaims{"aud": "api-token-auth.chainloop", "jti": "instance-token-id", "scope": "INSTANCE_ADMIN"} - rawToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte("secret")) - require.NoError(t, err) - apiToken = rawToken + apiToken = testAPIToken(t, jwt.MapClaims{"scope": "INSTANCE_ADMIN"}) require.NoError(t, cmd.Parent().PersistentPreRunE(cmd, nil)) assert.True(t, rootPreRunCalled) @@ -281,6 +282,51 @@ func TestAttestationRepositoryOrganizationNotice(t *testing.T) { assert.Equal(t, "saved-org", viper.GetString(confOptions.organization.viperKey)) } +func TestAttestationLocalStateOrganizationOverRepository(t *testing.T) { + for _, tc := range []struct { + name string + local string + runToken bool + }{ + {name: "different organization logs notice", local: "local-org"}, + {name: "same organization no notice", local: "repository-org"}, + // The token check applies to the organization in use, not to the + // organization in the file that the local state overrides. + {name: "token of the run organization", local: "local-org", runToken: true}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + configPath := filepath.Join(dir, ".chainloop.yml") + require.NoError(t, os.WriteFile(configPath, []byte("organization: repository-org\n"), 0o600)) + configPath, err := filepath.EvalSymlinks(configPath) + require.NoError(t, err) + t.Chdir(dir) + + _, cmd := newAttestationOrganizationTestCommand(t, "add", "saved-org") + attestationLocalStatePath = writeAttestationOrganizationState(t, tc.local) + if tc.runToken { + apiToken = testAPIToken(t, jwt.MapClaims{"org_name": tc.local}) + } + + var output bytes.Buffer + logger = zerolog.New(&output) + require.NoError(t, resolveAttestationOrganization(cmd)) + + assert.Equal(t, tc.local, effectiveOrganization(cmd)) + assert.NotContains(t, output.String(), "using organization from repository config") + if tc.local != "repository-org" { + assert.Equal(t, 1, strings.Count(output.String(), "using organization of the attestation in progress")) + assert.Contains(t, output.String(), tc.local) + assert.Contains(t, output.String(), "repository-org") + assert.Contains(t, output.String(), configPath) + } else { + assert.Empty(t, output.String()) + } + assert.Equal(t, "saved-org", viper.GetString(confOptions.organization.viperKey)) + }) + } +} + func TestAttestationRepositoryConfigLookupLogging(t *testing.T) { for _, tc := range []struct { name string @@ -378,6 +424,16 @@ func newAttestationOrganizationTestCommand(t *testing.T, command, savedOrganizat return nil, nil } +// testAPIToken signs an API token with the given claims added to the base ones. +func testAPIToken(t *testing.T, claims jwt.MapClaims) string { + t.Helper() + claims["aud"] = "api-token-auth.chainloop" + claims["jti"] = "token-id" + raw, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte("secret")) + require.NoError(t, err) + return raw +} + func writeAttestationOrganizationState(t *testing.T, organization string) string { t.Helper() state := &crafter.VersionedCraftingState{CraftingState: &v1.CraftingState{Attestation: &v1.Attestation{Workflow: &v1.WorkflowMetadata{Organization: organization}}}} diff --git a/docs/decisions/attestation-process.md b/docs/decisions/attestation-process.md index dbde45738..d6323e3b0 100644 --- a/docs/decisions/attestation-process.md +++ b/docs/decisions/attestation-process.md @@ -22,7 +22,7 @@ Structure. The index (README.md) has the parts Areas (the area map), Relationshi > Written by `eng-adr`. To change a decision, write a spec or run `eng-adr new`. Do not edit this page by hand. -**Purpose:** The attestation lifecycle of the CLI (`init`, `add`, `status`, `push`, `reset`, `verify`), and how it selects its organization and project. **Owner:** migmartri. **Does not own:** AI coding session evidence (Chainloop Trace), and login and tokens (Authentication). **Specs:** [issue-3063-attestation-repo-config](../specs/issue-3063-attestation-repo-config.md). **Last refresh:** 2026-11-23, commit 81dd68bb. +**Purpose:** The attestation lifecycle of the CLI (`init`, `add`, `status`, `push`, `reset`, `verify`), and how it selects its organization and project. **Owner:** migmartri. **Does not own:** AI coding session evidence (Chainloop Trace), and login and tokens (Authentication). **Specs:** [issue-3063-attestation-repo-config](../specs/issue-3063-attestation-repo-config.md). **Last refresh:** 2026-11-30, commit 9887921b. ## Language @@ -33,6 +33,7 @@ Structure. The index (README.md) has the parts Areas (the area map), Relationshi ### ATT-001: Organization order is flag, environment variable, repository config, saved default The `--org` flag and its environment variable win. For `init`, `add`, `push`, `status`, and `reset`, the repository config applies only when neither is set, and it comes before the saved default. +- Partly replaced by ATT-006: the place of the local attestation state, which comes before the repository config. - Why: the file pins the organization for the repository. - Rejected: the saved default before the file (most users have a saved default, so the file would almost never apply). - Deciders: migmartri, javirln @@ -56,6 +57,7 @@ Attestation commands and Trace read the repository config through one package. ### ATT-004: The repository config organization acts as `--org`, with a check for API tokens The organization from the file has the same effect as `--org` for the run. It is not saved as the default. When an API token belongs to a different organization, the command stops with an error that names both. +- Partly replaced by ATT-006: after `init`, the file does not act as `--org`. The organization of the local attestation state comes first. - Why: one rule for users: the file is a `--org` that the repository keeps. - Rejected: an exact copy of `--org` (with an API token, it ignores a different organization with no message). A warning only (CI logs often hide it). - Deciders: migmartri, javirln @@ -70,6 +72,14 @@ When the content of an `ARTIFACT` material is not JSON, for example a ZIP file, - Source: recorded directly, 2026-11-23, [#3843](https://github.com/chainloop-dev/chainloop/pull/3843) - Code: verified: `GetEvaluableContent` in `pkg/attestation/crafter/api/attestation/v1/crafting_state.go`. The CLI decodes the first JSON value, as before, so a file of JSON lines keeps its first value. Only a failed decode gives the empty object. +### ATT-006: After init, the organization of the run comes before the repository config +For `add`, `push`, `status`, and `reset` with local state, the organization in the local attestation state comes before the repository config. The order is `--org`, `CHAINLOOP_ORGANIZATION`, the local attestation state, the repository config, and the saved default. `init` reads the repository config and not the local state. With remote state (`--attestation-id`), the commands do not read the local state. When the repository config gives a different organization than the local state, the CLI logs the organization that it uses. The API token check applies only when the CLI uses the organization of the repository config. +- Why: the local state records the organization where `init` made the run. A later command that uses a different organization fails with "workflow run not found". R-003 of issue-3063-attestation-repo-config puts the file before the saved default only, not before the organization of a run. +- Rejected: the repository config before the local state (#3518). After `init --org`, the next commands then use the organization of the file, and they do not find the run. +- Deciders: migmartri +- Source: recorded directly, 2026-11-30, [#3861](https://github.com/chainloop-dev/chainloop/issues/3861). It keeps [#2823](https://github.com/chainloop-dev/chainloop/pull/2823) and corrects [#3518](https://github.com/chainloop-dev/chainloop/pull/3518), within R-003 and R-004 of [issue-3063-attestation-repo-config](../specs/issue-3063-attestation-repo-config.md). +- Code: verified: `resolveAttestationOrganization` in `app/cli/cmd/attestation.go`. The tests `TestAttestationOrganizationPrecedence` and `TestAttestationLocalStateOrganizationOverRepository` in `app/cli/cmd/attestation_test.go` show the order. + Not shown: 6 smaller decisions of [issue-3063-attestation-repo-config](../specs/issue-3063-attestation-repo-config.md). ## Non-Confirmed From 6b08a81fabf69878a565df5608dd43a2891181da Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 23:02:24 +0100 Subject: [PATCH 2/3] docs(decisions): link ATT-006 to its PR Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: f8788f1a-57ad-450c-a7cf-229ee5f1e2d9 --- docs/decisions/attestation-process.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions/attestation-process.md b/docs/decisions/attestation-process.md index d6323e3b0..f9cc16e1c 100644 --- a/docs/decisions/attestation-process.md +++ b/docs/decisions/attestation-process.md @@ -77,7 +77,7 @@ For `add`, `push`, `status`, and `reset` with local state, the organization in t - Why: the local state records the organization where `init` made the run. A later command that uses a different organization fails with "workflow run not found". R-003 of issue-3063-attestation-repo-config puts the file before the saved default only, not before the organization of a run. - Rejected: the repository config before the local state (#3518). After `init --org`, the next commands then use the organization of the file, and they do not find the run. - Deciders: migmartri -- Source: recorded directly, 2026-11-30, [#3861](https://github.com/chainloop-dev/chainloop/issues/3861). It keeps [#2823](https://github.com/chainloop-dev/chainloop/pull/2823) and corrects [#3518](https://github.com/chainloop-dev/chainloop/pull/3518), within R-003 and R-004 of [issue-3063-attestation-repo-config](../specs/issue-3063-attestation-repo-config.md). +- Source: recorded directly, 2026-11-30, [#3862](https://github.com/chainloop-dev/chainloop/pull/3862), for [#3861](https://github.com/chainloop-dev/chainloop/issues/3861). It keeps [#2823](https://github.com/chainloop-dev/chainloop/pull/2823) and corrects [#3518](https://github.com/chainloop-dev/chainloop/pull/3518), within R-003 and R-004 of [issue-3063-attestation-repo-config](../specs/issue-3063-attestation-repo-config.md). - Code: verified: `resolveAttestationOrganization` in `app/cli/cmd/attestation.go`. The tests `TestAttestationOrganizationPrecedence` and `TestAttestationLocalStateOrganizationOverRepository` in `app/cli/cmd/attestation_test.go` show the order. Not shown: 6 smaller decisions of [issue-3063-attestation-repo-config](../specs/issue-3063-attestation-repo-config.md). From 126fcbfa95254e83ab8096b0a45f96b130082e15 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 23:10:08 +0100 Subject: [PATCH 3/3] fix(cli): ignore the local attestation state with --attestation-id With remote state, a local state file is a leftover of another run, so it must not select the organization. Also mark ATT-002 as partly replaced by ATT-006. Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: f8788f1a-57ad-450c-a7cf-229ee5f1e2d9 --- app/cli/cmd/attestation.go | 4 +++- app/cli/cmd/attestation_test.go | 9 +++++++++ docs/decisions/attestation-process.md | 1 + 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/app/cli/cmd/attestation.go b/app/cli/cmd/attestation.go index f54f8e567..a11d6bad6 100644 --- a/app/cli/cmd/attestation.go +++ b/app/cli/cmd/attestation.go @@ -117,8 +117,10 @@ func resolveAttestationOrganization(cmd *cobra.Command) error { return nil } + // With remote state (--remote-state on init, --attestation-id on the other + // commands), a local state file is a leftover of another run. var localOrg string - if cmd.Name() != "init" && !useAttestationRemoteState { + if cmd.Name() != "init" && !useAttestationRemoteState && attestationID == "" { localOrg = orgFromLocalState(attestationLocalStatePath) } diff --git a/app/cli/cmd/attestation_test.go b/app/cli/cmd/attestation_test.go index ed80e34cb..d66c4516b 100644 --- a/app/cli/cmd/attestation_test.go +++ b/app/cli/cmd/attestation_test.go @@ -144,6 +144,7 @@ func TestAttestationOrganizationPrecedence(t *testing.T) { environment string repository string local string + remoteID string want string }{ {name: "flag", flag: "flag-org", environment: "environment-org", repository: "repository-org", local: "local-org", want: "flag-org"}, @@ -156,6 +157,10 @@ func TestAttestationOrganizationPrecedence(t *testing.T) { {name: "saved default", want: "saved-org"}, {name: "init flag over repository", command: "init", flag: "flag-org", repository: "repository-org", want: "flag-org"}, {name: "init repository ignores local state", command: "init", repository: "repository-org", local: "local-org", want: "repository-org"}, + // With --attestation-id the state is remote, so a leftover local state + // file must not select the organization. + {name: "remote state repository ignores local state", remoteID: "attestation-id", repository: "repository-org", local: "local-org", want: "repository-org"}, + {name: "remote state saved default ignores local state", remoteID: "attestation-id", local: "local-org", want: "saved-org"}, } { t.Run(tc.name, func(t *testing.T) { dir := t.TempDir() @@ -172,6 +177,7 @@ func TestAttestationOrganizationPrecedence(t *testing.T) { if tc.local != "" { attestationLocalStatePath = writeAttestationOrganizationState(t, tc.local) } + attestationID = tc.remoteID require.NoError(t, resolveAttestationOrganization(cmd)) assert.Equal(t, tc.want, effectiveOrganization(cmd)) @@ -392,8 +398,10 @@ func newAttestationOrganizationTestCommand(t *testing.T, command, savedOrganizat previousAPIToken := apiToken previousLocalStatePath := attestationLocalStatePath previousRemoteState := useAttestationRemoteState + previousAttestationID := attestationID previousLogger := logger apiToken = "" + attestationID = "" missingLocalStatePath := filepath.Join(t.TempDir(), "missing-state.json") useAttestationRemoteState = false logger = zerolog.Nop() @@ -401,6 +409,7 @@ func newAttestationOrganizationTestCommand(t *testing.T, command, savedOrganizat apiToken = previousAPIToken attestationLocalStatePath = previousLocalStatePath useAttestationRemoteState = previousRemoteState + attestationID = previousAttestationID logger = previousLogger }) diff --git a/docs/decisions/attestation-process.md b/docs/decisions/attestation-process.md index f9cc16e1c..ddbf85fde 100644 --- a/docs/decisions/attestation-process.md +++ b/docs/decisions/attestation-process.md @@ -42,6 +42,7 @@ The `--org` flag and its environment variable win. For `init`, `add`, `push`, `s ### ATT-002: init, add, push, status, and reset read the organization from the file The attestation commands that contact the control plane read the organization from the repository config. They are `init`, `add`, `push`, `status`, and `reset`. +- Partly replaced by ATT-006: after `init`, `add`, `push`, `status`, and `reset` use the organization of the local attestation state before the organization of the file. - Why: with remote state, a command must connect to the correct organization before it can load the state. - Deciders: migmartri, javirln - Source: [issue-3063-attestation-repo-config D-004](../specs/issue-3063-attestation-repo-config.md)