Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/DEVGUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:

Expand Down
33 changes: 29 additions & 4 deletions docs/cmd/auth-login.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,32 @@

Authenticate with SafeDep Cloud and store credentials in the keychain under the active profile.

By default, runs the OAuth2 device-code flow in the browser, picks an accessible tenant, creates a fresh API key, and stores both the OAuth tokens and the API key in the keychain. Pass `--api-key` to skip the OAuth flow and store an API key you already have.
By default, runs the OAuth2 device-code flow in the browser, picks an accessible tenant, makes sure the profile holds a valid API key, and stores the OAuth tokens and the API key in the keychain. Pass `--api-key` to skip the OAuth flow and store an API key you already have.

## API key

The device flow keeps the API key that the keychain holds for the profile only when all of these hold:

1. The key belongs to the tenant that you picked.
2. Its recorded expiry is more than 14 days away.
3. SafeDep Cloud accepts it.

Otherwise login creates a new key and prints why, for example `Created a new API key: the stored API key expired on 2026-11-20.` The key is saved with its id and expiry, so the next login and `safedep auth status` can tell when it expires.

A key with no recorded expiry, such as a key saved with `--api-key` or by an earlier CLI, is replaced, because `safedep auth status` cannot warn before it expires.

Login does not revoke the key that it replaces. That key stops working at its own expiry, and any tool that still holds a copy of it, such as an MCP client set up with `safedep protect mcp install`, keeps working until then. SafeDep Cloud still sends the expiry email for it. Delete it in app.safedep.io to revoke it at once.

Login keeps the stored key and prints a warning when SafeDep Cloud cannot be reached.

When login cannot create a new key, for example for a user who cannot create keys:

- If SafeDep Cloud still accepts the stored key, login keeps it and prints a warning.
- If the stored key belongs to another tenant, login fails and stores nothing. The OAuth tokens of one tenant next to the key of another would send pmg, vet and data plane commands to the other tenant.
- Otherwise login stores the OAuth tokens, prints a warning and exits with success. `safedep auth status` then shows the state of the old key. pmg and vet need a key: ask a tenant admin for one and save it with `safedep auth login --api-key`.
- With `--rotate-api-key`, login fails and stores nothing.

pmg and vet read the API key from the keychain. Login checks the keychain key, not `SAFEDEP_API_KEY`.

## Synopsis

Expand All @@ -19,8 +44,8 @@ safedep auth login --api-key [--api-key-value <key> | --from-stdin] [--tenant <d
| `--api-key-value <key>` | 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 <domain>` | Tenant domain. Used as fallback when none is stored for the profile. |
| `--api-key-expiry-days <n>` | Expiry for API keys created during device login (default 90). |
| `--rotate-api-key` | Force creation of a new API key during device login. By default, an existing API key for the chosen tenant is preserved. |
| `--api-key-expiry-days <n>` | Expiry for API keys created during device login (default 90). Must be more than 14, because login replaces a key that expires within 14 days. With `--rotate-api-key`, any positive value is accepted. |
| `--rotate-api-key` | Create a new API key during device login even when the stored key is valid. |
| `--no-api-key` | Skip API key creation during device login. OAuth tokens are still stored. |

Inherits root flags `--output`, `--profile`, and `--insecure-keychain-fallback`.
Expand All @@ -35,7 +60,7 @@ For `--api-key`:

## Outputs

- Device flow: opens the verification URL in your browser (rich mode) and prints the user code. After the IdP confirms the grant, prints a success line with tenant, profile, and API-key expiry.
- Device flow: opens the verification URL in your browser (rich mode) and prints the user code. After the IdP confirms the grant, prints a success line with tenant, profile, and the expiry of the API key that it created or kept.
- API-key flow: verifies the key against the data plane before storing. Prints success on completion.

## Exit codes
Expand Down
18 changes: 15 additions & 3 deletions docs/cmd/auth-status.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,25 @@ safedep auth status [--output table|plain|json] [--profile <name>]

## Output

Reports profile name, tenant, presence of an API key, presence of an OAuth token, and the OAuth access-token expiry decoded from the JWT.
Reports profile name, tenant, the API key and its recorded expiry, presence of an OAuth token, and the OAuth access-token expiry decoded from the JWT. Status reads the keychain only. It does not call SafeDep Cloud.

The API key has one of these states:

| State | Table badge | Meaning |
|---|---|---|
| `valid` | `configured` | The recorded expiry is more than 14 days away. |
| `expiring` | `expires soon` | The key expires within 14 days. `safedep auth login` replaces it. |
| `expired` | `expired` | The recorded expiry has passed. pmg and vet fail with this key. |
| `expiry_unknown` | `expiry unknown` | No expiry is recorded, for example for a key saved by `--api-key` or by an earlier CLI. Status cannot tell whether it has expired. `safedep auth login` replaces it with a key whose expiry is recorded. Login keeps it, with a warning, when it cannot create a new key and SafeDep Cloud still accepts this one. |
| `missing` | `not configured` | The profile holds no API key. |

The overall status is `authenticated` only when the OAuth token is valid and the API key has not expired.

| Mode | Format |
|---|---|
| `table` | Tabular block with badges for each credential. |
| `plain` | `key: value` lines. |
| `json` | `{profile, tenant, api_key_present, oauth_token_present, oauth_expires_at}`. |
| `plain` | `key: value` lines, with `API key state` and `Key expires` lines for an API key. |
| `json` | `{profile, tenant, api_key_present, api_key_state, api_key_expires_at, oauth_token_present, oauth_expires_at}`. |

## Exit codes

Expand Down
7 changes: 4 additions & 3 deletions docs/cmd/package-scan-run.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<ref>` suffix resolves to the head of
the default branch.

Expand Down
4 changes: 4 additions & 0 deletions docs/cmd/policy-decision-list.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ require (
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/uuid v1.6.0
github.com/oklog/ulid/v2 v2.1.2
github.com/safedep/dry v0.0.0-20260902191040-800bc36ff686
github.com/safedep/dry v0.0.0-20261123141204-0458858d29a8
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0
github.com/stretchr/testify v1.11.1
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,8 @@ github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/safedep/dry v0.0.0-20260902191040-800bc36ff686 h1:uODPiRdQfdI5rvaak/X1pRbHURBKrWP7CUjVuHViIkQ=
github.com/safedep/dry v0.0.0-20260902191040-800bc36ff686/go.mod h1:W/OgEQaB88bPxIKUHKZ2S9lYMtO7lsFlo/j1yNv8HDg=
github.com/safedep/dry v0.0.0-20261123141204-0458858d29a8 h1:jESd4h8s+v8PuY4RxbloLHX3RHynVbNUI/beWnJWt/M=
github.com/safedep/dry v0.0.0-20261123141204-0458858d29a8/go.mod h1:DHtiOuwrtW3gzmMEMfX74Cs/MjclA2eAqdCON5uoKA0=
github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
Expand Down
8 changes: 8 additions & 0 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
165 changes: 165 additions & 0 deletions internal/auth/apikey_renew.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package auth

import (
"context"
"errors"
"fmt"
"time"

"github.com/safedep/dry/cloud"
"github.com/safedep/dry/log"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)

// APIKeyRenewWindow is how long before its expiry login replaces an API key.
// A key that expires inside the window would stop pmg and vet before the user
// signs in again.
const APIKeyRenewWindow = 14 * 24 * time.Hour

// APIKeyState is what the keychain says about the stored API key.
type APIKeyState int

const (
APIKeyMissing APIKeyState = iota
APIKeyValid
APIKeyExpiring
APIKeyExpired
// APIKeyExpiryUnknown is a key saved with no expiry: a pasted key, or a
// key from a CLI that did not record it. Only SafeDep Cloud can tell
// whether it is valid.
APIKeyExpiryUnknown
)

// APIKeyStateAt returns the state of a stored key at now.
func APIKeyStateAt(present bool, expiresAt time.Time, now time.Time) APIKeyState {
switch {
case !present:
return APIKeyMissing
case expiresAt.IsZero():
return APIKeyExpiryUnknown
case !expiresAt.After(now):
return APIKeyExpired
case expiresAt.Before(now.Add(APIKeyRenewWindow)):
return APIKeyExpiring
default:
return APIKeyValid
}
}

// APIKeyVerifier checks a key against SafeDep Cloud. VerifyAPIKey is the
// production verifier. Tests pass a fake.
type APIKeyVerifier func(ctx context.Context, in APIKeyInput) error

// APIKeyDecision is whether login keeps the stored API key, and why not.
type APIKeyDecision struct {
Keep bool

// Reason says why login replaces the key. Empty when Keep is true.
Reason string

// ExpiresAt is the expiry of the key that login keeps.
ExpiresAt time.Time

// Warning reports a check that could not finish. Login keeps the key,
// because a network failure says nothing about the key.
Warning string

// OtherTenant means that the stored key belongs to another tenant. When
// login cannot create a key, it must then fail: the OAuth tokens of the
// picked tenant next to the key of another tenant would send data plane
// calls to the other tenant.
OtherTenant bool

// Fallback means that the stored key still works for the tenant, so
// login keeps it when it cannot create a new key. ExpiresAt is zero when
// the expiry of the key is not recorded.
Fallback bool
}

// DecideStoredAPIKey decides whether login keeps the API key that the
// keychain holds for the profile. stored is nil when the keychain holds no
// key. The key stays only when it belongs to tenant, its recorded expiry is
// more than APIKeyRenewWindow away, and SafeDep Cloud accepts it.
//
// A key with no recorded expiry is replaced: every key that a CLI saved
// before it recorded the expiry is one, and status cannot warn before such a
// key expires. Like a key inside the window, it is the fallback when login
// cannot create a new key.
func DecideStoredAPIKey(ctx context.Context, stored *cloud.Credentials, tenant string, now time.Time,
verify APIKeyVerifier,
) APIKeyDecision {
if stored == nil {
return APIKeyDecision{Reason: "no API key is stored"}
}

storedTenant, err := stored.GetTenantDomain()
if err != nil || storedTenant != tenant {
return APIKeyDecision{Reason: fmt.Sprintf("the stored API key belongs to tenant %q", storedTenant),
OtherTenant: true}
}

expiresAt, _ := stored.APIKeyExpiresAt()
state := APIKeyStateAt(true, expiresAt, now)
if state == APIKeyExpired {
return APIKeyDecision{Reason: "the stored API key expired on " + formatDay(expiresAt)}
}

key, err := stored.GetAPIKey()
if err != nil {
return APIKeyDecision{Reason: "the stored API key cannot be read"}
}

// A key that login replaces is checked too: login falls back to it when
// it cannot create a new key, and a revoked key must not be kept.
warning := ""
if err := verify(ctx, APIKeyInput{APIKey: key, Tenant: tenant}); err != nil {
// The gateway answers Unauthenticated for an expired key and
// PermissionDenied for a key that it does not know, such as a
// revoked one. Both mean that a new key is needed.
if code := status.Code(err); code == codes.Unauthenticated || code == codes.PermissionDenied {
return APIKeyDecision{Reason: "SafeDep Cloud rejected the stored API key"}
}
warning = fmt.Sprintf("could not verify the stored API key: %v", err)
}

switch state {
case APIKeyExpiring:
return APIKeyDecision{Reason: "the stored API key expires on " + formatDay(expiresAt),
Fallback: true, ExpiresAt: expiresAt, Warning: warning}
case APIKeyExpiryUnknown:
return APIKeyDecision{Reason: "the expiry of the stored API key is not recorded",
Fallback: true, Warning: warning}
}

return APIKeyDecision{Keep: true, ExpiresAt: expiresAt, Warning: warning}
}

func formatDay(t time.Time) string {
return t.UTC().Format("2006-01-02")
}

// StoredAPIKey returns the API key credentials of the profile in the
// keychain, or nil when there are none. It reads the keychain alone: pmg and
// vet read the key from there, so an API key in the environment must not
// stop login from replacing an expired keychain key.
func StoredAPIKey(opts []cloud.KeychainOption) (*cloud.Credentials, error) {
resolver, err := cloud.NewKeychainCredentialResolver(cloud.CredentialTypeAPIKey, opts...)
if err != nil {
return nil, err
}
defer func() {
if err := resolver.Close(); err != nil {
log.Warnf("auth: close keychain resolver: %v", err)
}
}()

creds, err := resolver.Resolve()
if errors.Is(err, cloud.ErrMissingCredentials) && !errors.Is(err, cloud.ErrIncompleteCredentials) {
return nil, nil
}
if err != nil {
return nil, err
}
return creds, nil
}
Loading
Loading