diff --git a/docs/DEVGUIDE.md b/docs/DEVGUIDE.md index d535387..c0fed97 100644 --- a/docs/DEVGUIDE.md +++ b/docs/DEVGUIDE.md @@ -67,7 +67,7 @@ Exceptions live in `rootLevelExceptions` in `internal/cmd/conventions_test.go`. Two distinct concerns: -**Messaging** (Info / Success / Warning / Error). For both humans and AI agents. Commands call `dry/tui.Info / Success / Warning / Error` directly. dry/tui auto-detects its mode (rich, plain, agent) from TTY state, env vars (`CLAUDE_CODE`, `ANTHROPIC_AGENT`, `CI`, `TERM=dumb`), and `SAFEDEP_OUTPUT`. Human users get colour and unicode; agents get terse, token-optimised text. The `--output` flag does **not** influence messaging. +**Messaging** (Info / Success / Warning / Error). For both humans and AI agents. Commands call `dry/tui.Info / Success / Warning / Error` directly. dry/tui auto-detects its mode (rich, plain, agent) from TTY state, env vars (`CLAUDE_CODE`, `ANTHROPIC_AGENT`, `CLAUDECODE`, `AI_AGENT`, `CI`, `TERM=dumb`), and `SAFEDEP_OUTPUT`. Human users get colour and unicode; agents get terse, token-optimised text. The `--output` flag does **not** influence messaging. **Renderable** (data presentation). Data commands implement `tui.Renderable`: diff --git a/docs/cmd/auth-login.md b/docs/cmd/auth-login.md index fad8844..2573393 100644 --- a/docs/cmd/auth-login.md +++ b/docs/cmd/auth-login.md @@ -2,7 +2,32 @@ Authenticate with SafeDep Cloud and store credentials in the keychain under the active profile. -By default, runs the OAuth2 device-code flow in the browser, picks an accessible tenant, creates a fresh API key, and stores both the OAuth tokens and the API key in the keychain. Pass `--api-key` to skip the OAuth flow and store an API key you already have. +By default, runs the OAuth2 device-code flow in the browser, picks an accessible tenant, makes sure the profile holds a valid API key, and stores the OAuth tokens and the API key in the keychain. Pass `--api-key` to skip the OAuth flow and store an API key you already have. + +## API key + +The device flow keeps the API key that the keychain holds for the profile only when all of these hold: + +1. The key belongs to the tenant that you picked. +2. Its recorded expiry is more than 14 days away. +3. SafeDep Cloud accepts it. + +Otherwise login creates a new key and prints why, for example `Created a new API key: the stored API key expired on 2026-11-20.` The key is saved with its id and expiry, so the next login and `safedep auth status` can tell when it expires. + +A key with no recorded expiry, such as a key saved with `--api-key` or by an earlier CLI, is replaced, because `safedep auth status` cannot warn before it expires. + +Login does not revoke the key that it replaces. That key stops working at its own expiry, and any tool that still holds a copy of it, such as an MCP client set up with `safedep protect mcp install`, keeps working until then. SafeDep Cloud still sends the expiry email for it. Delete it in app.safedep.io to revoke it at once. + +Login keeps the stored key and prints a warning when SafeDep Cloud cannot be reached. + +When login cannot create a new key, for example for a user who cannot create keys: + +- If SafeDep Cloud still accepts the stored key, login keeps it and prints a warning. +- If the stored key belongs to another tenant, login fails and stores nothing. The OAuth tokens of one tenant next to the key of another would send pmg, vet and data plane commands to the other tenant. +- Otherwise login stores the OAuth tokens, prints a warning and exits with success. `safedep auth status` then shows the state of the old key. pmg and vet need a key: ask a tenant admin for one and save it with `safedep auth login --api-key`. +- With `--rotate-api-key`, login fails and stores nothing. + +pmg and vet read the API key from the keychain. Login checks the keychain key, not `SAFEDEP_API_KEY`. ## Synopsis @@ -19,8 +44,8 @@ safedep auth login --api-key [--api-key-value | --from-stdin] [--tenant ` | Supply the API key inline. Only with `--api-key`; prefer `--from-stdin` or `SAFEDEP_API_KEY`. | | `--from-stdin` | Read API key from stdin. Only with `--api-key`. | | `--tenant ` | Tenant domain. Used as fallback when none is stored for the profile. | -| `--api-key-expiry-days ` | Expiry for API keys created during device login (default 90). | -| `--rotate-api-key` | Force creation of a new API key during device login. By default, an existing API key for the chosen tenant is preserved. | +| `--api-key-expiry-days ` | Expiry for API keys created during device login (default 90). Must be more than 14, because login replaces a key that expires within 14 days. With `--rotate-api-key`, any positive value is accepted. | +| `--rotate-api-key` | Create a new API key during device login even when the stored key is valid. | | `--no-api-key` | Skip API key creation during device login. OAuth tokens are still stored. | Inherits root flags `--output`, `--profile`, and `--insecure-keychain-fallback`. @@ -35,7 +60,7 @@ For `--api-key`: ## Outputs -- Device flow: opens the verification URL in your browser (rich mode) and prints the user code. After the IdP confirms the grant, prints a success line with tenant, profile, and API-key expiry. +- Device flow: opens the verification URL in your browser (rich mode) and prints the user code. After the IdP confirms the grant, prints a success line with tenant, profile, and the expiry of the API key that it created or kept. - API-key flow: verifies the key against the data plane before storing. Prints success on completion. ## Exit codes diff --git a/docs/cmd/auth-status.md b/docs/cmd/auth-status.md index c7ea786..ac0f0e8 100644 --- a/docs/cmd/auth-status.md +++ b/docs/cmd/auth-status.md @@ -10,13 +10,25 @@ safedep auth status [--output table|plain|json] [--profile ] ## Output -Reports profile name, tenant, presence of an API key, presence of an OAuth token, and the OAuth access-token expiry decoded from the JWT. +Reports profile name, tenant, the API key and its recorded expiry, presence of an OAuth token, and the OAuth access-token expiry decoded from the JWT. Status reads the keychain only. It does not call SafeDep Cloud. + +The API key has one of these states: + +| State | Table badge | Meaning | +|---|---|---| +| `valid` | `configured` | The recorded expiry is more than 14 days away. | +| `expiring` | `expires soon` | The key expires within 14 days. `safedep auth login` replaces it. | +| `expired` | `expired` | The recorded expiry has passed. pmg and vet fail with this key. | +| `expiry_unknown` | `expiry unknown` | No expiry is recorded, for example for a key saved by `--api-key` or by an earlier CLI. Status cannot tell whether it has expired. `safedep auth login` replaces it with a key whose expiry is recorded. Login keeps it, with a warning, when it cannot create a new key and SafeDep Cloud still accepts this one. | +| `missing` | `not configured` | The profile holds no API key. | + +The overall status is `authenticated` only when the OAuth token is valid and the API key has not expired. | Mode | Format | |---|---| | `table` | Tabular block with badges for each credential. | -| `plain` | `key: value` lines. | -| `json` | `{profile, tenant, api_key_present, oauth_token_present, oauth_expires_at}`. | +| `plain` | `key: value` lines, with `API key state` and `Key expires` lines for an API key. | +| `json` | `{profile, tenant, api_key_present, api_key_state, api_key_expires_at, oauth_token_present, oauth_expires_at}`. | ## Exit codes diff --git a/docs/cmd/package-scan-run.md b/docs/cmd/package-scan-run.md index cb5b25f..56a1b58 100644 --- a/docs/cmd/package-scan-run.md +++ b/docs/cmd/package-scan-run.md @@ -29,9 +29,10 @@ creating duplicates. Pass `--rescan` to force a fresh scan. A branch or tag of a GitHub repository is a mutable reference. The command resolves it to the commit SHA it points to before it submits the scan, so the scan stays bound to the code that was reviewed after the branch or tag moves. -This applies to every input form: a `pkg:github/owner/repo@ref` PURL, a GitHub -URL, and the explicit triple with a `github_actions` or `github_repository` -ecosystem. A version that is already a full commit SHA passes through without +This applies to every input form: a `pkg:github/owner/repo@ref` PURL for a +repository, a `pkg:githubactions/owner/repo@ref` PURL for a GitHub Action, a +GitHub URL, and the explicit triple with a `github_actions` or +`github_repository` ecosystem. A version that is already a full commit SHA passes through without a lookup. A GitHub URL without a `/tree/` suffix resolves to the head of the default branch. diff --git a/docs/cmd/policy-decision-list.md b/docs/cmd/policy-decision-list.md index 7a5ff54..c3dff92 100644 --- a/docs/cmd/policy-decision-list.md +++ b/docs/cmd/policy-decision-list.md @@ -53,6 +53,10 @@ form that pmg and vet store: | Go | `pkg:golang/github.com/BurntSushi/toml` | `github.com/BurntSushi/toml` | | Composer | `pkg:composer/laravel/framework` | `laravel/framework` | | PyPI | `pkg:pypi/Requests` | `Requests` | +| GitHub Actions | `pkg:githubactions/actions/checkout` | `actions/checkout` | +| GitHub repository | `pkg:github/safedep/vet` | `safedep/vet` | + +`pkg:github` names a GitHub repository. Use `pkg:githubactions` for a GitHub Action. ## Columns diff --git a/go.mod b/go.mod index 476625e..bfe4494 100644 --- a/go.mod +++ b/go.mod @@ -13,7 +13,7 @@ require ( github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 github.com/oklog/ulid/v2 v2.1.2 - github.com/safedep/dry v0.0.0-20260902191040-800bc36ff686 + github.com/safedep/dry v0.0.0-20261123141204-0458858d29a8 github.com/spf13/cobra v1.10.2 github.com/spf13/viper v1.21.0 github.com/stretchr/testify v1.11.1 diff --git a/go.sum b/go.sum index 9ab5444..c4bee5e 100644 --- a/go.sum +++ b/go.sum @@ -216,8 +216,8 @@ github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY= github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/safedep/dry v0.0.0-20260902191040-800bc36ff686 h1:uODPiRdQfdI5rvaak/X1pRbHURBKrWP7CUjVuHViIkQ= -github.com/safedep/dry v0.0.0-20260902191040-800bc36ff686/go.mod h1:W/OgEQaB88bPxIKUHKZ2S9lYMtO7lsFlo/j1yNv8HDg= +github.com/safedep/dry v0.0.0-20261123141204-0458858d29a8 h1:jESd4h8s+v8PuY4RxbloLHX3RHynVbNUI/beWnJWt/M= +github.com/safedep/dry v0.0.0-20261123141204-0458858d29a8/go.mod h1:DHtiOuwrtW3gzmMEMfX74Cs/MjclA2eAqdCON5uoKA0= github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4= github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= diff --git a/internal/app/app.go b/internal/app/app.go index 3f12b82..c1b3b35 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -123,6 +123,14 @@ func (a *App) CredentialStore() (cloud.CredentialStore, error) { return store, nil } +// StoredAPIKey returns the API key credentials that the keychain holds for +// the active profile, or nil when it holds none. It ignores SAFEDEP_API_KEY: +// pmg and vet read the key from the keychain, so login must decide on that +// key even when the environment holds another one. +func (a *App) StoredAPIKey() (*cloud.Credentials, error) { + return cliauth.StoredAPIKey(a.KeychainOptions()) +} + // APIKeyResolver returns the API-key credential resolver for the active // profile. Initialised lazily. Env vars (SAFEDEP_API_KEY + // SAFEDEP_TENANT_ID) win over the keychain, matching the convention diff --git a/internal/auth/apikey_renew.go b/internal/auth/apikey_renew.go new file mode 100644 index 0000000..79f2eb6 --- /dev/null +++ b/internal/auth/apikey_renew.go @@ -0,0 +1,165 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/safedep/dry/cloud" + "github.com/safedep/dry/log" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// APIKeyRenewWindow is how long before its expiry login replaces an API key. +// A key that expires inside the window would stop pmg and vet before the user +// signs in again. +const APIKeyRenewWindow = 14 * 24 * time.Hour + +// APIKeyState is what the keychain says about the stored API key. +type APIKeyState int + +const ( + APIKeyMissing APIKeyState = iota + APIKeyValid + APIKeyExpiring + APIKeyExpired + // APIKeyExpiryUnknown is a key saved with no expiry: a pasted key, or a + // key from a CLI that did not record it. Only SafeDep Cloud can tell + // whether it is valid. + APIKeyExpiryUnknown +) + +// APIKeyStateAt returns the state of a stored key at now. +func APIKeyStateAt(present bool, expiresAt time.Time, now time.Time) APIKeyState { + switch { + case !present: + return APIKeyMissing + case expiresAt.IsZero(): + return APIKeyExpiryUnknown + case !expiresAt.After(now): + return APIKeyExpired + case expiresAt.Before(now.Add(APIKeyRenewWindow)): + return APIKeyExpiring + default: + return APIKeyValid + } +} + +// APIKeyVerifier checks a key against SafeDep Cloud. VerifyAPIKey is the +// production verifier. Tests pass a fake. +type APIKeyVerifier func(ctx context.Context, in APIKeyInput) error + +// APIKeyDecision is whether login keeps the stored API key, and why not. +type APIKeyDecision struct { + Keep bool + + // Reason says why login replaces the key. Empty when Keep is true. + Reason string + + // ExpiresAt is the expiry of the key that login keeps. + ExpiresAt time.Time + + // Warning reports a check that could not finish. Login keeps the key, + // because a network failure says nothing about the key. + Warning string + + // OtherTenant means that the stored key belongs to another tenant. When + // login cannot create a key, it must then fail: the OAuth tokens of the + // picked tenant next to the key of another tenant would send data plane + // calls to the other tenant. + OtherTenant bool + + // Fallback means that the stored key still works for the tenant, so + // login keeps it when it cannot create a new key. ExpiresAt is zero when + // the expiry of the key is not recorded. + Fallback bool +} + +// DecideStoredAPIKey decides whether login keeps the API key that the +// keychain holds for the profile. stored is nil when the keychain holds no +// key. The key stays only when it belongs to tenant, its recorded expiry is +// more than APIKeyRenewWindow away, and SafeDep Cloud accepts it. +// +// A key with no recorded expiry is replaced: every key that a CLI saved +// before it recorded the expiry is one, and status cannot warn before such a +// key expires. Like a key inside the window, it is the fallback when login +// cannot create a new key. +func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant string, now time.Time, + verify APIKeyVerifier, +) APIKeyDecision { + if stored == nil { + return APIKeyDecision{Reason: "no API key is stored"} + } + + storedTenant, err := stored.GetTenantDomain() + if err != nil || storedTenant != tenant { + return APIKeyDecision{Reason: fmt.Sprintf("the stored API key belongs to tenant %q", storedTenant), + OtherTenant: true} + } + + expiresAt, _ := stored.APIKeyExpiresAt() + state := APIKeyStateAt(true, expiresAt, now) + if state == APIKeyExpired { + return APIKeyDecision{Reason: "the stored API key expired on " + formatDay(expiresAt)} + } + + key, err := stored.GetAPIKey() + if err != nil { + return APIKeyDecision{Reason: "the stored API key cannot be read"} + } + + // A key that login replaces is checked too: login falls back to it when + // it cannot create a new key, and a revoked key must not be kept. + warning := "" + if err := verify(ctx, APIKeyInput{APIKey: key, Tenant: tenant}); err != nil { + // The gateway answers Unauthenticated for an expired key and + // PermissionDenied for a key that it does not know, such as a + // revoked one. Both mean that a new key is needed. + if code := status.Code(err); code == codes.Unauthenticated || code == codes.PermissionDenied { + return APIKeyDecision{Reason: "SafeDep Cloud rejected the stored API key"} + } + warning = fmt.Sprintf("could not verify the stored API key: %v", err) + } + + switch state { + case APIKeyExpiring: + return APIKeyDecision{Reason: "the stored API key expires on " + formatDay(expiresAt), + Fallback: true, ExpiresAt: expiresAt, Warning: warning} + case APIKeyExpiryUnknown: + return APIKeyDecision{Reason: "the expiry of the stored API key is not recorded", + Fallback: true, Warning: warning} + } + + return APIKeyDecision{Keep: true, ExpiresAt: expiresAt, Warning: warning} +} + +func formatDay(t time.Time) string { + return t.UTC().Format("2006-01-02") +} + +// StoredAPIKey returns the API key credentials of the profile in the +// keychain, or nil when there are none. It reads the keychain alone: pmg and +// vet read the key from there, so an API key in the environment must not +// stop login from replacing an expired keychain key. +func StoredAPIKey(opts []cloud.KeychainOption) (*cloud.Credentials, error) { + resolver, err := cloud.NewKeychainCredentialResolver(cloud.CredentialTypeAPIKey, opts...) + if err != nil { + return nil, err + } + defer func() { + if err := resolver.Close(); err != nil { + log.Warnf("auth: close keychain resolver: %v", err) + } + }() + + creds, err := resolver.Resolve() + if errors.Is(err, cloud.ErrMissingCredentials) && !errors.Is(err, cloud.ErrIncompleteCredentials) { + return nil, nil + } + if err != nil { + return nil, err + } + return creds, nil +} diff --git a/internal/auth/apikey_renew_test.go b/internal/auth/apikey_renew_test.go new file mode 100644 index 0000000..2128261 --- /dev/null +++ b/internal/auth/apikey_renew_test.go @@ -0,0 +1,268 @@ +package auth + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/safedep/dry/cloud" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// keychainCredentials saves an API key the way login does and resolves it the +// way pmg and auth status do, so the test covers what the keychain holds. +func keychainCredentials(t *testing.T, key, tenant string, meta cloud.APIKeyMetadata) *cloud.Credentials { + t.Helper() + opts := []cloud.KeychainOption{ + cloud.WithAppName("safedep-cli-test-" + t.Name()), + cloud.WithInsecureFileFallbackPath(t.TempDir() + "/creds.json"), + } + + store, err := cloud.NewKeychainCredentialStore(opts...) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, store.Close()) }) + require.NoError(t, SaveBootstrapResult(store, "access", "refresh", &BootstrapResult{ + Tenant: tenant, APIKey: key, APIKeyID: meta.KeyID, APIKeyExpiresAt: meta.ExpiresAt, + })) + + resolver, err := cloud.NewKeychainCredentialResolver(cloud.CredentialTypeAPIKey, opts...) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, resolver.Close()) }) + + creds, err := resolver.Resolve() + require.NoError(t, err) + return creds +} + +func TestDecideStoredAPIKey(t *testing.T) { + now := time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC) + valid := cloud.APIKeyMetadata{KeyID: "key-1", ExpiresAt: now.Add(60 * 24 * time.Hour)} + + tests := []struct { + name string + // stored is nil for an empty keychain. + stored func(t *testing.T) *cloud.Credentials + verifyErr error + wantKeep bool + wantReason string + wantVerified bool + wantWarning bool + wantFallback bool + wantOther bool + }{ + { + name: "no stored key", + stored: func(*testing.T) *cloud.Credentials { return nil }, + wantReason: "no API key is stored", + }, + { + name: "a key of another tenant", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "old.safedep.io", valid) + }, + wantReason: `belongs to tenant "old.safedep.io"`, + wantOther: true, + }, + { + name: "an expired key", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", + cloud.APIKeyMetadata{KeyID: "key-1", ExpiresAt: now.Add(-24 * time.Hour)}) + }, + wantReason: "expired on 2026-11-21", + }, + { + name: "a key inside the renewal window that SafeDep Cloud accepts", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", + cloud.APIKeyMetadata{KeyID: "key-1", ExpiresAt: now.Add(3 * 24 * time.Hour)}) + }, + wantReason: "expires on 2026-11-25", + wantFallback: true, + wantVerified: true, + }, + { + // A revoked key inside the window must not become the fallback + // that login keeps when it cannot create a new key. + name: "a key inside the renewal window that SafeDep Cloud rejects", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", + cloud.APIKeyMetadata{KeyID: "key-1", ExpiresAt: now.Add(3 * 24 * time.Hour)}) + }, + verifyErr: fmt.Errorf("auth: data plane ping: %w", status.Error(codes.PermissionDenied, "revoked")), + wantReason: "SafeDep Cloud rejected the stored API key", + wantVerified: true, + }, + { + // Every key that a CLI saved before it recorded the expiry is one. + // Status cannot warn before it expires, so login replaces it and + // keeps it only when it cannot create a new key. + name: "a key with no recorded expiry that SafeDep Cloud accepts", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", cloud.APIKeyMetadata{}) + }, + wantReason: "expiry of the stored API key is not recorded", + wantFallback: true, + wantVerified: true, + }, + { + name: "a key with no recorded expiry that SafeDep Cloud rejects", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", cloud.APIKeyMetadata{}) + }, + verifyErr: fmt.Errorf("auth: data plane ping: %w", status.Error(codes.Unauthenticated, "key expired")), + wantReason: "SafeDep Cloud rejected the stored API key", + wantVerified: true, + }, + { + name: "a key that expires exactly at the end of the renewal window is kept", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", + cloud.APIKeyMetadata{KeyID: "key-1", ExpiresAt: now.Add(APIKeyRenewWindow)}) + }, + wantKeep: true, + wantVerified: true, + }, + { + name: "a key that expires now is expired", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", + cloud.APIKeyMetadata{KeyID: "key-1", ExpiresAt: now}) + }, + wantReason: "expired on 2026-11-22", + }, + { + name: "a valid key that SafeDep Cloud accepts", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", valid) + }, + wantKeep: true, + wantVerified: true, + }, + { + name: "a valid key that SafeDep Cloud rejects", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", valid) + }, + verifyErr: fmt.Errorf("auth: data plane ping: %w", status.Error(codes.Unauthenticated, "key expired")), + wantReason: "SafeDep Cloud rejected the stored API key", + wantVerified: true, + }, + { + name: "a valid key that the gateway does not know", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", valid) + }, + verifyErr: status.Error(codes.PermissionDenied, "access denied"), + wantReason: "SafeDep Cloud rejected the stored API key", + wantVerified: true, + }, + { + name: "a network failure keeps the key and warns", + stored: func(t *testing.T) *cloud.Credentials { + return keychainCredentials(t, "sk-1", "acme.safedep.io", valid) + }, + verifyErr: fmt.Errorf("auth: data plane ping: %w", status.Error(codes.Unavailable, "no route")), + wantKeep: true, + wantVerified: true, + wantWarning: true, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var verified APIKeyInput + verify := func(_ context.Context, in APIKeyInput) error { + verified = in + return tc.verifyErr + } + + got := DecideStoredAPIKey(context.Background(), tc.stored(t), "acme.safedep.io", now, verify) + + assert.Equal(t, tc.wantKeep, got.Keep) + if tc.wantReason == "" { + assert.Empty(t, got.Reason) + } else { + assert.Contains(t, got.Reason, tc.wantReason) + } + assert.Equal(t, tc.wantWarning, got.Warning != "", "warning %q", got.Warning) + assert.Equal(t, tc.wantFallback, got.Fallback) + assert.Equal(t, tc.wantOther, got.OtherTenant) + if tc.wantVerified { + assert.Equal(t, APIKeyInput{APIKey: "sk-1", Tenant: "acme.safedep.io"}, verified) + } else { + assert.Empty(t, verified, "the key must not be sent to SafeDep Cloud") + } + if got.Keep { + if exp, ok := tc.stored(t).APIKeyExpiresAt(); ok { + assert.True(t, exp.Equal(got.ExpiresAt)) + } else { + assert.True(t, got.ExpiresAt.IsZero()) + } + } + }) + } +} + +func TestBuildStatusReadsAPIKeyExpiry(t *testing.T) { + expiresAt := time.Date(2027, 2, 20, 0, 0, 0, 0, time.UTC) + opts := []cloud.KeychainOption{ + cloud.WithAppName("safedep-cli-test-" + t.Name()), + cloud.WithInsecureFileFallbackPath(t.TempDir() + "/creds.json"), + } + store, err := cloud.NewKeychainCredentialStore(opts...) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, store.Close()) }) + require.NoError(t, SaveBootstrapResult(store, "access", "refresh", &BootstrapResult{ + Tenant: "acme.safedep.io", APIKey: "sk-1", APIKeyID: "key-1", APIKeyExpiresAt: expiresAt, + })) + + st, err := BuildStatus(context.Background(), "default", opts) + require.NoError(t, err) + + assert.True(t, st.APIKey) + assert.True(t, expiresAt.Equal(st.APIKeyExpiresAt), "expiry %v", st.APIKeyExpiresAt) +} + +// pmg and vet read the keychain key. An API key in the environment must not +// hide an expired keychain key from login. +func TestStoredAPIKeyIgnoresTheEnvironment(t *testing.T) { + t.Setenv("SAFEDEP_API_KEY", "sk-env") + t.Setenv("SAFEDEP_TENANT_ID", "acme.safedep.io") + + opts := []cloud.KeychainOption{ + cloud.WithAppName("safedep-cli-test-" + t.Name()), + cloud.WithInsecureFileFallbackPath(t.TempDir() + "/creds.json"), + } + store, err := cloud.NewKeychainCredentialStore(opts...) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, store.Close()) }) + expired := time.Now().Add(-24 * time.Hour).UTC().Truncate(time.Second) + require.NoError(t, store.SaveAPIKeyCredentialWithMetadata( + "sk-keychain", "acme.safedep.io", cloud.APIKeyMetadata{KeyID: "key-1", ExpiresAt: expired})) + + creds, err := StoredAPIKey(opts) + require.NoError(t, err) + require.NotNil(t, creds) + + key, err := creds.GetAPIKey() + require.NoError(t, err) + assert.Equal(t, "sk-keychain", key) + got, ok := creds.APIKeyExpiresAt() + require.True(t, ok) + assert.True(t, expired.Equal(got)) +} + +func TestStoredAPIKeyEmptyKeychain(t *testing.T) { + opts := []cloud.KeychainOption{ + cloud.WithAppName("safedep-cli-test-" + t.Name()), + cloud.WithInsecureFileFallbackPath(t.TempDir() + "/creds.json"), + } + creds, err := StoredAPIKey(opts) + require.NoError(t, err) + assert.Nil(t, creds) +} diff --git a/internal/auth/bootstrap.go b/internal/auth/bootstrap.go index ea7d931..801b34f 100644 --- a/internal/auth/bootstrap.go +++ b/internal/auth/bootstrap.go @@ -36,6 +36,11 @@ type BootstrapInput struct { APIKeyName string Picker TenantPicker + // DecideAPIKey runs after the tenant is picked, so that a stored key for + // another tenant is replaced. When it keeps the stored key, no key is + // created. Nil means that a key is always created. + DecideAPIKey func(ctx context.Context, tenant string) APIKeyDecision + // RegistrationPrompter is called when the user has no accessible tenant. // It should collect registration data interactively and return it. When // nil, the zero-tenant case returns the existing "no accessible tenant" @@ -51,7 +56,16 @@ type BootstrapInput struct { type BootstrapResult struct { Tenant string APIKey string + APIKeyID string APIKeyExpiresAt time.Time + + // APIKeyDecision is what DecideAPIKey returned. Zero when it did not run. + APIKeyDecision APIKeyDecision + + // APIKeyError is why login could not create a key when DecideAPIKey ran + // and no usable key remains. The OAuth tokens of the login still work, + // so the caller saves them and reports the error as a warning. + APIKeyError error } // PostOAuthBootstrap completes the work that follows a successful device @@ -90,12 +104,44 @@ func PostOAuthBootstrap(ctx context.Context, in BootstrapInput) (*BootstrapResul return res, nil } - key, expiresAt, err := createAPIKey(ctx, in.ConnFor, in.AccessToken, tenant, in.APIKeyName, in.APIKeyExpiryDays) + if in.DecideAPIKey != nil { + res.APIKeyDecision = in.DecideAPIKey(ctx, tenant) + if res.APIKeyDecision.Keep { + return res, nil + } + } + + key, err := createAPIKey(ctx, in.ConnFor, in.AccessToken, tenant, in.APIKeyName, in.APIKeyExpiryDays) + if err != nil && in.DecideAPIKey != nil { + // A failed create must not cost the user the OAuth tokens of this + // login. A Viewer cannot create keys. Login fails instead for an + // explicit --rotate-api-key, which has no DecideAPIKey, and when the + // stored key belongs to another tenant. + decision := res.APIKeyDecision + if decision.Fallback && (decision.ExpiresAt.IsZero() || time.Now().Before(decision.ExpiresAt)) { + warning := fmt.Sprintf("could not create a new API key, so the stored key stays: %v", err) + if decision.Warning != "" { + warning = decision.Warning + ". " + warning + } + res.APIKeyDecision = APIKeyDecision{Keep: true, ExpiresAt: decision.ExpiresAt, Warning: warning} + return res, nil + } + if decision.OtherTenant { + return nil, err + } + res.APIKeyError = err + return res, nil + } if err != nil { return nil, err } - res.APIKey = key - res.APIKeyExpiresAt = expiresAt + res.APIKey = key.GetKey() + res.APIKeyID = key.GetKeyId() + // AsTime on a missing timestamp returns 1970-01-01. Saved as the expiry, + // it would make every later login replace a valid key. + if key.GetExpiresAt() != nil { + res.APIKeyExpiresAt = key.GetExpiresAt().AsTime() + } return res, nil } @@ -143,14 +189,16 @@ func pickTenant(tenants []string, preferred string, picker TenantPicker) (string return picker(tenants) } -func createAPIKey(ctx context.Context, connFor ControlPlaneConnFunc, token, tenant, name string, expiryDays int) (string, time.Time, error) { +func createAPIKey(ctx context.Context, connFor ControlPlaneConnFunc, token, tenant, name string, + expiryDays int, +) (*controltowerv1.CreateApiKeyResponse, error) { if expiryDays <= 0 || expiryDays > math.MaxInt32 { - return "", time.Time{}, fmt.Errorf("auth: api key expiry days out of range: %d", expiryDays) + return nil, fmt.Errorf("auth: api key expiry days out of range: %d", expiryDays) } conn, err := connFor(token, tenant) if err != nil { - return "", time.Time{}, err + return nil, err } defer closeConn("create api key", conn) @@ -162,9 +210,9 @@ func createAPIKey(ctx context.Context, connFor ControlPlaneConnFunc, token, tena ExpiryDays: int32(expiryDays), // #nosec G115 -- bounds-checked above }) if err != nil { - return "", time.Time{}, fmt.Errorf("auth: create api key: %w", err) + return nil, fmt.Errorf("auth: create api key: %w", err) } - return resp.GetKey(), resp.GetExpiresAt().AsTime(), nil + return resp, nil } // registerAndRefetch calls RegistrationPrompter to collect registration data, diff --git a/internal/auth/bootstrap_test.go b/internal/auth/bootstrap_test.go index b3130e3..b13aaab 100644 --- a/internal/auth/bootstrap_test.go +++ b/internal/auth/bootstrap_test.go @@ -5,6 +5,7 @@ import ( "errors" "net" "testing" + "time" controltowerv1grpc "buf.build/gen/go/safedep/api/grpc/go/safedep/services/controltower/v1/controltowerv1grpc" messagescontroltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1" @@ -12,8 +13,11 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" + "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/types/known/timestamppb" ) // fakeUserServer is a configurable UserServiceServer that returns a @@ -49,6 +53,28 @@ func (f *fakeUserServer) GetUserInfo(_ context.Context, _ *controltowerv1.GetUse type bootstrapTestServer struct { user *fakeUserServer onboarding *fakeOnboardingServer + apiKeys *fakeAPIKeyServer +} + +// fakeAPIKeyServer creates one API key per call and counts the calls. +type fakeAPIKeyServer struct { + controltowerv1grpc.UnimplementedApiKeyServiceServer + creates int + expiresAt time.Time + err error +} + +func (f *fakeAPIKeyServer) CreateApiKey(_ context.Context, req *controltowerv1.CreateApiKeyRequest, +) (*controltowerv1.CreateApiKeyResponse, error) { + f.creates++ + if f.err != nil { + return nil, f.err + } + resp := &controltowerv1.CreateApiKeyResponse{Key: "sk-new", KeyId: "key-new"} + if !f.expiresAt.IsZero() { + resp.ExpiresAt = timestamppb.New(f.expiresAt) + } + return resp, nil } func newBootstrapTestServer(t *testing.T, bts bootstrapTestServer) ControlPlaneConnFunc { @@ -57,6 +83,9 @@ func newBootstrapTestServer(t *testing.T, bts bootstrapTestServer) ControlPlaneC srv := grpc.NewServer() controltowerv1grpc.RegisterUserServiceServer(srv, bts.user) controltowerv1grpc.RegisterOnboardingServiceServer(srv, bts.onboarding) + if bts.apiKeys != nil { + controltowerv1grpc.RegisterApiKeyServiceServer(srv, bts.apiKeys) + } go func() { _ = srv.Serve(lis) }() t.Cleanup(func() { srv.Stop() @@ -176,3 +205,181 @@ func TestPostOAuthBootstrap_ZeroTenants_PrompterReturnsError_PropagatesError(t * require.Error(t, err) assert.Equal(t, promptErr, err) } + +// The decision on the stored key runs on the tenant that the user picked, so +// a key of the previous tenant is replaced. A kept key means no new key. +func TestPostOAuthBootstrap_DecideAPIKey(t *testing.T) { + expiresAt := time.Date(2027, 2, 20, 0, 0, 0, 0, time.UTC) + + tests := []struct { + name string + decision APIKeyDecision + noExpiry bool + wantCreates int + wantKey string + }{ + { + name: "a kept key creates no key", + decision: APIKeyDecision{Keep: true, ExpiresAt: expiresAt}, + wantCreates: 0, + }, + { + name: "a replaced key creates a key with its id and expiry", + decision: APIKeyDecision{Reason: "the stored API key expired on 2026-11-20"}, + wantCreates: 1, + wantKey: "sk-new", + }, + { + // A missing expiry must not become 1970-01-01, which every later + // login would read as expired. + name: "a response with no expiry records no expiry", + decision: APIKeyDecision{Reason: "no API key is stored"}, + noExpiry: true, + wantCreates: 1, + wantKey: "sk-new", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + apiKeys := &fakeAPIKeyServer{expiresAt: expiresAt} + if tc.noExpiry { + apiKeys.expiresAt = time.Time{} + } + connFor := newBootstrapTestServer(t, bootstrapTestServer{ + user: &fakeUserServer{responses: [][]string{{"old.safedep.io", "new.safedep.io"}}}, + onboarding: &fakeOnboardingServer{}, + apiKeys: apiKeys, + }) + + var decidedFor string + res, err := PostOAuthBootstrap(context.Background(), BootstrapInput{ + AccessToken: "token-123", + PreferredTenant: "old.safedep.io-gone", + CreateAPIKey: true, + APIKeyExpiryDays: 90, + Picker: func([]string) (string, error) { return "new.safedep.io", nil }, + DecideAPIKey: func(_ context.Context, tenant string) APIKeyDecision { + decidedFor = tenant + return tc.decision + }, + ConnFor: connFor, + }) + require.NoError(t, err) + + assert.Equal(t, "new.safedep.io", decidedFor, "the decision must see the picked tenant") + assert.Equal(t, tc.wantCreates, apiKeys.creates) + assert.Equal(t, tc.decision, res.APIKeyDecision) + assert.Equal(t, tc.wantKey, res.APIKey) + if tc.wantKey != "" { + assert.Equal(t, "key-new", res.APIKeyID) + assert.True(t, apiKeys.expiresAt.Equal(res.APIKeyExpiresAt), + "expiry %v, want %v", res.APIKeyExpiresAt, apiKeys.expiresAt) + } + }) + } +} + +// A login must not lose its OAuth tokens because the create failed while the +// stored key still works, for example for a user who cannot create keys. +func TestPostOAuthBootstrap_CreateFails(t *testing.T) { + expiresAt := time.Now().Add(72 * time.Hour).UTC().Truncate(time.Second) + keep := func(d APIKeyDecision) func(context.Context, string) APIKeyDecision { + return func(context.Context, string) APIKeyDecision { return d } + } + + tests := []struct { + name string + // decide is nil for --rotate-api-key. + decide func(context.Context, string) APIKeyDecision + wantErr bool + wantKeep bool + wantExpiresAt time.Time + wantWarnings []string + wantCreateError bool + }{ + { + name: "a stored key that still works is kept", + decide: keep(APIKeyDecision{Reason: "the stored API key expires soon", Fallback: true, ExpiresAt: expiresAt}), + wantKeep: true, + wantExpiresAt: expiresAt, + wantWarnings: []string{"could not create a new API key"}, + }, + { + name: "both warnings reach the user", + decide: keep(APIKeyDecision{Reason: "the stored API key expires soon", Fallback: true, ExpiresAt: expiresAt, + Warning: "could not verify the stored API key: no route"}), + wantKeep: true, + wantExpiresAt: expiresAt, + wantWarnings: []string{"could not verify the stored API key", "could not create a new API key"}, + }, + { + name: "a stored key with no recorded expiry that still works is kept", + decide: keep(APIKeyDecision{Reason: "the expiry of the stored API key is not recorded", Fallback: true}), + wantKeep: true, + wantWarnings: []string{"could not create a new API key"}, + }, + { + // The OAuth tokens of the login still work, so the caller saves + // them and reports the error. + name: "a fallback that expired during the create leaves no key", + decide: keep(APIKeyDecision{Reason: "the stored API key expires soon", Fallback: true, + ExpiresAt: time.Now().Add(-time.Second)}), + wantCreateError: true, + }, + { + name: "no usable stored key leaves no key", + decide: keep(APIKeyDecision{Reason: "the stored API key expired"}), + wantCreateError: true, + }, + { + // B's OAuth tokens next to A's key would send data plane calls + // to tenant A. + name: "a stored key of another tenant fails the login", + decide: keep(APIKeyDecision{Reason: `the stored API key belongs to tenant "old.safedep.io"`, + OtherTenant: true}), + wantErr: true, + }, + { + name: "--rotate-api-key fails the login", + wantErr: true, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + connFor := newBootstrapTestServer(t, bootstrapTestServer{ + user: &fakeUserServer{responses: [][]string{{"acme.safedep.io"}}}, + onboarding: &fakeOnboardingServer{}, + apiKeys: &fakeAPIKeyServer{err: status.Error(codes.PermissionDenied, "member role required")}, + }) + + res, err := PostOAuthBootstrap(context.Background(), BootstrapInput{ + AccessToken: "token-123", + CreateAPIKey: true, + APIKeyExpiryDays: 90, + DecideAPIKey: tc.decide, + ConnFor: connFor, + }) + + if tc.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + assert.Empty(t, res.APIKey) + assert.Equal(t, tc.wantKeep, res.APIKeyDecision.Keep) + if tc.wantKeep { + assert.True(t, tc.wantExpiresAt.Equal(res.APIKeyDecision.ExpiresAt)) + } + for _, w := range tc.wantWarnings { + assert.Contains(t, res.APIKeyDecision.Warning, w) + } + if tc.wantCreateError { + assert.Equal(t, codes.PermissionDenied, status.Code(res.APIKeyError)) + } else { + assert.NoError(t, res.APIKeyError) + } + }) + } +} diff --git a/internal/auth/mocks/CredentialStore_mock.go b/internal/auth/mocks/CredentialStore_mock.go index a42b6c5..55628ae 100644 --- a/internal/auth/mocks/CredentialStore_mock.go +++ b/internal/auth/mocks/CredentialStore_mock.go @@ -5,6 +5,7 @@ package mocks import ( + "github.com/safedep/dry/cloud" mock "github.com/stretchr/testify/mock" ) @@ -180,6 +181,69 @@ func (_c *CredentialStoreMock_SaveAPIKeyCredential_Call) RunAndReturn(run func(a return _c } +// SaveAPIKeyCredentialWithMetadata provides a mock function for the type CredentialStoreMock +func (_mock *CredentialStoreMock) SaveAPIKeyCredentialWithMetadata(apiKey string, tenantDomain string, meta cloud.APIKeyMetadata) error { + ret := _mock.Called(apiKey, tenantDomain, meta) + + if len(ret) == 0 { + panic("no return value specified for SaveAPIKeyCredentialWithMetadata") + } + + var r0 error + if returnFunc, ok := ret.Get(0).(func(string, string, cloud.APIKeyMetadata) error); ok { + r0 = returnFunc(apiKey, tenantDomain, meta) + } else { + r0 = ret.Error(0) + } + return r0 +} + +// CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SaveAPIKeyCredentialWithMetadata' +type CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call struct { + *mock.Call +} + +// SaveAPIKeyCredentialWithMetadata is a helper method to define mock.On call +// - apiKey string +// - tenantDomain string +// - meta cloud.APIKeyMetadata +func (_e *CredentialStoreMock_Expecter) SaveAPIKeyCredentialWithMetadata(apiKey interface{}, tenantDomain interface{}, meta interface{}) *CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call { + return &CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call{Call: _e.mock.On("SaveAPIKeyCredentialWithMetadata", apiKey, tenantDomain, meta)} +} + +func (_c *CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call) Run(run func(apiKey string, tenantDomain string, meta cloud.APIKeyMetadata)) *CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 string + if args[0] != nil { + arg0 = args[0].(string) + } + var arg1 string + if args[1] != nil { + arg1 = args[1].(string) + } + var arg2 cloud.APIKeyMetadata + if args[2] != nil { + arg2 = args[2].(cloud.APIKeyMetadata) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call) Return(err error) *CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call { + _c.Call.Return(err) + return _c +} + +func (_c *CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call) RunAndReturn(run func(apiKey string, tenantDomain string, meta cloud.APIKeyMetadata) error) *CredentialStoreMock_SaveAPIKeyCredentialWithMetadata_Call { + _c.Call.Return(run) + return _c +} + // SaveTokenCredential provides a mock function for the type CredentialStoreMock func (_mock *CredentialStoreMock) SaveTokenCredential(token string, refreshToken string, tenantDomain string) error { ret := _mock.Called(token, refreshToken, tenantDomain) diff --git a/internal/auth/save.go b/internal/auth/save.go index 98feed3..2d2de94 100644 --- a/internal/auth/save.go +++ b/internal/auth/save.go @@ -7,16 +7,24 @@ import ( ) // SaveBootstrapResult persists the access token, refresh token, and (if present) -// API key from a completed bootstrap to the credential store. +// API key from a completed bootstrap to the credential store. The key is saved +// with its id and expiry, so that the next login and auth status can tell an +// expired key from a valid one. func SaveBootstrapResult(store cloud.CredentialStore, accessToken, refreshToken string, b *BootstrapResult) error { if err := store.SaveTokenCredential(accessToken, refreshToken, b.Tenant); err != nil { return fmt.Errorf("save token credential: %w", err) } - if b.APIKey != "" { - if err := store.SaveAPIKeyCredential(b.APIKey, b.Tenant); err != nil { - return fmt.Errorf("save api key credential: %w", err) - } + if b.APIKey == "" { + return nil + } + + err := store.SaveAPIKeyCredentialWithMetadata(b.APIKey, b.Tenant, cloud.APIKeyMetadata{ + KeyID: b.APIKeyID, + ExpiresAt: b.APIKeyExpiresAt, + }) + if err != nil { + return fmt.Errorf("save api key credential: %w", err) } return nil diff --git a/internal/auth/save_test.go b/internal/auth/save_test.go index 5156dfd..cbef071 100644 --- a/internal/auth/save_test.go +++ b/internal/auth/save_test.go @@ -6,11 +6,14 @@ import ( "time" "github.com/safedep/cli/internal/auth/mocks" + "github.com/safedep/dry/cloud" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSaveBootstrapResult(t *testing.T) { + expiresAt := time.Now().Add(24 * time.Hour) + tests := []struct { name string setup func(t *testing.T) *mocks.CredentialStoreMock @@ -25,7 +28,8 @@ func TestSaveBootstrapResult(t *testing.T) { setup: func(t *testing.T) *mocks.CredentialStoreMock { m := mocks.NewCredentialStoreMock(t) m.EXPECT().SaveTokenCredential("access-token-123", "refresh-token-456", "example.safedep.io").Return(nil) - m.EXPECT().SaveAPIKeyCredential("api-key-789", "example.safedep.io").Return(nil) + m.EXPECT().SaveAPIKeyCredentialWithMetadata("api-key-789", "example.safedep.io", + cloud.APIKeyMetadata{KeyID: "key-1", ExpiresAt: expiresAt}).Return(nil) return m }, accessToken: "access-token-123", @@ -33,7 +37,8 @@ func TestSaveBootstrapResult(t *testing.T) { bootstrap: &BootstrapResult{ Tenant: "example.safedep.io", APIKey: "api-key-789", - APIKeyExpiresAt: time.Now().Add(24 * time.Hour), + APIKeyID: "key-1", + APIKeyExpiresAt: expiresAt, }, expectErr: false, }, @@ -70,11 +75,12 @@ func TestSaveBootstrapResult(t *testing.T) { expectErrText: "save token credential:", }, { - name: "error on SaveAPIKeyCredential", + name: "error on SaveAPIKeyCredentialWithMetadata", setup: func(t *testing.T) *mocks.CredentialStoreMock { m := mocks.NewCredentialStoreMock(t) m.EXPECT().SaveTokenCredential("access-token-123", "refresh-token-456", "example.safedep.io").Return(nil) - m.EXPECT().SaveAPIKeyCredential("api-key-789", "example.safedep.io").Return(errors.New("keychain error")) + m.EXPECT().SaveAPIKeyCredentialWithMetadata("api-key-789", "example.safedep.io", cloud.APIKeyMetadata{}). + Return(errors.New("keychain error")) return m }, accessToken: "access-token-123", diff --git a/internal/auth/status.go b/internal/auth/status.go index 4fc0252..a3f4b70 100644 --- a/internal/auth/status.go +++ b/internal/auth/status.go @@ -16,6 +16,15 @@ type Status struct { APIKey bool OAuth bool OAuthExpiresAt time.Time + + // APIKeyExpiresAt is the recorded expiry of the API key. Zero when the + // keychain holds no expiry for it. + APIKeyExpiresAt time.Time +} + +// APIKeyState returns the state of the stored API key at now. +func (s Status) APIKeyState(now time.Time) APIKeyState { + return APIKeyStateAt(s.APIKey, s.APIKeyExpiresAt, now) } // OAuthValid reports whether the profile holds an OAuth access token that @@ -43,6 +52,9 @@ func BuildStatus(_ context.Context, profile string, opts []cloud.KeychainOption) if t, terr := creds.GetTenantDomain(); terr == nil { s.Tenant = t } + if exp, ok := creds.APIKeyExpiresAt(); ok { + s.APIKeyExpiresAt = exp + } } else if !isMissingCredentials(err) { return s, err } diff --git a/internal/cmd/auth/login.go b/internal/cmd/auth/login.go index 9c46c10..6695697 100644 --- a/internal/cmd/auth/login.go +++ b/internal/cmd/auth/login.go @@ -1,9 +1,11 @@ package auth import ( + "context" "errors" "fmt" "io" + "math" "os" "strings" "time" @@ -87,11 +89,46 @@ func runAPIKeyLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { return nil } +// deviceLoginDeps holds what device login reaches outside the process: +// the keychain, the browser flow, the control plane and the data plane. +// runDeviceLogin fills it from App and the network. Tests fill it with fakes. +type deviceLoginDeps struct { + store func() (cloud.CredentialStore, error) + storedAPIKey func() (*cloud.Credentials, error) + deviceFlow func(context.Context) (*cliauth.DeviceFlowResult, error) + bootstrap func(context.Context, cliauth.BootstrapInput) (*cliauth.BootstrapResult, error) + verify cliauth.APIKeyVerifier +} + func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { + return deviceLogin(cmd, a, flags, deviceLoginDeps{ + store: a.CredentialStore, + storedAPIKey: a.StoredAPIKey, + deviceFlow: func(ctx context.Context) (*cliauth.DeviceFlowResult, error) { + return cliauth.RunDeviceFlow(ctx, cliauth.PrintVerification, + cliauth.EmailVerificationRetry(cmd.InOrStdin())) + }, + bootstrap: cliauth.PostOAuthBootstrap, + verify: cliauth.VerifyAPIKey, + }) +} + +func deviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags, deps deviceLoginDeps) error { + if err := validateAPIKeyExpiryDays(flags); err != nil { + return err + } + + // Open the keychain before the browser flow. A machine with no usable + // keychain then fails before SafeDep Cloud creates a key that login + // could not store. + store, err := deps.store() + if err != nil { + return err + } + tui.Info("Starting OAuth2 device login…") - res, err := cliauth.RunDeviceFlow(cmd.Context(), cliauth.PrintVerification, - cliauth.EmailVerificationRetry(cmd.InOrStdin())) + res, err := deps.deviceFlow(cmd.Context()) if err != nil { return err } @@ -104,7 +141,11 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { } } - createKey, name := apiKeyCreationPlan(a, preferredTenant, flags) + createKey, decideAPIKey := apiKeyPlan(flags, deps.storedAPIKey, deps.verify) + var name string + if createKey { + name = cliauth.APIKeyName(cliauth.Hostname(), time.Now()) + } var registrationPrompter func() (*cliauth.RegistrationInput, error) if flags.noAPIKey { @@ -115,12 +156,13 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { registrationPrompter = cliauth.NewRegistrationPrompter(res.AccessToken) } - bootstrap, err := cliauth.PostOAuthBootstrap(cmd.Context(), cliauth.BootstrapInput{ + bootstrap, err := deps.bootstrap(cmd.Context(), cliauth.BootstrapInput{ AccessToken: res.AccessToken, PreferredTenant: preferredTenant, CreateAPIKey: createKey, APIKeyName: name, APIKeyExpiryDays: flags.apiKeyExpiryDays, + DecideAPIKey: decideAPIKey, Picker: cliauth.PromptTenantPicker, RegistrationPrompter: registrationPrompter, }) @@ -128,19 +170,29 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { return err } - store, err := a.CredentialStore() - if err != nil { + if err := cliauth.SaveBootstrapResult(store, res.AccessToken, res.RefreshToken, bootstrap); err != nil { return err } - if err := cliauth.SaveBootstrapResult(store, res.AccessToken, res.RefreshToken, bootstrap); err != nil { - return err + decision := bootstrap.APIKeyDecision + if decision.Warning != "" { + tui.Warning("%s", decision.Warning) } switch { + case bootstrap.APIKeyError != nil: + tui.Warning("Could not create an API key: %v", bootstrap.APIKeyError) + tui.Success("Authenticated as %s (profile %q). OAuth tokens stored. No usable API key: %s.", + bootstrap.Tenant, a.Profile(), decision.Reason) case bootstrap.APIKey != "": - tui.Success("Authenticated as %s (profile %q). API key created, expires %s.", - bootstrap.Tenant, a.Profile(), bootstrap.APIKeyExpiresAt.UTC().Format("2006-01-02")) + if decision.Reason != "" { + tui.Info("Created a new API key: %s.", decision.Reason) + } + tui.Success("Authenticated as %s (profile %q). API key created, %s.", + bootstrap.Tenant, a.Profile(), expiryPhrase(bootstrap.APIKeyExpiresAt)) + case decision.Keep: + tui.Success("Authenticated as %s (profile %q). Kept the stored API key, %s.", + bootstrap.Tenant, a.Profile(), expiryPhrase(decision.ExpiresAt)) case createKey: tui.Success("Authenticated as %s (profile %q). API key creation skipped — none in response.", bootstrap.Tenant, a.Profile()) default: @@ -150,39 +202,55 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { return nil } -// apiKeyCreationPlan decides whether to ask the bootstrap to create an API -// key, and what to name it. --no-api-key wins. --rotate-api-key always -// creates. Otherwise we skip when the profile already holds a key for the -// preferred tenant. -func apiKeyCreationPlan(a *app.App, preferredTenant string, flags loginFlags) (bool, string) { +// validateAPIKeyExpiryDays refuses a lifetime that SafeDep Cloud would refuse, +// before the browser flow. It also refuses a lifetime inside the renewal +// window: login replaces a key that expires within the window, so such a key +// would be replaced on every login. --rotate-api-key asks for a new key in +// any case, so it accepts a short lifetime. +func validateAPIKeyExpiryDays(flags loginFlags) error { if flags.noAPIKey { - return false, "" + return nil + } + if flags.apiKeyExpiryDays <= 0 || flags.apiKeyExpiryDays > math.MaxInt32 { + return fmt.Errorf("--api-key-expiry-days must be a positive number of days: got %d", flags.apiKeyExpiryDays) } - if !flags.rotateAPIKey && hasAPIKeyForTenant(a, preferredTenant) { - log.Warnf("auth login: existing API key kept; use --rotate-api-key to create a new one") - return false, "" + if flags.rotateAPIKey { + return nil } - return true, cliauth.APIKeyName(cliauth.Hostname(), time.Now()) + windowDays := int(cliauth.APIKeyRenewWindow.Hours() / 24) + if flags.apiKeyExpiryDays <= windowDays { + return fmt.Errorf("--api-key-expiry-days must be more than %d: login replaces a key that expires within %d days", + windowDays, windowDays) + } + return nil } -func hasAPIKeyForTenant(a *app.App, tenant string) bool { - if tenant == "" { - return false +// apiKeyPlan returns whether login creates or checks an API key, and the +// check that decides on the stored key once the tenant is picked. The check +// is nil when login always creates a key. +func apiKeyPlan(flags loginFlags, storedAPIKey func() (*cloud.Credentials, error), verify cliauth.APIKeyVerifier, +) (bool, func(context.Context, string) cliauth.APIKeyDecision) { + if flags.noAPIKey { + return false, nil } - resolver, err := a.APIKeyResolver() - if err != nil { - log.Warnf("auth login: api-key check: %v", err) - return false + if flags.rotateAPIKey { + return true, nil } - creds, err := resolver.Resolve() - if err != nil { - return false + return true, func(ctx context.Context, tenant string) cliauth.APIKeyDecision { + stored, err := storedAPIKey() + if err != nil { + return cliauth.APIKeyDecision{Reason: fmt.Sprintf("the stored API key cannot be read: %v", err)} + } + return cliauth.DecideStoredAPIKey(ctx, stored, tenant, time.Now(), verify) } - got, err := creds.GetTenantDomain() - if err != nil { - return false +} + +// expiryPhrase reports the expiry of a key for the login message. +func expiryPhrase(expiresAt time.Time) string { + if expiresAt.IsZero() { + return "expiry not recorded" } - return got == tenant + return "expires " + expiresAt.UTC().Format("2006-01-02") } func resolveAPIKey(flags loginFlags) (string, error) { diff --git a/internal/cmd/auth/login_test.go b/internal/cmd/auth/login_test.go new file mode 100644 index 0000000..74dfab6 --- /dev/null +++ b/internal/cmd/auth/login_test.go @@ -0,0 +1,181 @@ +package auth + +import ( + "bytes" + "context" + "io" + "os" + "testing" + "time" + + "github.com/safedep/cli/internal/app" + cliauth "github.com/safedep/cli/internal/auth" + "github.com/safedep/cli/internal/config" + "github.com/safedep/dry/cloud" + "github.com/safedep/dry/tui/output" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestAPIKeyPlan(t *testing.T) { + tests := []struct { + name string + flags loginFlags + wantCreate bool + wantDecider bool + }{ + {name: "default checks the stored key", flags: loginFlags{}, wantCreate: true, wantDecider: true}, + {name: "--rotate-api-key always creates", flags: loginFlags{rotateAPIKey: true}, wantCreate: true}, + {name: "--no-api-key creates no key", flags: loginFlags{noAPIKey: true}}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + create, decide := apiKeyPlan(tc.flags, nil, nil) + assert.Equal(t, tc.wantCreate, create) + assert.Equal(t, tc.wantDecider, decide != nil) + }) + } +} + +func TestValidateAPIKeyExpiryDays(t *testing.T) { + assert.Error(t, validateAPIKeyExpiryDays(loginFlags{apiKeyExpiryDays: 14})) + assert.NoError(t, validateAPIKeyExpiryDays(loginFlags{apiKeyExpiryDays: 15})) + assert.NoError(t, validateAPIKeyExpiryDays(loginFlags{apiKeyExpiryDays: 1, noAPIKey: true})) + assert.NoError(t, validateAPIKeyExpiryDays(loginFlags{apiKeyExpiryDays: 7, rotateAPIKey: true})) + assert.Error(t, validateAPIKeyExpiryDays(loginFlags{apiKeyExpiryDays: 0, rotateAPIKey: true})) +} + +// TestDeviceLogin runs device login against a file keychain, a fake data +// plane and a bootstrap that calls the key check of login, so it covers what +// login hands the bootstrap, what it saves and what it tells the user. +func TestDeviceLogin(t *testing.T) { + const tenant = "acme.safedep.io" + now := time.Now().UTC().Truncate(time.Second) + newExpiry := now.Add(90 * 24 * time.Hour) + + tests := []struct { + name string + storedExpiry time.Time + verifyErr error + createErr error + wantAPIKey string + wantVerified bool + wantOutput []string + }{ + { + name: "replaces an expired stored key and saves the new one", + storedExpiry: now.Add(-24 * time.Hour), + wantAPIKey: "sk-new", + wantOutput: []string{"Created a new API key: the stored API key expired on"}, + }, + { + name: "keeps a valid stored key and reports a failed check", + storedExpiry: now.Add(60 * 24 * time.Hour), + verifyErr: status.Error(codes.Unavailable, "no route"), + wantAPIKey: "sk-old", + wantVerified: true, + wantOutput: []string{"could not verify the stored API key", "Kept the stored API key"}, + }, + { + name: "replaces a key that SafeDep Cloud rejects", + storedExpiry: now.Add(60 * 24 * time.Hour), + verifyErr: status.Error(codes.Unauthenticated, "key expired"), + wantAPIKey: "sk-new", + wantVerified: true, + wantOutput: []string{"Created a new API key: SafeDep Cloud rejected the stored API key"}, + }, + { + name: "saves the OAuth tokens when no key can be created", + storedExpiry: now.Add(-24 * time.Hour), + createErr: status.Error(codes.PermissionDenied, "member role required"), + wantAPIKey: "sk-old", + wantOutput: []string{"Could not create an API key", "No usable API key: the stored API key expired on"}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + opts := []cloud.KeychainOption{ + cloud.WithAppName("safedep-cli-test-" + t.Name()), + cloud.WithInsecureFileFallbackPath(t.TempDir() + "/creds.json"), + } + store, err := cloud.NewKeychainCredentialStore(opts...) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, store.Close()) }) + require.NoError(t, cliauth.SaveBootstrapResult(store, "access-old", "refresh-old", &cliauth.BootstrapResult{ + Tenant: tenant, APIKey: "sk-old", APIKeyID: "key-old", APIKeyExpiresAt: tc.storedExpiry, + })) + + var verified cliauth.APIKeyInput + deps := deviceLoginDeps{ + store: func() (cloud.CredentialStore, error) { return store, nil }, + storedAPIKey: func() (*cloud.Credentials, error) { return cliauth.StoredAPIKey(opts) }, + deviceFlow: func(context.Context) (*cliauth.DeviceFlowResult, error) { + return &cliauth.DeviceFlowResult{AccessToken: "access-new", RefreshToken: "refresh-new"}, nil + }, + verify: func(_ context.Context, in cliauth.APIKeyInput) error { + verified = in + return tc.verifyErr + }, + // The bootstrap of login after the tenant pick: it keeps the + // stored key when the check says so, and creates a key + // otherwise. + bootstrap: func(ctx context.Context, in cliauth.BootstrapInput) (*cliauth.BootstrapResult, error) { + res := &cliauth.BootstrapResult{Tenant: tenant} + if in.DecideAPIKey != nil { + res.APIKeyDecision = in.DecideAPIKey(ctx, tenant) + if res.APIKeyDecision.Keep { + return res, nil + } + } + if tc.createErr != nil { + res.APIKeyError = tc.createErr + return res, nil + } + res.APIKey, res.APIKeyID, res.APIKeyExpiresAt = "sk-new", "key-new", newExpiry + return res, nil + }, + } + + var stderr bytes.Buffer + output.SetWriters(io.Discard, &stderr) + t.Cleanup(func() { output.SetWriters(os.Stdout, os.Stderr) }) + + cmd := &cobra.Command{} + cmd.SetContext(context.Background()) + err = deviceLogin(cmd, app.New(&config.Config{}), loginFlags{tenant: tenant, apiKeyExpiryDays: 90}, deps) + require.NoError(t, err) + + stored, err := cliauth.StoredAPIKey(opts) + require.NoError(t, err) + key, err := stored.GetAPIKey() + require.NoError(t, err) + assert.Equal(t, tc.wantAPIKey, key) + if tc.wantAPIKey == "sk-new" { + expiresAt, ok := stored.APIKeyExpiresAt() + require.True(t, ok) + assert.True(t, newExpiry.Equal(expiresAt)) + } + + tokens, err := cloud.NewKeychainCredentialResolver(cloud.CredentialTypeToken, opts...) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, tokens.Close()) }) + creds, err := tokens.Resolve() + require.NoError(t, err) + token, err := creds.GetToken() + require.NoError(t, err) + assert.Equal(t, "access-new", token, "login must save the OAuth tokens") + + if tc.wantVerified { + assert.Equal(t, cliauth.APIKeyInput{APIKey: "sk-old", Tenant: tenant}, verified) + } + for _, want := range tc.wantOutput { + assert.Contains(t, stderr.String(), want) + } + }) + } +} diff --git a/internal/cmd/auth/status.go b/internal/cmd/auth/status.go index 381a7f6..b480930 100644 --- a/internal/cmd/auth/status.go +++ b/internal/cmd/auth/status.go @@ -36,19 +36,25 @@ type statusResult struct { } type statusJSON struct { - Profile string `json:"profile"` - Tenant string `json:"tenant,omitempty"` - APIKey bool `json:"api_key_present"` - OAuthToken bool `json:"oauth_token_present"` - OAuthExpiresAt string `json:"oauth_expires_at,omitempty"` + Profile string `json:"profile"` + Tenant string `json:"tenant,omitempty"` + APIKey bool `json:"api_key_present"` + APIKeyState string `json:"api_key_state"` + APIKeyExpiresAt string `json:"api_key_expires_at,omitempty"` + OAuthToken bool `json:"oauth_token_present"` + OAuthExpiresAt string `json:"oauth_expires_at,omitempty"` } func (r *statusResult) RenderJSON() ([]byte, error) { out := statusJSON{ - Profile: r.st.Profile, - Tenant: r.st.Tenant, - APIKey: r.st.APIKey, - OAuthToken: r.st.OAuth, + Profile: r.st.Profile, + Tenant: r.st.Tenant, + APIKey: r.st.APIKey, + APIKeyState: apiKeyStateName(r.st.APIKeyState(time.Now())), + OAuthToken: r.st.OAuth, + } + if !r.st.APIKeyExpiresAt.IsZero() { + out.APIKeyExpiresAt = r.st.APIKeyExpiresAt.UTC().Format(time.RFC3339) } if !r.st.OAuthExpiresAt.IsZero() { out.OAuthExpiresAt = r.st.OAuthExpiresAt.UTC().Format(time.RFC3339) @@ -63,6 +69,12 @@ func (r *statusResult) RenderPlain() string { fmt.Fprintf(&sb, "Tenant: %s\n", r.st.Tenant) } fmt.Fprintf(&sb, "API key: %s\n", yesNo(r.st.APIKey)) + if r.st.APIKey { + fmt.Fprintf(&sb, "API key state: %s\n", apiKeyStateName(r.st.APIKeyState(time.Now()))) + } + if !r.st.APIKeyExpiresAt.IsZero() { + fmt.Fprintf(&sb, "Key expires: %s\n", r.st.APIKeyExpiresAt.UTC().Format(time.RFC3339)) + } fmt.Fprintf(&sb, "OAuth token: %s\n", yesNo(r.st.OAuth)) if !r.st.OAuthExpiresAt.IsZero() { fmt.Fprintf(&sb, "OAuth expires: %s\n", r.st.OAuthExpiresAt.UTC().Format(time.RFC3339)) @@ -80,7 +92,9 @@ func (r *statusResult) RenderTable() string { Field("Status", overallStatusBadge(r.st, now)). Field("Profile", r.st.Profile). Field("Tenant", emptyDash(r.st.Tenant)). - Field("API key", yesNoBadge(r.st.APIKey)). + Field("API key", apiKeyBadge(r.st, now)). + FieldIf(!r.st.APIKeyExpiresAt.IsZero(), apiKeyExpiryLabel(r.st, now), + humanize.Time(r.st.APIKeyExpiresAt, now)). Field("OAuth token", oauthBadge(r.st, now)). FieldIf(!r.st.OAuthExpiresAt.IsZero(), expiryLabel, humanize.Time(r.st.OAuthExpiresAt, now)). @@ -93,10 +107,10 @@ func (r *statusResult) RenderTable() string { // overallStatusBadge summarises the credential state in one badge so users // do not have to reason over the per-credential rows. An expired OAuth -// token does not count as authenticated. +// token or an expired API key does not count as authenticated. func overallStatusBadge(st cliauth.Status, now time.Time) string { switch { - case st.APIKey && st.OAuthValid(now): + case st.APIKey && st.APIKeyState(now) != cliauth.APIKeyExpired && st.OAuthValid(now): return drytui.Badge(theme.RoleSuccess, "authenticated") case st.APIKey || st.OAuth: return drytui.Badge(theme.RoleMedium, "partially authenticated") @@ -122,28 +136,67 @@ func nextStepHint(st cliauth.Status, now time.Time) string { switch { case !st.APIKey && !st.OAuth: return "Run 'safedep auth login' to authenticate with SafeDep Cloud." + case st.APIKeyState(now) == cliauth.APIKeyExpired: + return "API key expired. Run 'safedep auth login' to create a new one." case st.OAuth && !st.OAuthValid(now): return "OAuth token expired. Run 'safedep auth login' to re-authenticate." case !st.APIKey: return "Data plane API key missing. Run 'safedep auth login' to create one." case !st.OAuth: return "Control plane OAuth token missing. Run 'safedep auth login' to complete setup." + case st.APIKeyState(now) == cliauth.APIKeyExpiring: + return "API key expires soon. Run 'safedep auth login' to renew it." + case st.APIKeyState(now) == cliauth.APIKeyExpiryUnknown: + return "API key expiry is not recorded, so status cannot tell whether the key has expired. " + + "Run 'safedep auth login' to replace it with a key whose expiry is recorded." } return "" } -func yesNo(b bool) string { - if b { - return "yes" +func apiKeyBadge(st cliauth.Status, now time.Time) string { + switch st.APIKeyState(now) { + case cliauth.APIKeyMissing: + return drytui.Badge(theme.RoleWarning, "not configured") + case cliauth.APIKeyExpired: + return drytui.Badge(theme.RoleError, "expired") + case cliauth.APIKeyExpiring: + return drytui.Badge(theme.RoleMedium, "expires soon") + case cliauth.APIKeyExpiryUnknown: + return drytui.Badge(theme.RoleMedium, "expiry unknown") + default: + return drytui.Badge(theme.RoleSuccess, "configured") } - return "no" } -func yesNoBadge(b bool) string { +func apiKeyExpiryLabel(st cliauth.Status, now time.Time) string { + if st.APIKeyState(now) == cliauth.APIKeyExpired { + return "API key expired" + } + return "API key expires" +} + +// apiKeyStateName is the JSON name of a state. Scripts match on it, so the +// names do not change. +func apiKeyStateName(state cliauth.APIKeyState) string { + switch state { + case cliauth.APIKeyValid: + return "valid" + case cliauth.APIKeyExpiring: + return "expiring" + case cliauth.APIKeyExpired: + return "expired" + case cliauth.APIKeyExpiryUnknown: + return "expiry_unknown" + default: + return "missing" + } +} + +func yesNo(b bool) string { if b { - return drytui.Badge(theme.RoleSuccess, "configured") + return "yes" } - return drytui.Badge(theme.RoleWarning, "not configured") + return "no" } func emptyDash(s string) string { diff --git a/internal/cmd/auth/status_test.go b/internal/cmd/auth/status_test.go index a261b8c..0bd5fc6 100644 --- a/internal/cmd/auth/status_test.go +++ b/internal/cmd/auth/status_test.go @@ -1,17 +1,22 @@ package auth import ( + "encoding/json" "strings" "testing" "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" cliauth "github.com/safedep/cli/internal/auth" ) var statusNow = time.Date(2026, 7, 12, 12, 0, 0, 0, time.UTC) +// keyValidUntil is an API key expiry outside the renewal window of statusNow. +var keyValidUntil = statusNow.Add(60 * 24 * time.Hour) + func TestNextStepHint(t *testing.T) { tests := []struct { name string @@ -21,12 +26,27 @@ func TestNextStepHint(t *testing.T) { {"nothing configured", cliauth.Status{}, "safedep auth login"}, {"api key only", cliauth.Status{APIKey: true}, "OAuth token missing"}, {"oauth only", cliauth.Status{OAuth: true}, "API key missing"}, - {"fully authenticated", cliauth.Status{APIKey: true, OAuth: true}, ""}, + {"fully authenticated", cliauth.Status{APIKey: true, OAuth: true, APIKeyExpiresAt: keyValidUntil}, ""}, { "oauth expired", cliauth.Status{APIKey: true, OAuth: true, OAuthExpiresAt: statusNow.Add(-16 * 24 * time.Hour)}, "OAuth token expired", }, + { + "api key expired with a valid oauth token", + cliauth.Status{APIKey: true, OAuth: true, APIKeyExpiresAt: statusNow.Add(-time.Hour)}, + "API key expired", + }, + { + "api key inside the renewal window", + cliauth.Status{APIKey: true, OAuth: true, APIKeyExpiresAt: statusNow.Add(3 * 24 * time.Hour)}, + "API key expires soon", + }, + { + "api key with no recorded expiry", + cliauth.Status{APIKey: true, OAuth: true}, + "API key expiry is not recorded", + }, } for _, tc := range tests { @@ -49,6 +69,11 @@ func TestOverallStatusBadge(t *testing.T) { }{ {"both valid", cliauth.Status{APIKey: true, OAuth: true, OAuthExpiresAt: statusNow.Add(time.Hour)}, "authenticated"}, {"no known expiry counts valid", cliauth.Status{APIKey: true, OAuth: true}, "authenticated"}, + { + "api key expired", + cliauth.Status{APIKey: true, OAuth: true, APIKeyExpiresAt: statusNow.Add(-time.Hour)}, + "partially authenticated", + }, {"oauth expired", cliauth.Status{APIKey: true, OAuth: true, OAuthExpiresAt: statusNow.Add(-time.Hour)}, "partially authenticated"}, {"api key only", cliauth.Status{APIKey: true}, "partially authenticated"}, {"nothing", cliauth.Status{}, "not authenticated"}, @@ -63,18 +88,53 @@ func TestOverallStatusBadge(t *testing.T) { func TestStatusResultRenderTable(t *testing.T) { r := &statusResult{st: cliauth.Status{ - Profile: "default", - Tenant: "acme.safedep.io", - APIKey: true, - OAuth: true, + Profile: "default", + Tenant: "acme.safedep.io", + APIKey: true, + OAuth: true, + APIKeyExpiresAt: time.Now().Add(60 * 24 * time.Hour), }} out := r.RenderTable() assert.Contains(t, out, "Authentication") assert.Contains(t, out, "authenticated") assert.Contains(t, out, "acme.safedep.io") + assert.Contains(t, out, "API key expires") assert.NotContains(t, out, "auth login", "no hint when fully authenticated") } +// An expired API key with a valid OAuth token is the state that made pmg +// fail while status still read "authenticated". +func TestStatusResultRenderTableExpiredAPIKey(t *testing.T) { + r := &statusResult{st: cliauth.Status{ + Profile: "default", + Tenant: "acme.safedep.io", + APIKey: true, + OAuth: true, + OAuthExpiresAt: time.Now().Add(9 * time.Hour), + APIKeyExpiresAt: time.Now().Add(-48 * time.Hour), + }} + out := r.RenderTable() + assert.Contains(t, out, "partially authenticated") + assert.Contains(t, out, "API key expired") + assert.Contains(t, out, "safedep auth login") +} + +func TestStatusResultRenderJSONAPIKeyState(t *testing.T) { + expiresAt := time.Now().Add(-48 * time.Hour).UTC().Truncate(time.Second) + r := &statusResult{st: cliauth.Status{ + Profile: "default", + APIKey: true, + APIKeyExpiresAt: expiresAt, + }} + data, err := r.RenderJSON() + require.NoError(t, err) + + var got map[string]any + require.NoError(t, json.Unmarshal(data, &got)) + assert.Equal(t, "expired", got["api_key_state"]) + assert.Equal(t, expiresAt.Format(time.RFC3339), got["api_key_expires_at"]) +} + func TestStatusResultRenderTableExpiredOAuth(t *testing.T) { r := &statusResult{st: cliauth.Status{ Profile: "default", @@ -111,3 +171,11 @@ func TestStatusResultRenderPlainUnchangedShape(t *testing.T) { assert.Contains(t, plain, "OAuth expires: 2026-08-01T00:00:00Z") assert.NotContains(t, plain, "Status:", "plain output must not gain the table-only status row") } + +func TestStatusResultRenderPlainExpiredAPIKey(t *testing.T) { + expiresAt := time.Now().Add(-48 * time.Hour).UTC().Truncate(time.Second) + r := &statusResult{st: cliauth.Status{Profile: "default", APIKey: true, APIKeyExpiresAt: expiresAt}} + plain := r.RenderPlain() + assert.Contains(t, plain, "API key state: expired") + assert.Contains(t, plain, "Key expires: "+expiresAt.Format(time.RFC3339)) +} diff --git a/internal/cmd/packages/packages_test.go b/internal/cmd/packages/packages_test.go index 4a6aed7..6c2fffb 100644 --- a/internal/cmd/packages/packages_test.go +++ b/internal/cmd/packages/packages_test.go @@ -141,16 +141,16 @@ func TestResolveTarget(t *testing.T) { wantN: "publisher.ext", wantV: "1.2.3", }, { - name: "purl github branch pinned to commit", + name: "purl github repository branch pinned to commit", ref: "pkg:github/safedep/vet@main", resolver: &fakeResolver{sha: testSHA}, - wantEco: packagev1.Ecosystem_ECOSYSTEM_GITHUB_ACTIONS, + wantEco: packagev1.Ecosystem_ECOSYSTEM_GITHUB_REPOSITORY, wantN: "safedep/vet", wantV: testSHA, wantCalls: 1, wantOwner: "safedep", wantRepo: "vet", wantRef: "main", }, { name: "purl github actions subpath uses the repository", - ref: "pkg:github/aws-actions/configure-aws-credentials/assume-role@v2", + ref: "pkg:githubactions/aws-actions/configure-aws-credentials/assume-role@v2", resolver: &fakeResolver{sha: testSHA}, wantEco: packagev1.Ecosystem_ECOSYSTEM_GITHUB_ACTIONS, wantN: "aws-actions/configure-aws-credentials/assume-role", wantV: testSHA, @@ -159,7 +159,7 @@ func TestResolveTarget(t *testing.T) { { name: "purl github commit passes through without a lookup", ref: "pkg:github/safedep/vet@" + testSHA, - wantEco: packagev1.Ecosystem_ECOSYSTEM_GITHUB_ACTIONS, + wantEco: packagev1.Ecosystem_ECOSYSTEM_GITHUB_REPOSITORY, wantN: "safedep/vet", wantV: testSHA, }, { diff --git a/internal/cmd/policy/decision_test.go b/internal/cmd/policy/decision_test.go index 31dd0d0..6c9835c 100644 --- a/internal/cmd/policy/decision_test.go +++ b/internal/cmd/policy/decision_test.go @@ -298,7 +298,8 @@ func TestParseDecisionPackage(t *testing.T) { {purl: "pkg:gem/Rails", ecosystem: packagev1.Ecosystem_ECOSYSTEM_RUBYGEMS, name: "Rails"}, {purl: "pkg:cargo/serde", ecosystem: packagev1.Ecosystem_ECOSYSTEM_CARGO, name: "serde"}, {purl: "pkg:nuget/Newtonsoft.Json", ecosystem: packagev1.Ecosystem_ECOSYSTEM_NUGET, name: "Newtonsoft.Json"}, - {purl: "pkg:github/actions/checkout", ecosystem: packagev1.Ecosystem_ECOSYSTEM_GITHUB_ACTIONS, name: "actions/checkout"}, + {purl: "pkg:githubactions/actions/checkout", ecosystem: packagev1.Ecosystem_ECOSYSTEM_GITHUB_ACTIONS, name: "actions/checkout"}, + {purl: "pkg:github/safedep/vet", ecosystem: packagev1.Ecosystem_ECOSYSTEM_GITHUB_REPOSITORY, name: "safedep/vet"}, {purl: "pkg:npm/lodash@4.17.21", wantErr: "has a version"}, {purl: "pkg:npm/%40acme/ui@1.0.0", wantErr: "has a version"}, {purl: "pkg:npm/@acme/ui@1.0.0", wantErr: "has a version"},