diff --git a/app/cli/cmd/attestation.go b/app/cli/cmd/attestation.go index a80288b33..a11d6bad6 100644 --- a/app/cli/cmd/attestation.go +++ b/app/cli/cmd/attestation.go @@ -107,41 +107,60 @@ 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) - } + // 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 && attestationID == "" { + 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..d66c4516b 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,17 +139,28 @@ func TestAttestationRepositoryOrganizationCommands(t *testing.T) { func TestAttestationOrganizationPrecedence(t *testing.T) { for _, tc := range []struct { name string + command string flag string 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"}, {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"}, + // 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() @@ -157,7 +169,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)) @@ -165,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)) @@ -201,10 +214,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 +238,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 +288,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 @@ -346,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() @@ -355,6 +409,7 @@ func newAttestationOrganizationTestCommand(t *testing.T, command, savedOrganizat apiToken = previousAPIToken attestationLocalStatePath = previousLocalStatePath useAttestationRemoteState = previousRemoteState + attestationID = previousAttestationID logger = previousLogger }) @@ -378,6 +433,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..ddbf85fde 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 @@ -41,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) @@ -56,6 +58,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 +73,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, [#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). ## Non-Confirmed