auth

package
v1.11.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	WorkloadIdentityTokenFileEnv   = "BASETEN_WORKLOAD_IDENTITY_TOKEN_FILE"
	WorkloadIdentityTokenEnv       = "BASETEN_WORKLOAD_IDENTITY_TOKEN"
	WorkloadIdentityTrustRuleIDEnv = "BASETEN_WORKLOAD_IDENTITY_TRUST_RULE_ID"
)

Environment variables that select workload identity federation: the CLI exchanges an identity token, read from WorkloadIdentityTokenFileEnv or given inline in WorkloadIdentityTokenEnv, for a short-lived Baseten access token under the trust rule in WorkloadIdentityTrustRuleIDEnv.

Variables

This section is empty.

Functions

func DefaultConfigDir

func DefaultConfigDir() (string, error)

DefaultConfigDir returns the config directory: $BASETEN_CONFIG_DIR > os.UserConfigDir()/baseten

func IsTokenExchangeRefused added in v1.10.0

func IsTokenExchangeRefused(err error) bool

IsTokenExchangeRefused reports whether err carries the token exchange's OAuth invalid_grant answer, which Baseten sends for every refused identity token.

func NewErrProfileNotFound added in v1.7.0

func NewErrProfileNotFound(names []string, profileName string) error

NewErrProfileNotFound returns the error for a named profile that is not in the store, suggesting how to add it.

func OAuthContext

func OAuthContext(ctx context.Context, base http.RoundTripper) context.Context

OAuthContext returns a context that carries an oauth2 HTTP client which stamps the Baseten User-Agent on every request, layered over base. Requests made through the client are bound to ctx, so cancelling ctx aborts them.

func WorkloadIdentityEnvSet added in v1.10.0

func WorkloadIdentityEnvSet() bool

WorkloadIdentityEnvSet reports whether any workload identity variable is set, including in a combination that does not resolve.

Types

type AuthFile

type AuthFile struct {
	Version int `json:"version"`
	// Current is the name of the profile used when no profile is selected via
	// flag or environment.
	Current string `json:"current,omitempty"`
	// RequireExplicitProfile disables the current profile: every command must
	// select a profile via flag or environment.
	RequireExplicitProfile bool               `json:"require_explicit_profile,omitempty"`
	Profiles               map[string]Profile `json:"profiles"`
	// InsecureRoutesKeys holds routes API keys by scope hash. Only populated
	// when the keyring is unavailable.
	InsecureRoutesKeys map[string]string `json:"routes_keys,omitempty"`
}

AuthFile is the on-disk auth.json structure. Unrecognized keys are ignored on read and dropped on the next write.

type AuthType

type AuthType string

AuthType identifies how a credential was obtained.

const (
	AuthTypeOAuth  AuthType = "oauth"
	AuthTypeAPIKey AuthType = "api_key"
)

type DriveToken added in v1.10.0

type DriveToken struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
}

type DriveTokenScope added in v1.10.0

type DriveTokenScope struct {
	ManagementURL string `json:"management_url"`
	Identity      string `json:"identity"`
}

DriveTokenScope keys the cache by issuing endpoint and Session.CacheIdentity.

type ErrExplicitProfileRequired added in v1.8.0

type ErrExplicitProfileRequired struct {
	// Profiles are the stored profile names in sorted order.
	Profiles []string
}

ErrExplicitProfileRequired is returned when explicit profile selection is required and nothing selected a profile.

func (*ErrExplicitProfileRequired) Error added in v1.8.0

type GridToken added in v1.7.0

type GridToken struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
}

type GridTokenScope added in v1.7.0

type GridTokenScope struct {
	ManagementURL string `json:"management_url"`
	Identity      string `json:"identity"`
}

GridTokenScope keys the cache by issuing endpoint and Session.CacheIdentity.

type OAuthCredential

type OAuthCredential struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token"`
	Expiry       time.Time `json:"expiry,omitempty"`
}

OAuthCredential holds an OAuth access and refresh token pair, along with the access token's absolute expiry. Expiry is what golang.org/x/oauth2 uses to decide whether to refresh; persisting it lets refresh work across CLI invocations.

type Profile added in v0.2.0

type Profile struct {
	RemoteURL string   `json:"remote_url"`
	AuthType  AuthType `json:"auth_type"`

	// InsecureOAuthCredential and InsecureAPIKey are only populated when the
	// keyring is unavailable or --insecure-storage was used.
	InsecureOAuthCredential *OAuthCredential `json:"oauth_credential,omitempty"`
	InsecureAPIKey          string           `json:"api_key,omitempty"`
}

Profile is a single named, self-contained credential: a remote URL plus the auth used against it. The profile name is the keyring account and the auth.json map key.

type RoutesKeyScope added in v1.1.0

type RoutesKeyScope struct {
	ManagementURL string `json:"management_url"`
	Profile       string `json:"profile"`
	UserID        string `json:"user_id"`
	TeamID        string `json:"team_id"`
}

RoutesKeyScope identifies a saved Grid API key by issuing endpoint, profile, user, and team: each profile keeps one key per user and team on this machine.

type SandboxToken added in v1.7.0

type SandboxToken struct {
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expires_at"`
}

type SandboxTokenScope added in v1.7.0

type SandboxTokenScope struct {
	ManagementURL string `json:"management_url"`
	Identity      string `json:"identity"`
}

SandboxTokenScope keys the cache by issuing endpoint and Session.CacheIdentity.

type Session added in v0.2.0

type Session struct {
	// contains filtered or unexported fields
}

Session is the auth context resolved once per invocation. Exactly one of the credential paths applies: a stored profile (ProfileName set), an ephemeral API key from the environment (ephemeralAPIKey set), or workload identity from the environment (workloadIdentity set).

func ResolveSession added in v0.2.0

func ResolveSession(profileFlag, defaultProfile string) (*Session, error)

ResolveSession determines the effective auth for this invocation, most specific source first:

  1. profileFlag (the --profile flag)
  2. BASETEN_API_KEY (+ optional BASETEN_REMOTE_URL), ephemeral
  3. BASETEN_WORKLOAD_IDENTITY_TRUST_RULE_ID with BASETEN_WORKLOAD_IDENTITY_TOKEN_FILE or BASETEN_WORKLOAD_IDENTITY_TOKEN (+ optional BASETEN_REMOTE_URL), ephemeral workload identity. Setting these and BASETEN_API_KEY together is an error.
  4. BASETEN_PROFILE
  5. defaultProfile (a baked-in fallback, e.g. from the SSH config)
  6. the current profile in auth.json, or an *ErrExplicitProfileRequired when explicit profile selection is required

defaultProfile is "" for most commands; the SSH sign/proxy commands pass their --default-profile so a pinned profile is used only when nothing more specific selects one.

A named profile that does not exist is not an error here; the failure surfaces when a credential is actually needed (or in the auth commands that manage profiles directly).

func (*Session) APIKey added in v1.4.0

func (s *Session) APIKey(ctx context.Context) (string, error)

APIKey returns the session's API key when it authenticates with one — the ephemeral BASETEN_API_KEY value, or the stored key of an API key profile — and "" for OAuth or unauthenticated sessions, which have no embeddable key.

func (*Session) CacheIdentity added in v0.4.0

func (s *Session) CacheIdentity() string

CacheIdentity returns a stable, filesystem-safe token for the resolved credential, scoping on-disk caches so an entry written under one credential is never read under another. Hashed to keep the profile name (an email by default) and the API key out of file paths.

func (*Session) CachesCapabilityTokens added in v1.10.0

func (s *Session) CachesCapabilityTokens() bool

CachesCapabilityTokens reports whether sandbox and Grid tokens minted for the session may be cached across invocations. Not under workload identity: another workload can present a different identity through the same token file path, which no cache key derived from the session tells apart.

func (*Session) IsEphemeral added in v0.2.0

func (s *Session) IsEphemeral() bool

IsEphemeral reports whether the session uses credentials from the environment (BASETEN_API_KEY or workload identity) rather than a stored profile.

func (*Session) NewWorkloadIdentityCredentials added in v1.10.0

func (s *Session) NewWorkloadIdentityCredentials(managementURL string, httpClient *http.Client) (*client.WorkloadIdentityCredentials, error)

NewWorkloadIdentityCredentials builds the credentials that exchange the session's identity token at managementURL. Callers build them once per invocation and share them, so the access token is exchanged once and reused. A nil httpClient uses http.DefaultClient.

func (*Session) ProfileName added in v0.2.0

func (s *Session) ProfileName() string

ProfileName is the stored profile this session uses, or "" when the session is ephemeral or unauthenticated.

func (*Session) RemoteURL added in v0.2.0

func (s *Session) RemoteURL() string

RemoteURL is the remote the resolved session targets. It may be empty, in which case the caller applies its own default.

func (*Session) UsesAPIKey added in v1.1.0

func (s *Session) UsesAPIKey() bool

UsesAPIKey reports whether the session authenticates with an API key, from BASETEN_API_KEY or an API key profile, rather than OAuth.

func (*Session) WorkloadIdentity added in v1.10.0

func (s *Session) WorkloadIdentity() *WorkloadIdentity

WorkloadIdentity returns the session's workload identity configuration, or nil when the session does not authenticate with workload identity.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store manages reading and writing auth.json and keyring secrets.

func NewStore

func NewStore(opts StoreOptions) *Store

NewStore creates a Store from the given options.

func (*Store) ClearDriveToken added in v1.10.0

func (s *Store) ClearDriveToken(ctx context.Context, scope DriveTokenScope) error

ClearDriveToken forgets the token cached for scope, in the keyring and in the plaintext file.

func (*Store) ClearGridTokens added in v1.7.0

func (s *Store) ClearGridTokens(ctx context.Context, scope GridTokenScope) error

ClearGridTokens forgets every token cached for scope.

func (*Store) ClearSandboxToken added in v1.7.0

func (s *Store) ClearSandboxToken(ctx context.Context, scope SandboxTokenScope) error

ClearSandboxToken forgets the token cached for scope, in the keyring and in the plaintext file.

func (*Store) ClearVolumeTokens added in v1.10.0

func (s *Store) ClearVolumeTokens(ctx context.Context, scope VolumeTokenScope) error

ClearVolumeTokens forgets the tokens cached for scope, in the keyring and in the plaintext file.

func (*Store) CurrentProfile added in v0.2.0

func (s *Store) CurrentProfile() (name string, profile Profile, ok bool, err error)

CurrentProfile returns the current profile name and entry. When explicit profile selection is required, it returns an *ErrExplicitProfileRequired instead.

func (*Store) GetAPIKey

func (s *Store) GetAPIKey(ctx context.Context, profileName string) (string, error)

GetAPIKey retrieves the API key for a profile, trying the keyring first, then falling back to the auth.json plaintext field.

func (*Store) GetDriveToken added in v1.10.0

func (s *Store) GetDriveToken(ctx context.Context, scope DriveTokenScope) (*DriveToken, error)

GetDriveToken returns the token cached for scope, or nil. Tries the keyring first, then falls back to the plaintext file. Only ctx's error is returned: a cache that cannot be read is a miss.

func (*Store) GetGridToken added in v1.7.0

func (s *Store) GetGridToken(ctx context.Context, scope GridTokenScope, teamID string) (*GridToken, error)

GetGridToken returns the token cached for scope and teamID, or nil.

func (*Store) GetOAuthCredential

func (s *Store) GetOAuthCredential(ctx context.Context, profileName string) (*OAuthCredential, error)

GetOAuthCredential retrieves the OAuth credential for a profile, trying the keyring first, then falling back to the auth.json plaintext field.

func (*Store) GetProfile added in v0.2.0

func (s *Store) GetProfile(profileName string) (Profile, bool)

GetProfile returns the profile with the given name.

func (*Store) GetRoutesKey added in v1.1.0

func (s *Store) GetRoutesKey(ctx context.Context, scope RoutesKeyScope) (string, error)

GetRoutesKey returns the Grid API key saved for scope, or "" if there is none. Tries the keyring first, then falls back to the auth.json plaintext field.

func (*Store) GetSandboxToken added in v1.7.0

func (s *Store) GetSandboxToken(ctx context.Context, scope SandboxTokenScope) (*SandboxToken, error)

GetSandboxToken returns the token cached for scope, or nil. Tries the keyring first, then falls back to the plaintext file. Only ctx's error is returned: a cache that cannot be read is a miss.

func (*Store) GetVolumeTokens added in v1.10.0

func (s *Store) GetVolumeTokens(ctx context.Context, scope VolumeTokenScope) ([]VolumeToken, error)

GetVolumeTokens returns the tokens cached for scope. Tries the keyring first, then falls back to the plaintext file. Only ctx's error is returned: a cache that cannot be read is empty.

func (*Store) Load

func (s *Store) Load() (*AuthFile, error)

Load reads auth.json from disk. Returns an empty AuthFile if it does not exist.

func (*Store) ProfileNames added in v0.2.0

func (s *Store) ProfileNames() ([]string, error)

ProfileNames returns the stored profile names in sorted order.

func (*Store) RemoveProfile added in v0.2.0

func (s *Store) RemoveProfile(ctx context.Context, profileName string) error

RemoveProfile removes a profile and deletes its keyring entry. If the removed profile was current, the current pointer is cleared.

func (*Store) SetAPIKeyProfile added in v0.2.0

func (s *Store) SetAPIKeyProfile(ctx context.Context, profileName, remoteURL, apiKey string, switchCurrent bool, warnWriter func(string)) error

SetAPIKeyProfile stores an API key credential under name. When switchCurrent is true and explicit profile selection is not required, the profile also becomes the current profile.

func (*Store) SetDriveToken added in v1.10.0

func (s *Store) SetDriveToken(ctx context.Context, scope DriveTokenScope, token DriveToken) error

SetDriveToken caches token. Tries the keyring first; falls back to the plaintext file. Only ctx's error is returned: failing to cache never fails the caller, which still has the token.

func (*Store) SetGridToken added in v1.7.0

func (s *Store) SetGridToken(ctx context.Context, scope GridTokenScope, teamID string, token GridToken, warnWriter func(string)) error

SetGridToken caches token, warning via warnWriter (if non-nil) when the keyring refuses it.

func (*Store) SetOAuthProfile added in v0.2.0

func (s *Store) SetOAuthProfile(ctx context.Context, profileName, remoteURL string, cred OAuthCredential, switchCurrent bool, warnWriter func(string)) error

SetOAuthProfile stores an OAuth credential under name. When switchCurrent is true and explicit profile selection is not required, the profile also becomes the current profile. Tries the keyring first; falls back to plaintext in auth.json with a warning written to warnWriter (if non-nil).

func (*Store) SetRequireExplicitProfile added in v1.8.0

func (s *Store) SetRequireExplicitProfile(required bool) error

SetRequireExplicitProfile enables or disables explicit profile selection. Enabling clears the current profile so disabling later does not revive a stale one.

func (*Store) SetRoutesKey added in v1.1.0

func (s *Store) SetRoutesKey(ctx context.Context, scope RoutesKeyScope, key string, warnWriter func(string)) error

SetRoutesKey saves a Grid API key for scope. Tries the keyring first; falls back to plaintext in auth.json with a warning written to warnWriter (if non-nil).

func (*Store) SetSandboxToken added in v1.7.0

func (s *Store) SetSandboxToken(ctx context.Context, scope SandboxTokenScope, token SandboxToken) error

SetSandboxToken caches token. Tries the keyring first; falls back to the plaintext file. Only ctx's error is returned: failing to cache never fails the caller, which still has the token.

func (*Store) SetVolumeTokens added in v1.10.0

func (s *Store) SetVolumeTokens(ctx context.Context, scope VolumeTokenScope, tokens []VolumeToken) error

SetVolumeTokens replaces the tokens cached for scope. Expired tokens are dropped, then the soonest to expire beyond [maxVolumeTokens], then more of those for as long as the keyring refuses the entry as too big. Tries the keyring first; falls back to the plaintext file. Only ctx's error is returned: failing to cache never fails the caller, which still has its token.

func (*Store) SwitchProfile added in v0.2.0

func (s *Store) SwitchProfile(profileName string) error

SwitchProfile sets the current profile. Returns an error if it does not exist.

type StoreOptions

type StoreOptions struct {
	// Dir is the directory where auth.json is stored.
	Dir string

	// InsecureStorage, when true, stores secrets in auth.json instead of
	// the system keyring.
	InsecureStorage bool
}

StoreOptions configures a Store.

type Transport

type Transport struct {
	Session *Session

	// OAuthConfig is the OAuth2 configuration used for token refresh.
	OAuthConfig *oauth2.Config

	// WorkloadIdentity exchanges and caches access tokens for a workload
	// identity session. Required when the session uses workload identity.
	WorkloadIdentity client.Credentials

	Base http.RoundTripper
	// contains filtered or unexported fields
}

Transport is an HTTP client that injects the appropriate Authorization header for the resolved session. For OAuth credentials, it uses oauth2.TokenSource for transparent token refresh.

It implements the Do(*http.Request) (*http.Response, error) interface expected by the baseten-go SDK clients.

func (*Transport) AccessToken added in v1.10.0

func (t *Transport) AccessToken(ctx context.Context) (client.AccessToken, error)

AccessToken returns a current access token for a workload identity or OAuth session: a workload identity token is exchanged, or reused while cached; an OAuth token is refreshed and persisted when it has expired. API key sessions have no access token and get an error.

func (*Transport) Credential added in v0.4.0

func (t *Transport) Credential(ctx context.Context) (string, error)

Credential resolves the session's credential as a bearer token: an API key verbatim, or an access token from Transport.AccessToken. The backend accepts either kind under the Bearer scheme, which is also the only shape the truss CLI's forwarded credential accepts.

func (*Transport) Do

func (t *Transport) Do(req *http.Request) (*http.Response, error)

type VolumeToken added in v1.10.0

type VolumeToken struct {
	Namespace string   `json:"namespace"`
	Volume    string   `json:"volume"`
	Hosting   string   `json:"hosting,omitempty"`
	Scopes    []string `json:"scopes"`

	Token     string    `json:"token"`
	Endpoint  string    `json:"endpoint"`
	ExpiresAt time.Time `json:"expires_at"`
}

VolumeToken is a cached volume token and what it was requested for.

type VolumeTokenScope added in v1.10.0

type VolumeTokenScope struct {
	ManagementURL string `json:"management_url"`
	Identity      string `json:"identity"`
}

VolumeTokenScope keys the cache by issuing endpoint and Session.CacheIdentity.

type WorkloadIdentity added in v1.10.0

type WorkloadIdentity struct {
	IdentityTokenFile string
	// IdentityToken is the identity token itself. Unlike a file, it cannot be
	// replaced while the CLI runs, so exchanges fail once it expires.
	IdentityToken string
	TrustRuleID   string
}

WorkloadIdentity is the workload identity federation configuration read from the environment. Exactly one of IdentityTokenFile and IdentityToken is set.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL