From 8c99db13ed83abdd6e7bcc94bd1beb3db6bfa896 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 08:46:24 +0000 Subject: [PATCH 01/11] fix(auth): replace an expired API key on login and show its expiry in status safedep auth login kept any API key that the keychain held, with no check of its expiry and no visible message, and the CLI did not record the expiry. After the 90 days of the first key, login renewed only the OAuth tokens, auth status still read "authenticated", and pmg sent the expired key. Login now keeps the stored key only when it belongs to the picked tenant, its recorded expiry is more than 14 days away, and SafeDep Cloud accepts it. Otherwise it creates a new key and says why. The decision runs after the tenant pick, and reads the keychain key, which pmg and vet use. A network failure keeps the key and prints a warning. Login does not revoke the old key, so a tool that holds a copy keeps working until the key expires. The key is saved with its id and expiry (dry APIKeyMetadataStore). A key saved by an earlier CLI has no recorded expiry, so the first login replaces it once. auth status shows the API key expiry and a state: valid, expiring, expired, expiry_unknown or missing. An expired key no longer counts as authenticated. The JSON output adds api_key_state and api_key_expires_at. dry moves to the commit that adds the API key metadata. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- docs/cmd/auth-login.md | 22 +++- docs/cmd/auth-status.md | 16 ++- go.mod | 2 +- go.sum | 4 +- internal/auth/apikey_renew.go | 112 +++++++++++++++++++++ internal/auth/apikey_renew_test.go | 155 +++++++++++++++++++++++++++++ internal/auth/bootstrap.go | 35 +++++-- internal/auth/bootstrap_test.go | 83 +++++++++++++++ internal/auth/save.go | 24 ++++- internal/auth/status.go | 12 +++ internal/cmd/auth/login.go | 73 +++++++++----- internal/cmd/auth/status.go | 87 ++++++++++++---- internal/cmd/auth/status_test.go | 70 ++++++++++++- 13 files changed, 624 insertions(+), 71 deletions(-) create mode 100644 internal/auth/apikey_renew.go create mode 100644 internal/auth/apikey_renew_test.go diff --git a/docs/cmd/auth-login.md b/docs/cmd/auth-login.md index fad8844..3c3642f 100644 --- a/docs/cmd/auth-login.md +++ b/docs/cmd/auth-login.md @@ -2,7 +2,23 @@ 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 saved by an earlier CLI has no recorded expiry, so the first login replaces it once. + +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. Delete it in app.safedep.io to revoke it at once. + +When SafeDep Cloud cannot be reached, login keeps the stored key and prints a warning. + +pmg and vet read the API key from the keychain. Login checks the keychain key, not `SAFEDEP_API_KEY`. ## Synopsis @@ -20,7 +36,7 @@ safedep auth login --api-key [--api-key-value | --from-stdin] [--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. | +| `--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 +51,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..41ad070 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. | +| `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}`. | +| `json` | `{profile, tenant, api_key_present, api_key_state, api_key_expires_at, oauth_token_present, oauth_expires_at}`. | ## Exit codes diff --git a/go.mod b/go.mod index 476625e..fb3d6ba 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-20261122111234-f738a7fee092 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..41c5225 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-20261122111234-f738a7fee092 h1:MPSeDSDoSUh856SCnYNxMx1hWXKP7nMJsqseiH1tZwQ= +github.com/safedep/dry v0.0.0-20261122111234-f738a7fee092/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/auth/apikey_renew.go b/internal/auth/apikey_renew.go new file mode 100644 index 0000000..d42a16e --- /dev/null +++ b/internal/auth/apikey_renew.go @@ -0,0 +1,112 @@ +package auth + +import ( + "context" + "fmt" + "time" + + "github.com/safedep/dry/cloud" + "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 +} + +// 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 +// outside APIKeyRenewWindow, and SafeDep Cloud accepts it. A key with no +// recorded expiry is replaced once, so that its expiry gets recorded. +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)} + } + + expiresAt, _ := stored.APIKeyExpiresAt() + switch APIKeyStateAt(true, expiresAt, now) { + case APIKeyExpired: + return APIKeyDecision{Reason: "the stored API key expired on " + formatDay(expiresAt)} + case APIKeyExpiring: + return APIKeyDecision{Reason: "the stored API key expires on " + formatDay(expiresAt)} + case APIKeyExpiryUnknown: + return APIKeyDecision{Reason: "the expiry of the stored API key is not recorded"} + } + + key, err := stored.GetAPIKey() + if err != nil { + return APIKeyDecision{Reason: "the stored API key cannot be read"} + } + + if err := verify(ctx, APIKeyInput{APIKey: key, Tenant: tenant}); err != nil { + if code := status.Code(err); code == codes.Unauthenticated || code == codes.PermissionDenied { + return APIKeyDecision{Reason: "SafeDep Cloud rejected the stored API key"} + } + return APIKeyDecision{Keep: true, ExpiresAt: expiresAt, + Warning: fmt.Sprintf("could not verify the stored API key: %v", err)} + } + + return APIKeyDecision{Keep: true, ExpiresAt: expiresAt} +} + +func formatDay(t time.Time) string { + return t.UTC().Format("2006-01-02") +} diff --git a/internal/auth/apikey_renew_test.go b/internal/auth/apikey_renew_test.go new file mode 100644 index 0000000..a7abbc9 --- /dev/null +++ b/internal/auth/apikey_renew_test.go @@ -0,0 +1,155 @@ +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 + }{ + { + 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"`, + }, + { + 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", + 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", + }, + { + name: "a key with no recorded expiry", + 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", + }, + { + 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) + 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 { + assert.True(t, valid.ExpiresAt.Equal(got.ExpiresAt)) + } + }) + } +} diff --git a/internal/auth/bootstrap.go b/internal/auth/bootstrap.go index ea7d931..574e5fb 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,11 @@ 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 } // PostOAuthBootstrap completes the work that follows a successful device @@ -90,12 +99,20 @@ 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 { return nil, err } - res.APIKey = key - res.APIKeyExpiresAt = expiresAt + res.APIKey = key.GetKey() + res.APIKeyID = key.GetKeyId() + res.APIKeyExpiresAt = key.GetExpiresAt().AsTime() return res, nil } @@ -143,14 +160,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 +181,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..f511414 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" @@ -14,6 +15,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/types/known/timestamppb" ) // fakeUserServer is a configurable UserServiceServer that returns a @@ -49,6 +51,24 @@ 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 +} + +func (f *fakeAPIKeyServer) CreateApiKey(_ context.Context, req *controltowerv1.CreateApiKeyRequest, +) (*controltowerv1.CreateApiKeyResponse, error) { + f.creates++ + return &controltowerv1.CreateApiKeyResponse{ + Key: "sk-new", + KeyId: "key-new", + ExpiresAt: timestamppb.New(f.expiresAt), + }, nil } func newBootstrapTestServer(t *testing.T, bts bootstrapTestServer) ControlPlaneConnFunc { @@ -57,6 +77,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 +199,63 @@ 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 + 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", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + apiKeys := &fakeAPIKeyServer{expiresAt: expiresAt} + 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, expiresAt.Equal(res.APIKeyExpiresAt)) + } + }) + } +} diff --git a/internal/auth/save.go b/internal/auth/save.go index 98feed3..1362b56 100644 --- a/internal/auth/save.go +++ b/internal/auth/save.go @@ -7,16 +7,30 @@ 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. A store that cannot hold metadata gets the key +// alone. 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 + } + + var err error + if metaStore, ok := store.(cloud.APIKeyMetadataStore); ok { + err = metaStore.SaveAPIKeyCredentialWithMetadata(b.APIKey, b.Tenant, cloud.APIKeyMetadata{ + KeyID: b.APIKeyID, + ExpiresAt: b.APIKeyExpiresAt, + }) + } else { + err = store.SaveAPIKeyCredential(b.APIKey, b.Tenant) + } + if err != nil { + return fmt.Errorf("save api key credential: %w", err) } return nil 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..f27ae37 100644 --- a/internal/cmd/auth/login.go +++ b/internal/cmd/auth/login.go @@ -1,6 +1,7 @@ package auth import ( + "context" "errors" "fmt" "io" @@ -104,7 +105,15 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { } } - createKey, name := apiKeyCreationPlan(a, preferredTenant, flags) + createKey := !flags.noAPIKey + var name string + var decideAPIKey func(context.Context, string) cliauth.APIKeyDecision + if createKey { + name = cliauth.APIKeyName(cliauth.Hostname(), time.Now()) + if !flags.rotateAPIKey { + decideAPIKey = storedAPIKeyDecider(a) + } + } var registrationPrompter func() (*cliauth.RegistrationInput, error) if flags.noAPIKey { @@ -121,6 +130,7 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { CreateAPIKey: createKey, APIKeyName: name, APIKeyExpiryDays: flags.apiKeyExpiryDays, + DecideAPIKey: decideAPIKey, Picker: cliauth.PromptTenantPicker, RegistrationPrompter: registrationPrompter, }) @@ -137,10 +147,21 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { return err } + decision := bootstrap.APIKeyDecision + if decision.Warning != "" { + tui.Warning("%s", decision.Warning) + } + switch { case bootstrap.APIKey != "": + if decision.Reason != "" { + tui.Info("Created a new API key: %s.", decision.Reason) + } tui.Success("Authenticated as %s (profile %q). API key created, expires %s.", bootstrap.Tenant, a.Profile(), bootstrap.APIKeyExpiresAt.UTC().Format("2006-01-02")) + case decision.Keep: + tui.Success("Authenticated as %s (profile %q). Kept the stored API key, expires %s.", + bootstrap.Tenant, a.Profile(), decision.ExpiresAt.UTC().Format("2006-01-02")) case createKey: tui.Success("Authenticated as %s (profile %q). API key creation skipped — none in response.", bootstrap.Tenant, a.Profile()) default: @@ -150,39 +171,39 @@ 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) { - if flags.noAPIKey { - return false, "" +// storedAPIKeyDecider returns the check that decides, once the tenant is +// picked, whether login keeps the API key of the profile. 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 storedAPIKeyDecider(a *app.App) func(context.Context, string) cliauth.APIKeyDecision { + return func(ctx context.Context, tenant string) cliauth.APIKeyDecision { + return cliauth.DecideStoredAPIKey(ctx, storedAPIKey(a), tenant, time.Now(), cliauth.VerifyAPIKey) } - 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, "" - } - return true, cliauth.APIKeyName(cliauth.Hostname(), time.Now()) } -func hasAPIKeyForTenant(a *app.App, tenant string) bool { - if tenant == "" { - return false - } - resolver, err := a.APIKeyResolver() +// storedAPIKey returns the API key credentials of the profile in the +// keychain, or nil when there are none. A keychain that cannot be read counts +// as no key, so login creates one. +func storedAPIKey(a *app.App) *cloud.Credentials { + resolver, err := cloud.NewKeychainCredentialResolver(cloud.CredentialTypeAPIKey, a.KeychainOptions()...) if err != nil { - log.Warnf("auth login: api-key check: %v", err) - return false + log.Warnf("auth login: stored api key: %v", err) + return nil } + defer func() { + if err := resolver.Close(); err != nil { + log.Warnf("auth login: close keychain resolver: %v", err) + } + }() + creds, err := resolver.Resolve() if err != nil { - return false - } - got, err := creds.GetTenantDomain() - if err != nil { - return false + if !errors.Is(err, cloud.ErrMissingCredentials) { + log.Warnf("auth login: stored api key: %v", err) + } + return nil } - return got == tenant + return creds } func resolveAPIKey(flags loginFlags) (string, error) { diff --git a/internal/cmd/auth/status.go b/internal/cmd/auth/status.go index 381a7f6..48f7b97 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,9 @@ 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.APIKeyExpiresAt.IsZero() { + fmt.Fprintf(&sb, "API 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 +89,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 +104,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 +133,66 @@ 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. Run 'safedep auth login' to renew the key and record it." } 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..78a1a99 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", From ad0be218d6df5c87edd4076c862734b7671b12dd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 08:56:03 +0000 Subject: [PATCH 02/11] fix(packages): read pkg:github as a repository and pkg:githubactions as an Action The dry that the API key change needs maps pkg:github to a GitHub repository and pkg:githubactions to a GitHub Action (dry #172). The CLI is the last step of that rollout: Control Tower and malysis already read the new types. - safedep package scan run pkg:github/owner/repo@ref scans the repository. An Action takes pkg:githubactions/owner/repo@ref. - safedep policy decision list --package pkg:github/... matches the repository. An Action takes pkg:githubactions/.... - The docs say so, and the tests use the new types. The bootstrap also stores no expiry when CreateApiKey returns none. AsTime on a missing timestamp returns 1970-01-01, and the next login would replace a valid key. dry moves to the commit that binds the API key fields to the key with a fingerprint. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- docs/cmd/package-scan-run.md | 7 ++++--- docs/cmd/policy-decision-list.md | 4 ++++ go.mod | 2 +- go.sum | 4 ++-- internal/auth/bootstrap.go | 6 +++++- internal/auth/bootstrap_test.go | 26 ++++++++++++++++++++------ internal/cmd/packages/packages_test.go | 8 ++++---- internal/cmd/policy/decision_test.go | 3 ++- 8 files changed, 42 insertions(+), 18 deletions(-) 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 fb3d6ba..f5b2145 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-20261122111234-f738a7fee092 + github.com/safedep/dry v0.0.0-20261123085248-82c849ed3cea 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 41c5225..eff48b2 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-20261122111234-f738a7fee092 h1:MPSeDSDoSUh856SCnYNxMx1hWXKP7nMJsqseiH1tZwQ= -github.com/safedep/dry v0.0.0-20261122111234-f738a7fee092/go.mod h1:DHtiOuwrtW3gzmMEMfX74Cs/MjclA2eAqdCON5uoKA0= +github.com/safedep/dry v0.0.0-20261123085248-82c849ed3cea h1:pFp68QhwzIRKP3//IfUaI0mzDnp177sxsuEscErh+aE= +github.com/safedep/dry v0.0.0-20261123085248-82c849ed3cea/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/auth/bootstrap.go b/internal/auth/bootstrap.go index 574e5fb..db33c8d 100644 --- a/internal/auth/bootstrap.go +++ b/internal/auth/bootstrap.go @@ -112,7 +112,11 @@ func PostOAuthBootstrap(ctx context.Context, in BootstrapInput) (*BootstrapResul } res.APIKey = key.GetKey() res.APIKeyID = key.GetKeyId() - res.APIKeyExpiresAt = key.GetExpiresAt().AsTime() + // 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 } diff --git a/internal/auth/bootstrap_test.go b/internal/auth/bootstrap_test.go index f511414..07808a3 100644 --- a/internal/auth/bootstrap_test.go +++ b/internal/auth/bootstrap_test.go @@ -64,11 +64,11 @@ type fakeAPIKeyServer struct { func (f *fakeAPIKeyServer) CreateApiKey(_ context.Context, req *controltowerv1.CreateApiKeyRequest, ) (*controltowerv1.CreateApiKeyResponse, error) { f.creates++ - return &controltowerv1.CreateApiKeyResponse{ - Key: "sk-new", - KeyId: "key-new", - ExpiresAt: timestamppb.New(f.expiresAt), - }, nil + 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 { @@ -208,6 +208,7 @@ func TestPostOAuthBootstrap_DecideAPIKey(t *testing.T) { tests := []struct { name string decision APIKeyDecision + noExpiry bool wantCreates int wantKey string }{ @@ -222,11 +223,23 @@ func TestPostOAuthBootstrap_DecideAPIKey(t *testing.T) { 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{}, @@ -254,7 +267,8 @@ func TestPostOAuthBootstrap_DecideAPIKey(t *testing.T) { assert.Equal(t, tc.wantKey, res.APIKey) if tc.wantKey != "" { assert.Equal(t, "key-new", res.APIKeyID) - assert.True(t, expiresAt.Equal(res.APIKeyExpiresAt)) + assert.True(t, apiKeys.expiresAt.Equal(res.APIKeyExpiresAt), + "expiry %v, want %v", res.APIKeyExpiresAt, apiKeys.expiresAt) } }) } 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"}, From 63afe2cf1f47c7fcae05d29e7adb09cc77f51cd1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:07:37 +0000 Subject: [PATCH 03/11] fix(auth): keep a working key when login cannot replace it, and test the login wiring - A key with no recorded expiry, such as a key saved with --api-key, stays when SafeDep Cloud accepts it. Login no longer replaces it without a check, and auth status no longer tells the user to log in again for it. An expired key still fails the check and is replaced. - When CreateApiKey fails and the stored key still works for the tenant, login keeps the key, saves the OAuth tokens and warns. A user who cannot create keys could otherwise not log in. - Login opens the keychain before the browser flow, so a machine with no usable keychain fails before SafeDep Cloud creates a key. - --api-key-expiry-days must be more than 14. Login replaces a key that expires within 14 days, so a shorter lifetime replaced the key on every login. - A keychain that cannot be read gives its own reason. A key with no reported expiry prints "expiry not recorded". - auth status --output plain shows the API key state, and its rows align. - Tests cover the login plan, the keychain read with an API key in the environment, auth status reading the expiry, the create fallback and plain output for an expired key. - DEVGUIDE lists the agent-mode variables that dry/tui reads. dry moves to the commit that keeps the tenant and the metadata of API keys in one bindings field. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- docs/DEVGUIDE.md | 2 +- docs/cmd/auth-login.md | 12 ++-- docs/cmd/auth-status.md | 4 +- go.mod | 2 +- go.sum | 4 +- internal/auth/apikey_renew.go | 19 ++++-- internal/auth/apikey_renew_test.go | 45 +++++++++++-- internal/auth/bootstrap.go | 10 +++ internal/auth/bootstrap_test.go | 56 ++++++++++++++++ internal/cmd/auth/login.go | 100 ++++++++++++++++++++--------- internal/cmd/auth/login_test.go | 76 ++++++++++++++++++++++ internal/cmd/auth/status.go | 8 ++- internal/cmd/auth/status_test.go | 10 ++- 13 files changed, 292 insertions(+), 56 deletions(-) create mode 100644 internal/cmd/auth/login_test.go 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 3c3642f..e4ec069 100644 --- a/docs/cmd/auth-login.md +++ b/docs/cmd/auth-login.md @@ -9,14 +9,16 @@ By default, runs the OAuth2 device-code flow in the browser, picks an accessible 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. +2. It does not expire within 14 days. 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 saved by an earlier CLI has no recorded expiry, so the first login replaces it once. +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. -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. Delete it in app.safedep.io to revoke it at once. +A key with no recorded expiry, such as a key saved with `--api-key` or by an earlier CLI, stays when SafeDep Cloud accepts it. Pass `--rotate-api-key` to replace it with a key whose expiry is recorded. -When SafeDep Cloud cannot be reached, login keeps the stored key and prints a warning. +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, and when it cannot create a new key while the stored key still works, for example for a user who cannot create keys. pmg and vet read the API key from the keychain. Login checks the keychain key, not `SAFEDEP_API_KEY`. @@ -35,7 +37,7 @@ 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). | +| `--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. | | `--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. | diff --git a/docs/cmd/auth-status.md b/docs/cmd/auth-status.md index 41ad070..79b228e 100644 --- a/docs/cmd/auth-status.md +++ b/docs/cmd/auth-status.md @@ -19,7 +19,7 @@ The API key has one of these states: | `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. | +| `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 --rotate-api-key` replaces it with a key whose expiry is recorded. | | `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. @@ -27,7 +27,7 @@ The overall status is `authenticated` only when the OAuth token is valid and the | Mode | Format | |---|---| | `table` | Tabular block with badges for each credential. | -| `plain` | `key: value` lines. | +| `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/go.mod b/go.mod index f5b2145..4a23c2d 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-20261123085248-82c849ed3cea + github.com/safedep/dry v0.0.0-20261123090304-8e573bccdfd2 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 eff48b2..6822cb5 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-20261123085248-82c849ed3cea h1:pFp68QhwzIRKP3//IfUaI0mzDnp177sxsuEscErh+aE= -github.com/safedep/dry v0.0.0-20261123085248-82c849ed3cea/go.mod h1:DHtiOuwrtW3gzmMEMfX74Cs/MjclA2eAqdCON5uoKA0= +github.com/safedep/dry v0.0.0-20261123090304-8e573bccdfd2 h1:MqIARvB87AFgOL2zr4bvHB1YJPhB2+sIJ5uy7idMDuU= +github.com/safedep/dry v0.0.0-20261123090304-8e573bccdfd2/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/auth/apikey_renew.go b/internal/auth/apikey_renew.go index d42a16e..8282f2a 100644 --- a/internal/auth/apikey_renew.go +++ b/internal/auth/apikey_renew.go @@ -62,13 +62,18 @@ type APIKeyDecision struct { // Warning reports a check that could not finish. Login keeps the key, // because a network failure says nothing about the key. Warning string + + // Fallback means that the stored key still works for the tenant, so + // login keeps it when it cannot create a new key. ExpiresAt is set. + 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 -// outside APIKeyRenewWindow, and SafeDep Cloud accepts it. A key with no -// recorded expiry is replaced once, so that its expiry gets recorded. +// key. The key stays only when it belongs to tenant, it does not expire +// within APIKeyRenewWindow, and SafeDep Cloud accepts it. A key with no +// recorded expiry, such as a pasted key, stays when SafeDep Cloud accepts it: +// an expired key fails that check. func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant string, now time.Time, verify APIKeyVerifier, ) APIKeyDecision { @@ -86,9 +91,8 @@ func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant s case APIKeyExpired: return APIKeyDecision{Reason: "the stored API key expired on " + formatDay(expiresAt)} case APIKeyExpiring: - return APIKeyDecision{Reason: "the stored API key expires on " + formatDay(expiresAt)} - case APIKeyExpiryUnknown: - return APIKeyDecision{Reason: "the expiry of the stored API key is not recorded"} + return APIKeyDecision{Reason: "the stored API key expires on " + formatDay(expiresAt), + Fallback: true, ExpiresAt: expiresAt} } key, err := stored.GetAPIKey() @@ -97,6 +101,9 @@ func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant s } 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"} } diff --git a/internal/auth/apikey_renew_test.go b/internal/auth/apikey_renew_test.go index a7abbc9..29ed64f 100644 --- a/internal/auth/apikey_renew_test.go +++ b/internal/auth/apikey_renew_test.go @@ -51,6 +51,7 @@ func TestDecideStoredAPIKey(t *testing.T) { wantReason string wantVerified bool wantWarning bool + wantFallback bool }{ { name: "no stored key", @@ -78,14 +79,25 @@ func TestDecideStoredAPIKey(t *testing.T) { 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", + wantReason: "expires on 2026-11-25", + wantFallback: true, }, { - name: "a key with no recorded expiry", + 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", + wantKeep: 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 valid key that SafeDep Cloud accepts", @@ -142,14 +154,39 @@ func TestDecideStoredAPIKey(t *testing.T) { 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) 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 { - assert.True(t, valid.ExpiresAt.Equal(got.ExpiresAt)) + 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) +} diff --git a/internal/auth/bootstrap.go b/internal/auth/bootstrap.go index db33c8d..7e991a9 100644 --- a/internal/auth/bootstrap.go +++ b/internal/auth/bootstrap.go @@ -107,6 +107,16 @@ func PostOAuthBootstrap(ctx context.Context, in BootstrapInput) (*BootstrapResul } key, err := createAPIKey(ctx, in.ConnFor, in.AccessToken, tenant, in.APIKeyName, in.APIKeyExpiryDays) + if err != nil && res.APIKeyDecision.Fallback { + // The stored key still works, so a failed create must not cost the + // user the OAuth tokens of this login. A Viewer cannot create keys. + res.APIKeyDecision = APIKeyDecision{ + Keep: true, + ExpiresAt: res.APIKeyDecision.ExpiresAt, + Warning: fmt.Sprintf("could not create a new API key, so the stored key stays: %v", err), + } + return res, nil + } if err != nil { return nil, err } diff --git a/internal/auth/bootstrap_test.go b/internal/auth/bootstrap_test.go index 07808a3..86a5def 100644 --- a/internal/auth/bootstrap_test.go +++ b/internal/auth/bootstrap_test.go @@ -13,7 +13,9 @@ 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" ) @@ -59,11 +61,15 @@ 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) @@ -273,3 +279,53 @@ func TestPostOAuthBootstrap_DecideAPIKey(t *testing.T) { }) } } + +// 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.Date(2026, 11, 30, 0, 0, 0, 0, time.UTC) + + tests := []struct { + name string + decision APIKeyDecision + wantErr bool + }{ + { + name: "a stored key that still works is kept", + decision: APIKeyDecision{Reason: "the stored API key expires on 2026-11-30", Fallback: true, ExpiresAt: expiresAt}, + }, + { + name: "no usable stored key fails the login", + decision: APIKeyDecision{Reason: "the stored API key expired on 2026-11-20"}, + 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: func(context.Context, string) APIKeyDecision { return tc.decision }, + ConnFor: connFor, + }) + + if tc.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + assert.True(t, res.APIKeyDecision.Keep) + assert.True(t, expiresAt.Equal(res.APIKeyDecision.ExpiresAt)) + assert.Contains(t, res.APIKeyDecision.Warning, "could not create a new API key") + assert.Empty(t, res.APIKey) + }) + } +} diff --git a/internal/cmd/auth/login.go b/internal/cmd/auth/login.go index f27ae37..a793c8a 100644 --- a/internal/cmd/auth/login.go +++ b/internal/cmd/auth/login.go @@ -89,6 +89,18 @@ func runAPIKeyLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { } func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) 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 := a.CredentialStore() + if err != nil { + return err + } + tui.Info("Starting OAuth2 device login…") res, err := cliauth.RunDeviceFlow(cmd.Context(), cliauth.PrintVerification, @@ -105,14 +117,10 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { } } - createKey := !flags.noAPIKey + createKey, decideAPIKey := apiKeyPlan(flags, a.KeychainOptions()) var name string - var decideAPIKey func(context.Context, string) cliauth.APIKeyDecision if createKey { name = cliauth.APIKeyName(cliauth.Hostname(), time.Now()) - if !flags.rotateAPIKey { - decideAPIKey = storedAPIKeyDecider(a) - } } var registrationPrompter func() (*cliauth.RegistrationInput, error) @@ -138,11 +146,6 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { return err } - store, err := a.CredentialStore() - if err != nil { - return err - } - if err := cliauth.SaveBootstrapResult(store, res.AccessToken, res.RefreshToken, bootstrap); err != nil { return err } @@ -157,11 +160,11 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { if decision.Reason != "" { tui.Info("Created a new API key: %s.", decision.Reason) } - tui.Success("Authenticated as %s (profile %q). API key created, expires %s.", - bootstrap.Tenant, a.Profile(), bootstrap.APIKeyExpiresAt.UTC().Format("2006-01-02")) + 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, expires %s.", - bootstrap.Tenant, a.Profile(), decision.ExpiresAt.UTC().Format("2006-01-02")) + 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: @@ -171,24 +174,49 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { return nil } -// storedAPIKeyDecider returns the check that decides, once the tenant is -// picked, whether login keeps the API key of the profile. 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 storedAPIKeyDecider(a *app.App) func(context.Context, string) cliauth.APIKeyDecision { - return func(ctx context.Context, tenant string) cliauth.APIKeyDecision { - return cliauth.DecideStoredAPIKey(ctx, storedAPIKey(a), tenant, time.Now(), cliauth.VerifyAPIKey) +// validateAPIKeyExpiryDays 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. +func validateAPIKeyExpiryDays(flags loginFlags) error { + if flags.noAPIKey { + return nil + } + 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 +} + +// 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, opts []cloud.KeychainOption, +) (bool, func(context.Context, string) cliauth.APIKeyDecision) { + if flags.noAPIKey { + return false, nil + } + if flags.rotateAPIKey { + return true, nil + } + return true, func(ctx context.Context, tenant string) cliauth.APIKeyDecision { + stored, err := storedAPIKey(opts) + 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(), cliauth.VerifyAPIKey) } } // storedAPIKey returns the API key credentials of the profile in the -// keychain, or nil when there are none. A keychain that cannot be read counts -// as no key, so login creates one. -func storedAPIKey(a *app.App) *cloud.Credentials { - resolver, err := cloud.NewKeychainCredentialResolver(cloud.CredentialTypeAPIKey, a.KeychainOptions()...) +// 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 { - log.Warnf("auth login: stored api key: %v", err) - return nil + return nil, err } defer func() { if err := resolver.Close(); err != nil { @@ -197,13 +225,21 @@ func storedAPIKey(a *app.App) *cloud.Credentials { }() creds, err := resolver.Resolve() + if errors.Is(err, cloud.ErrMissingCredentials) && !errors.Is(err, cloud.ErrIncompleteCredentials) { + return nil, nil + } if err != nil { - if !errors.Is(err, cloud.ErrMissingCredentials) { - log.Warnf("auth login: stored api key: %v", err) - } - return nil + return nil, err + } + return creds, nil +} + +// 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 creds + 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..307b8e3 --- /dev/null +++ b/internal/cmd/auth/login_test.go @@ -0,0 +1,76 @@ +package auth + +import ( + "testing" + "time" + + "github.com/safedep/dry/cloud" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +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) + assert.Equal(t, tc.wantCreate, create) + assert.Equal(t, tc.wantDecider, decide != nil) + }) + } +} + +// 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.(cloud.APIKeyMetadataStore).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) +} + +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})) +} diff --git a/internal/cmd/auth/status.go b/internal/cmd/auth/status.go index 48f7b97..c5d96d3 100644 --- a/internal/cmd/auth/status.go +++ b/internal/cmd/auth/status.go @@ -69,8 +69,11 @@ 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, "API key expires: %s\n", r.st.APIKeyExpiresAt.UTC().Format(time.RFC3339)) + 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() { @@ -144,7 +147,8 @@ func nextStepHint(st cliauth.Status, now time.Time) string { 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. Run 'safedep auth login' to renew the key and record it." + return "API key expiry is not recorded, so status cannot tell whether the key has expired. " + + "Run 'safedep auth login --rotate-api-key' to replace it with a key whose expiry is recorded." } return "" } diff --git a/internal/cmd/auth/status_test.go b/internal/cmd/auth/status_test.go index 78a1a99..49610b0 100644 --- a/internal/cmd/auth/status_test.go +++ b/internal/cmd/auth/status_test.go @@ -45,7 +45,7 @@ func TestNextStepHint(t *testing.T) { { "api key with no recorded expiry", cliauth.Status{APIKey: true, OAuth: true}, - "API key expiry is not recorded", + "--rotate-api-key", }, } @@ -171,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)) +} From 20d50ba2f42c978a6c0194697dfe11f9cbdf08a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:11:15 +0000 Subject: [PATCH 04/11] refactor(auth): read the stored API key in internal/auth, not in the command docs/DEVGUIDE.md allows no direct keychain read from command code. The keychain-only read that login uses to decide on the stored key moves to internal/auth as StoredAPIKey, next to BuildStatus, which reads the keychain the same way. The command passes the keychain options of App. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- internal/auth/apikey_renew.go | 27 +++++++++++++++++++ internal/auth/apikey_renew_test.go | 39 +++++++++++++++++++++++++++ internal/cmd/auth/login.go | 27 +------------------ internal/cmd/auth/login_test.go | 42 ------------------------------ 4 files changed, 67 insertions(+), 68 deletions(-) diff --git a/internal/auth/apikey_renew.go b/internal/auth/apikey_renew.go index 8282f2a..0d0e734 100644 --- a/internal/auth/apikey_renew.go +++ b/internal/auth/apikey_renew.go @@ -2,10 +2,12 @@ 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" ) @@ -117,3 +119,28 @@ func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant s 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 index 29ed64f..25cc06e 100644 --- a/internal/auth/apikey_renew_test.go +++ b/internal/auth/apikey_renew_test.go @@ -190,3 +190,42 @@ func TestBuildStatusReadsAPIKeyExpiry(t *testing.T) { 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.(cloud.APIKeyMetadataStore).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/cmd/auth/login.go b/internal/cmd/auth/login.go index a793c8a..8d32839 100644 --- a/internal/cmd/auth/login.go +++ b/internal/cmd/auth/login.go @@ -201,7 +201,7 @@ func apiKeyPlan(flags loginFlags, opts []cloud.KeychainOption, return true, nil } return true, func(ctx context.Context, tenant string) cliauth.APIKeyDecision { - stored, err := storedAPIKey(opts) + stored, err := cliauth.StoredAPIKey(opts) if err != nil { return cliauth.APIKeyDecision{Reason: fmt.Sprintf("the stored API key cannot be read: %v", err)} } @@ -209,31 +209,6 @@ func apiKeyPlan(flags loginFlags, opts []cloud.KeychainOption, } } -// 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 login: 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 -} - // expiryPhrase reports the expiry of a key for the login message. func expiryPhrase(expiresAt time.Time) string { if expiresAt.IsZero() { diff --git a/internal/cmd/auth/login_test.go b/internal/cmd/auth/login_test.go index 307b8e3..01b02b5 100644 --- a/internal/cmd/auth/login_test.go +++ b/internal/cmd/auth/login_test.go @@ -2,11 +2,8 @@ package auth import ( "testing" - "time" - "github.com/safedep/dry/cloud" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestAPIKeyPlan(t *testing.T) { @@ -30,45 +27,6 @@ func TestAPIKeyPlan(t *testing.T) { } } -// 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.(cloud.APIKeyMetadataStore).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) -} - func TestValidateAPIKeyExpiryDays(t *testing.T) { assert.Error(t, validateAPIKeyExpiryDays(loginFlags{apiKeyExpiryDays: 14})) assert.NoError(t, validateAPIKeyExpiryDays(loginFlags{apiKeyExpiryDays: 15})) From 60438d5e081ca55e821834756651bedb574ddd63 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:17:24 +0000 Subject: [PATCH 05/11] fix(auth): check a key inside the renewal window before it can be the fallback A key that expires within 14 days became the fallback without a Ping. When login then could not create a new key, it kept that key and reported success, even if SafeDep Cloud had revoked it. The key inside the window now gets the same Ping as a valid key. A rejected key is replaced with no fallback. An accepted key is replaced, and stays the fallback when the create fails. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- internal/auth/apikey_renew.go | 20 ++++++++++++-------- internal/auth/apikey_renew_test.go | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/internal/auth/apikey_renew.go b/internal/auth/apikey_renew.go index 0d0e734..ea73b07 100644 --- a/internal/auth/apikey_renew.go +++ b/internal/auth/apikey_renew.go @@ -89,12 +89,9 @@ func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant s } expiresAt, _ := stored.APIKeyExpiresAt() - switch APIKeyStateAt(true, expiresAt, now) { - case APIKeyExpired: + state := APIKeyStateAt(true, expiresAt, now) + if state == APIKeyExpired { return APIKeyDecision{Reason: "the stored API key expired on " + formatDay(expiresAt)} - case APIKeyExpiring: - return APIKeyDecision{Reason: "the stored API key expires on " + formatDay(expiresAt), - Fallback: true, ExpiresAt: expiresAt} } key, err := stored.GetAPIKey() @@ -102,6 +99,9 @@ func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant s return APIKeyDecision{Reason: "the stored API key cannot be read"} } + // A key inside the renewal window 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 @@ -109,11 +109,15 @@ func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant s if code := status.Code(err); code == codes.Unauthenticated || code == codes.PermissionDenied { return APIKeyDecision{Reason: "SafeDep Cloud rejected the stored API key"} } - return APIKeyDecision{Keep: true, ExpiresAt: expiresAt, - Warning: fmt.Sprintf("could not verify the stored API key: %v", err)} + warning = fmt.Sprintf("could not verify the stored API key: %v", err) + } + + if state == APIKeyExpiring { + return APIKeyDecision{Reason: "the stored API key expires on " + formatDay(expiresAt), + Fallback: true, ExpiresAt: expiresAt, Warning: warning} } - return APIKeyDecision{Keep: true, ExpiresAt: expiresAt} + return APIKeyDecision{Keep: true, ExpiresAt: expiresAt, Warning: warning} } func formatDay(t time.Time) string { diff --git a/internal/auth/apikey_renew_test.go b/internal/auth/apikey_renew_test.go index 25cc06e..808a057 100644 --- a/internal/auth/apikey_renew_test.go +++ b/internal/auth/apikey_renew_test.go @@ -74,13 +74,26 @@ func TestDecideStoredAPIKey(t *testing.T) { wantReason: "expired on 2026-11-21", }, { - name: "a key inside the renewal window", + 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, }, { name: "a key with no recorded expiry that SafeDep Cloud accepts", From 77ea26e036b677c8a74b7572c89332bf754dbec5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:20:42 +0000 Subject: [PATCH 06/11] fix(auth): keep both warnings and recheck the fallback expiry after a failed create When the Ping of a stored key failed with a network error and the create then failed too, the create warning replaced the Ping warning, so login did not say that it could not verify the key. Login now prints both. The fallback key is kept only while it has not expired. The create can take longer than the last seconds of a key inside the renewal window. TestPostOAuthBootstrap_CreateFails used a fixed expiry date, which would have failed after that date. It now uses a time relative to now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- internal/auth/bootstrap.go | 8 ++++++-- internal/auth/bootstrap_test.go | 32 ++++++++++++++++++++++++-------- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/internal/auth/bootstrap.go b/internal/auth/bootstrap.go index 7e991a9..63ceb4c 100644 --- a/internal/auth/bootstrap.go +++ b/internal/auth/bootstrap.go @@ -107,13 +107,17 @@ func PostOAuthBootstrap(ctx context.Context, in BootstrapInput) (*BootstrapResul } key, err := createAPIKey(ctx, in.ConnFor, in.AccessToken, tenant, in.APIKeyName, in.APIKeyExpiryDays) - if err != nil && res.APIKeyDecision.Fallback { + if err != nil && res.APIKeyDecision.Fallback && time.Now().Before(res.APIKeyDecision.ExpiresAt) { // The stored key still works, so a failed create must not cost the // user the OAuth tokens of this login. A Viewer cannot create keys. + warning := fmt.Sprintf("could not create a new API key, so the stored key stays: %v", err) + if prev := res.APIKeyDecision.Warning; prev != "" { + warning = prev + ". " + warning + } res.APIKeyDecision = APIKeyDecision{ Keep: true, ExpiresAt: res.APIKeyDecision.ExpiresAt, - Warning: fmt.Sprintf("could not create a new API key, so the stored key stays: %v", err), + Warning: warning, } return res, nil } diff --git a/internal/auth/bootstrap_test.go b/internal/auth/bootstrap_test.go index 86a5def..8ad095e 100644 --- a/internal/auth/bootstrap_test.go +++ b/internal/auth/bootstrap_test.go @@ -283,20 +283,34 @@ func TestPostOAuthBootstrap_DecideAPIKey(t *testing.T) { // 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.Date(2026, 11, 30, 0, 0, 0, 0, time.UTC) + expiresAt := time.Now().Add(72 * time.Hour).UTC().Truncate(time.Second) tests := []struct { - name string - decision APIKeyDecision - wantErr bool + name string + decision APIKeyDecision + wantErr bool + wantWarnings []string }{ { - name: "a stored key that still works is kept", - decision: APIKeyDecision{Reason: "the stored API key expires on 2026-11-30", Fallback: true, ExpiresAt: expiresAt}, + name: "a stored key that still works is kept", + decision: APIKeyDecision{Reason: "the stored API key expires soon", Fallback: true, ExpiresAt: expiresAt}, + wantWarnings: []string{"could not create a new API key"}, + }, + { + name: "both warnings reach the user", + decision: APIKeyDecision{Reason: "the stored API key expires soon", Fallback: true, ExpiresAt: expiresAt, + Warning: "could not verify the stored API key: no route"}, + wantWarnings: []string{"could not verify the stored API key", "could not create a new API key"}, + }, + { + name: "a fallback that expired during the create fails the login", + decision: APIKeyDecision{Reason: "the stored API key expires soon", Fallback: true, + ExpiresAt: time.Now().Add(-time.Second)}, + wantErr: true, }, { name: "no usable stored key fails the login", - decision: APIKeyDecision{Reason: "the stored API key expired on 2026-11-20"}, + decision: APIKeyDecision{Reason: "the stored API key expired"}, wantErr: true, }, } @@ -324,7 +338,9 @@ func TestPostOAuthBootstrap_CreateFails(t *testing.T) { require.NoError(t, err) assert.True(t, res.APIKeyDecision.Keep) assert.True(t, expiresAt.Equal(res.APIKeyDecision.ExpiresAt)) - assert.Contains(t, res.APIKeyDecision.Warning, "could not create a new API key") + for _, w := range tc.wantWarnings { + assert.Contains(t, res.APIKeyDecision.Warning, w) + } assert.Empty(t, res.APIKey) }) } From ba5e7c808f861795c3dacf10eab548b22e1cea8e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:18:09 +0000 Subject: [PATCH 07/11] chore(deps): move dry to the commit that stores API key metadata in one field The CLI uses the same dry API. dry now keeps the metadata in one best-effort keychain field. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 4a23c2d..98852e9 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-20261123090304-8e573bccdfd2 + github.com/safedep/dry v0.0.0-20261123111624-84c28d2fcde1 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 6822cb5..0abf438 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-20261123090304-8e573bccdfd2 h1:MqIARvB87AFgOL2zr4bvHB1YJPhB2+sIJ5uy7idMDuU= -github.com/safedep/dry v0.0.0-20261123090304-8e573bccdfd2/go.mod h1:DHtiOuwrtW3gzmMEMfX74Cs/MjclA2eAqdCON5uoKA0= +github.com/safedep/dry v0.0.0-20261123111624-84c28d2fcde1 h1:MqtVOk3OBHrxRQOjdjZEiFDAtZ091cuSqrbUaXTHTak= +github.com/safedep/dry v0.0.0-20261123111624-84c28d2fcde1/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= From e1848ff314c99f30e11fdf36c4742492845b8556 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:36:02 +0000 Subject: [PATCH 08/11] refactor(auth): save the API key metadata through CredentialStore dry now has SaveAPIKeyCredentialWithMetadata on CredentialStore, so SaveBootstrapResult calls it directly. The type check and its fallback to SaveAPIKeyCredential are gone: a wrapped store could take the fallback and save the key with no expiry. The test checks that the key id and expiry reach the store. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- go.mod | 2 +- go.sum | 4 +- internal/auth/apikey_renew_test.go | 2 +- internal/auth/mocks/CredentialStore_mock.go | 64 +++++++++++++++++++++ internal/auth/save.go | 16 ++---- internal/auth/save_test.go | 14 +++-- 6 files changed, 83 insertions(+), 19 deletions(-) diff --git a/go.mod b/go.mod index 98852e9..3d8ea15 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-20261123111624-84c28d2fcde1 + github.com/safedep/dry v0.0.0-20261123113435-ca6e27aaf6b2 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 0abf438..5144fef 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-20261123111624-84c28d2fcde1 h1:MqtVOk3OBHrxRQOjdjZEiFDAtZ091cuSqrbUaXTHTak= -github.com/safedep/dry v0.0.0-20261123111624-84c28d2fcde1/go.mod h1:DHtiOuwrtW3gzmMEMfX74Cs/MjclA2eAqdCON5uoKA0= +github.com/safedep/dry v0.0.0-20261123113435-ca6e27aaf6b2 h1:5OV641ale7Q/R6Jo9kYYUTBVPVTi562vYzU84e3BhNM= +github.com/safedep/dry v0.0.0-20261123113435-ca6e27aaf6b2/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/auth/apikey_renew_test.go b/internal/auth/apikey_renew_test.go index 808a057..8408aac 100644 --- a/internal/auth/apikey_renew_test.go +++ b/internal/auth/apikey_renew_test.go @@ -218,7 +218,7 @@ func TestStoredAPIKeyIgnoresTheEnvironment(t *testing.T) { 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.(cloud.APIKeyMetadataStore).SaveAPIKeyCredentialWithMetadata( + require.NoError(t, store.SaveAPIKeyCredentialWithMetadata( "sk-keychain", "acme.safedep.io", cloud.APIKeyMetadata{KeyID: "key-1", ExpiresAt: expired})) creds, err := StoredAPIKey(opts) 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 1362b56..2d2de94 100644 --- a/internal/auth/save.go +++ b/internal/auth/save.go @@ -9,8 +9,7 @@ import ( // SaveBootstrapResult persists the access token, refresh token, and (if present) // 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. A store that cannot hold metadata gets the key -// alone. +// 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) @@ -20,15 +19,10 @@ func SaveBootstrapResult(store cloud.CredentialStore, accessToken, refreshToken return nil } - var err error - if metaStore, ok := store.(cloud.APIKeyMetadataStore); ok { - err = metaStore.SaveAPIKeyCredentialWithMetadata(b.APIKey, b.Tenant, cloud.APIKeyMetadata{ - KeyID: b.APIKeyID, - ExpiresAt: b.APIKeyExpiresAt, - }) - } else { - err = store.SaveAPIKeyCredential(b.APIKey, b.Tenant) - } + 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) } 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", From 6c0a5ed2bc0f9d3157103b16414e55f6a407d9ad Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 14:14:36 +0000 Subject: [PATCH 09/11] build(deps): pin dry at the merge of safedep/dry#193 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 3d8ea15..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-20261123113435-ca6e27aaf6b2 + 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 5144fef..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-20261123113435-ca6e27aaf6b2 h1:5OV641ale7Q/R6Jo9kYYUTBVPVTi562vYzU84e3BhNM= -github.com/safedep/dry v0.0.0-20261123113435-ca6e27aaf6b2/go.mod h1:DHtiOuwrtW3gzmMEMfX74Cs/MjclA2eAqdCON5uoKA0= +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= From fbcee8eab44f0a691803ad6194eeafecbd58de0b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 14:53:25 +0000 Subject: [PATCH 10/11] fix(auth): replace a key with no recorded expiry, and keep the OAuth tokens when no key can be created Every key that a CLI saved before it recorded the expiry has none. Login kept such a key while SafeDep Cloud accepted it, and status called it authenticated, so the key could still expire under pmg and vet with no warning. Login now replaces it, and keeps it as the fallback when it cannot create a new key. When the stored key was expired, rejected or for another tenant and the create failed, login exited before it saved the OAuth tokens. A user who cannot create keys lost the control plane login. Login now saves the tokens and warns. An explicit --rotate-api-key still fails. --rotate-api-key accepts any --api-key-expiry-days: the 14-day minimum only stops login from replacing its own key on every run. Command code read the keychain through a helper in internal/auth. It now reads it through App.StoredAPIKey. Device login takes its keychain, browser flow, bootstrap and verifier as dependencies, and TestDeviceLogin covers the wiring that no test guarded: the key check that login hands the bootstrap, what it saves, and what it prints. The decision test adds cases at the boundaries of the renewal window. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- docs/cmd/auth-login.md | 14 ++- docs/cmd/auth-status.md | 2 +- internal/app/app.go | 8 ++ internal/auth/apikey_renew.go | 24 +++-- internal/auth/apikey_renew_test.go | 23 ++++- internal/auth/bootstrap.go | 29 +++--- internal/auth/bootstrap_test.go | 72 ++++++++++---- internal/cmd/auth/login.go | 48 ++++++++-- internal/cmd/auth/login_test.go | 148 ++++++++++++++++++++++++++++- internal/cmd/auth/status.go | 2 +- internal/cmd/auth/status_test.go | 2 +- 11 files changed, 313 insertions(+), 59 deletions(-) diff --git a/docs/cmd/auth-login.md b/docs/cmd/auth-login.md index e4ec069..97e9e84 100644 --- a/docs/cmd/auth-login.md +++ b/docs/cmd/auth-login.md @@ -9,16 +9,22 @@ By default, runs the OAuth2 device-code flow in the browser, picks an accessible 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. It does not expire within 14 days. +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, stays when SafeDep Cloud accepts it. Pass `--rotate-api-key` to replace it with a key whose expiry is recorded. +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, and when it cannot create a new key while the stored key still works, for example for a user who cannot create keys. +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. +- 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`. @@ -37,7 +43,7 @@ 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). Must be more than 14, because login replaces a key that expires within 14 days. | +| `--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 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. | diff --git a/docs/cmd/auth-status.md b/docs/cmd/auth-status.md index 79b228e..4ebe05d 100644 --- a/docs/cmd/auth-status.md +++ b/docs/cmd/auth-status.md @@ -19,7 +19,7 @@ The API key has one of these states: | `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 --rotate-api-key` replaces it with a key whose expiry is recorded. | +| `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. | | `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. 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 index ea73b07..af2c2b1 100644 --- a/internal/auth/apikey_renew.go +++ b/internal/auth/apikey_renew.go @@ -66,16 +66,20 @@ type APIKeyDecision struct { Warning string // Fallback means that the stored key still works for the tenant, so - // login keeps it when it cannot create a new key. ExpiresAt is set. + // 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, it does not expire -// within APIKeyRenewWindow, and SafeDep Cloud accepts it. A key with no -// recorded expiry, such as a pasted key, stays when SafeDep Cloud accepts it: -// an expired key fails that check. +// 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 { @@ -99,8 +103,8 @@ func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant s return APIKeyDecision{Reason: "the stored API key cannot be read"} } - // A key inside the renewal window is checked too: login falls back to it - // when it cannot create a new key, and a revoked key must not be kept. + // 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 @@ -112,9 +116,13 @@ func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant s warning = fmt.Sprintf("could not verify the stored API key: %v", err) } - if state == APIKeyExpiring { + 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} diff --git a/internal/auth/apikey_renew_test.go b/internal/auth/apikey_renew_test.go index 8408aac..f49f336 100644 --- a/internal/auth/apikey_renew_test.go +++ b/internal/auth/apikey_renew_test.go @@ -96,11 +96,15 @@ func TestDecideStoredAPIKey(t *testing.T) { 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{}) }, - wantKeep: true, + wantReason: "expiry of the stored API key is not recorded", + wantFallback: true, wantVerified: true, }, { @@ -112,6 +116,23 @@ func TestDecideStoredAPIKey(t *testing.T) { 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 { diff --git a/internal/auth/bootstrap.go b/internal/auth/bootstrap.go index 63ceb4c..9ae7f77 100644 --- a/internal/auth/bootstrap.go +++ b/internal/auth/bootstrap.go @@ -61,6 +61,11 @@ type BootstrapResult struct { // 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 @@ -107,18 +112,20 @@ func PostOAuthBootstrap(ctx context.Context, in BootstrapInput) (*BootstrapResul } key, err := createAPIKey(ctx, in.ConnFor, in.AccessToken, tenant, in.APIKeyName, in.APIKeyExpiryDays) - if err != nil && res.APIKeyDecision.Fallback && time.Now().Before(res.APIKeyDecision.ExpiresAt) { - // The stored key still works, so a failed create must not cost the - // user the OAuth tokens of this login. A Viewer cannot create keys. - warning := fmt.Sprintf("could not create a new API key, so the stored key stays: %v", err) - if prev := res.APIKeyDecision.Warning; prev != "" { - warning = prev + ". " + warning - } - res.APIKeyDecision = APIKeyDecision{ - Keep: true, - ExpiresAt: res.APIKeyDecision.ExpiresAt, - Warning: warning, + 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. An explicit --rotate-api-key + // has no DecideAPIKey and fails instead. + 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 } + res.APIKeyError = err return res, nil } if err != nil { diff --git a/internal/auth/bootstrap_test.go b/internal/auth/bootstrap_test.go index 8ad095e..72badb5 100644 --- a/internal/auth/bootstrap_test.go +++ b/internal/auth/bootstrap_test.go @@ -284,34 +284,57 @@ func TestPostOAuthBootstrap_DecideAPIKey(t *testing.T) { // 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 - decision APIKeyDecision - wantErr bool - wantWarnings []string + 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", - decision: APIKeyDecision{Reason: "the stored API key expires soon", Fallback: true, ExpiresAt: expiresAt}, - wantWarnings: []string{"could not create a new API key"}, + 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", - decision: APIKeyDecision{Reason: "the stored API key expires soon", Fallback: true, ExpiresAt: expiresAt, - Warning: "could not verify the stored API key: no route"}, - wantWarnings: []string{"could not verify the stored API key", "could not create a new API key"}, + 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 fallback that expired during the create fails the login", - decision: APIKeyDecision{Reason: "the stored API key expires soon", Fallback: true, - ExpiresAt: time.Now().Add(-time.Second)}, - wantErr: true, + 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"}, }, { - name: "no usable stored key fails the login", - decision: APIKeyDecision{Reason: "the stored API key expired"}, - wantErr: true, + // 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, + }, + { + name: "--rotate-api-key fails the login", + wantErr: true, }, } @@ -327,7 +350,7 @@ func TestPostOAuthBootstrap_CreateFails(t *testing.T) { AccessToken: "token-123", CreateAPIKey: true, APIKeyExpiryDays: 90, - DecideAPIKey: func(context.Context, string) APIKeyDecision { return tc.decision }, + DecideAPIKey: tc.decide, ConnFor: connFor, }) @@ -336,12 +359,19 @@ func TestPostOAuthBootstrap_CreateFails(t *testing.T) { return } require.NoError(t, err) - assert.True(t, res.APIKeyDecision.Keep) - assert.True(t, expiresAt.Equal(res.APIKeyDecision.ExpiresAt)) + 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) } - assert.Empty(t, res.APIKey) + if tc.wantCreateError { + assert.Equal(t, codes.PermissionDenied, status.Code(res.APIKeyError)) + } else { + assert.NoError(t, res.APIKeyError) + } }) } } diff --git a/internal/cmd/auth/login.go b/internal/cmd/auth/login.go index 8d32839..95e5c91 100644 --- a/internal/cmd/auth/login.go +++ b/internal/cmd/auth/login.go @@ -88,7 +88,31 @@ 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 } @@ -96,15 +120,14 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { // 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 := a.CredentialStore() + 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 } @@ -117,7 +140,7 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { } } - createKey, decideAPIKey := apiKeyPlan(flags, a.KeychainOptions()) + createKey, decideAPIKey := apiKeyPlan(flags, deps.storedAPIKey, deps.verify) var name string if createKey { name = cliauth.APIKeyName(cliauth.Hostname(), time.Now()) @@ -132,7 +155,7 @@ 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, @@ -156,6 +179,10 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { } 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 != "": if decision.Reason != "" { tui.Info("Created a new API key: %s.", decision.Reason) @@ -176,9 +203,10 @@ func runDeviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags) error { // validateAPIKeyExpiryDays 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. +// 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 { + if flags.noAPIKey || flags.rotateAPIKey { return nil } windowDays := int(cliauth.APIKeyRenewWindow.Hours() / 24) @@ -192,7 +220,7 @@ func validateAPIKeyExpiryDays(flags loginFlags) error { // 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, opts []cloud.KeychainOption, +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 @@ -201,11 +229,11 @@ func apiKeyPlan(flags loginFlags, opts []cloud.KeychainOption, return true, nil } return true, func(ctx context.Context, tenant string) cliauth.APIKeyDecision { - stored, err := cliauth.StoredAPIKey(opts) + 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(), cliauth.VerifyAPIKey) + return cliauth.DecideStoredAPIKey(ctx, stored, tenant, time.Now(), verify) } } diff --git a/internal/cmd/auth/login_test.go b/internal/cmd/auth/login_test.go index 01b02b5..c9be077 100644 --- a/internal/cmd/auth/login_test.go +++ b/internal/cmd/auth/login_test.go @@ -1,9 +1,23 @@ 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) { @@ -20,7 +34,7 @@ func TestAPIKeyPlan(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - create, decide := apiKeyPlan(tc.flags, nil) + create, decide := apiKeyPlan(tc.flags, nil, nil) assert.Equal(t, tc.wantCreate, create) assert.Equal(t, tc.wantDecider, decide != nil) }) @@ -31,4 +45,136 @@ 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})) +} + +// 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 c5d96d3..b480930 100644 --- a/internal/cmd/auth/status.go +++ b/internal/cmd/auth/status.go @@ -148,7 +148,7 @@ func nextStepHint(st cliauth.Status, now time.Time) string { 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 --rotate-api-key' to replace it with a key whose expiry is recorded." + "Run 'safedep auth login' to replace it with a key whose expiry is recorded." } return "" } diff --git a/internal/cmd/auth/status_test.go b/internal/cmd/auth/status_test.go index 49610b0..0bd5fc6 100644 --- a/internal/cmd/auth/status_test.go +++ b/internal/cmd/auth/status_test.go @@ -45,7 +45,7 @@ func TestNextStepHint(t *testing.T) { { "api key with no recorded expiry", cliauth.Status{APIKey: true, OAuth: true}, - "--rotate-api-key", + "API key expiry is not recorded", }, } From 4c8a9db9898287767391d4b80233b4e3b3bd8b1a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:03:46 +0000 Subject: [PATCH 11/11] fix(auth): fail login when the stored key of another tenant cannot be replaced When the stored API key belonged to another tenant and the create failed, login saved the OAuth tokens of the picked tenant next to the key of the other tenant. api_key_metadata keeps that key on its own tenant, so data plane calls kept going to the other tenant, and pmg with an older dry sent the key with the wrong tenant. Login now fails in that case and saves nothing, as it did before. --rotate-api-key skips only the 14-day minimum. A lifetime that SafeDep Cloud refuses, such as 0, fails before the browser flow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YBw4rZJsNtttvFp8xuGbEj --- docs/cmd/auth-login.md | 3 ++- docs/cmd/auth-status.md | 2 +- internal/auth/apikey_renew.go | 9 ++++++++- internal/auth/apikey_renew_test.go | 3 +++ internal/auth/bootstrap.go | 8 ++++++-- internal/auth/bootstrap_test.go | 8 ++++++++ internal/cmd/auth/login.go | 18 +++++++++++++----- internal/cmd/auth/login_test.go | 1 + 8 files changed, 42 insertions(+), 10 deletions(-) diff --git a/docs/cmd/auth-login.md b/docs/cmd/auth-login.md index 97e9e84..2573393 100644 --- a/docs/cmd/auth-login.md +++ b/docs/cmd/auth-login.md @@ -23,6 +23,7 @@ Login keeps the stored key and prints a warning when SafeDep Cloud cannot be rea 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. @@ -43,7 +44,7 @@ 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). Must be more than 14, because login replaces a key that expires within 14 days. With `--rotate-api-key`, any value is accepted. | +| `--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. | diff --git a/docs/cmd/auth-status.md b/docs/cmd/auth-status.md index 4ebe05d..ac0f0e8 100644 --- a/docs/cmd/auth-status.md +++ b/docs/cmd/auth-status.md @@ -19,7 +19,7 @@ The API key has one of these states: | `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. | +| `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. diff --git a/internal/auth/apikey_renew.go b/internal/auth/apikey_renew.go index af2c2b1..79f2eb6 100644 --- a/internal/auth/apikey_renew.go +++ b/internal/auth/apikey_renew.go @@ -65,6 +65,12 @@ type APIKeyDecision struct { // 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. @@ -89,7 +95,8 @@ func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant s storedTenant, err := stored.GetTenantDomain() if err != nil || storedTenant != tenant { - return APIKeyDecision{Reason: fmt.Sprintf("the stored API key belongs to tenant %q", storedTenant)} + return APIKeyDecision{Reason: fmt.Sprintf("the stored API key belongs to tenant %q", storedTenant), + OtherTenant: true} } expiresAt, _ := stored.APIKeyExpiresAt() diff --git a/internal/auth/apikey_renew_test.go b/internal/auth/apikey_renew_test.go index f49f336..2128261 100644 --- a/internal/auth/apikey_renew_test.go +++ b/internal/auth/apikey_renew_test.go @@ -52,6 +52,7 @@ func TestDecideStoredAPIKey(t *testing.T) { wantVerified bool wantWarning bool wantFallback bool + wantOther bool }{ { name: "no stored key", @@ -64,6 +65,7 @@ func TestDecideStoredAPIKey(t *testing.T) { return keychainCredentials(t, "sk-1", "old.safedep.io", valid) }, wantReason: `belongs to tenant "old.safedep.io"`, + wantOther: true, }, { name: "an expired key", @@ -189,6 +191,7 @@ func TestDecideStoredAPIKey(t *testing.T) { } 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 { diff --git a/internal/auth/bootstrap.go b/internal/auth/bootstrap.go index 9ae7f77..801b34f 100644 --- a/internal/auth/bootstrap.go +++ b/internal/auth/bootstrap.go @@ -114,8 +114,9 @@ func PostOAuthBootstrap(ctx context.Context, in BootstrapInput) (*BootstrapResul 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. An explicit --rotate-api-key - // has no DecideAPIKey and fails instead. + // 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) @@ -125,6 +126,9 @@ func PostOAuthBootstrap(ctx context.Context, in BootstrapInput) (*BootstrapResul 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 } diff --git a/internal/auth/bootstrap_test.go b/internal/auth/bootstrap_test.go index 72badb5..b13aaab 100644 --- a/internal/auth/bootstrap_test.go +++ b/internal/auth/bootstrap_test.go @@ -332,6 +332,14 @@ func TestPostOAuthBootstrap_CreateFails(t *testing.T) { 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, diff --git a/internal/cmd/auth/login.go b/internal/cmd/auth/login.go index 95e5c91..6695697 100644 --- a/internal/cmd/auth/login.go +++ b/internal/cmd/auth/login.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "math" "os" "strings" "time" @@ -201,12 +202,19 @@ func deviceLogin(cmd *cobra.Command, a *app.App, flags loginFlags, deps deviceLo return nil } -// validateAPIKeyExpiryDays 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. +// 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 || flags.rotateAPIKey { + if flags.noAPIKey { + 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 { return nil } windowDays := int(cliauth.APIKeyRenewWindow.Hours() / 24) diff --git a/internal/cmd/auth/login_test.go b/internal/cmd/auth/login_test.go index c9be077..74dfab6 100644 --- a/internal/cmd/auth/login_test.go +++ b/internal/cmd/auth/login_test.go @@ -46,6 +46,7 @@ func TestValidateAPIKeyExpiryDays(t *testing.T) { 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