cloud

package
v0.0.0-...-c685235 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultAppName is the shared keychain application name used by all SafeDep tools.
	DefaultAppName = "safedep"

	// DefaultProfile is the default credential profile name.
	DefaultProfile = "default"
)
View Source
const ProfileEnvVar = "SAFEDEP_PROFILE"

ProfileEnvVar names the environment variable that selects the credential profile when the caller has no explicit profile.

View Source
const WorkloadIdentityAudience = "sts.safedep.io"

WorkloadIdentityAudience is the audience that SafeDep Cloud requires in a workload identity token.

Variables

View Source
var (
	// ErrInvalidCredentialType is returned when credentials don't match the
	// expected type for the client (e.g., API key for control plane).
	ErrInvalidCredentialType = errors.New("cloud: invalid credential type for this client")

	// ErrMissingCredentials is returned when required credential fields are empty.
	ErrMissingCredentials = errors.New("cloud: missing required credentials")

	// ErrIncompleteCredentials is returned when a source holds one half of a
	// credential pair, for example an API key with no tenant. It wraps
	// ErrMissingCredentials, so existing errors.Is checks still match.
	ErrIncompleteCredentials = fmt.Errorf("cloud: incomplete credentials: %w", ErrMissingCredentials)

	// ErrWorkloadCredential is returned by Credentials.GetAPIKey for
	// workload identity credentials. They hold no fixed API key: the access
	// token comes from an exchange and expires. Use Credentials.Workload. It
	// wraps ErrInvalidCredentialType.
	ErrWorkloadCredential = fmt.Errorf("cloud: workload identity credentials have no fixed API key, use Workload: %w",
		ErrInvalidCredentialType)
)
View Source
var ErrNoWorkloadIdentity = errors.New("cloud: no workload identity in the environment")

ErrNoWorkloadIdentity is returned when the environment has no workload identity, for example a GitHub Actions job without "id-token: write".

View Source
var ErrWorkloadCredentialRevoked = errors.New("cloud: the workload credential is revoked")

ErrWorkloadCredentialRevoked is returned by a RefreshingWorkloadCredential after Revoke.

Functions

func ResolveProfile

func ResolveProfile(explicit string) string

ResolveProfile returns the credential profile that SafeDep tools use: explicit (usually a --profile flag value) when it is set, else SAFEDEP_PROFILE, else DefaultProfile.

Types

type Client

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

Client is a connection to SafeDep Cloud.

func NewControlPlaneClient

func NewControlPlaneClient(name string, creds *Credentials) (*Client, error)

NewControlPlaneClient creates a connection to cloud.safedep.io (JWT auth).

func NewDataPlaneClient

func NewDataPlaneClient(name string, creds *Credentials) (*Client, error)

NewDataPlaneClient creates a connection to api.safedep.io (API key auth).

func (*Client) Close

func (c *Client) Close() error

Close closes the connection.

func (*Client) Connection

func (c *Client) Connection() *grpc.ClientConn

Connection returns the underlying gRPC client connection.

type CloseableCredentialResolver

type CloseableCredentialResolver interface {
	CredentialResolver
	io.Closer
}

CloseableCredentialResolver combines CredentialResolver with io.Closer for resolvers that own underlying resources.

func NewDefaultCredentialResolver

func NewDefaultCredentialResolver(credType CredentialType, opts ...KeychainOption) (CloseableCredentialResolver, error)

NewDefaultCredentialResolver returns the resolver chain that SafeDep tools share, so that one sign-in serves every tool.

For CredentialTypeAPIKey it reads SAFEDEP_API_KEY and SAFEDEP_TENANT_ID first. Then it reads the keychain profile from ResolveProfile. A WithProfile option replaces that profile.

SAFEDEP_TENANT_ID with no SAFEDEP_API_KEY selects the workload identity of the environment, such as a GitHub Actions job with "id-token: write". The credentials then exchange the workload identity token for a workload credential, with the source CredentialSourceWorkloadIdentity. Each Resolve returns the same workload identity credentials. An explicit SAFEDEP_API_KEY always takes precedence, and a SAFEDEP_API_KEY that is set to an empty value is ErrIncompleteCredentials, so that a missing secret does not silently select the exchange.

A source that holds half a credential stops the chain with ErrIncompleteCredentials, so a typo in one variable does not silently select another tenant from the keychain.

A keychain that cannot open does not fail construction. The environment still works on a machine with no keychain, and Resolve reports the keychain error only when the environment has no credentials.

func NewKeychainCredentialResolver

func NewKeychainCredentialResolver(credType CredentialType, opts ...KeychainOption) (CloseableCredentialResolver, error)

NewKeychainCredentialResolver creates a credential resolver backed by the keychain. The credType parameter specifies which credential type to resolve.

type CredentialResolver

type CredentialResolver interface {
	Resolve() (*Credentials, error)
}

CredentialResolver resolves SafeDep Cloud credentials.

func NewChainCredentialResolver

func NewChainCredentialResolver(resolvers ...CredentialResolver) CredentialResolver

NewChainCredentialResolver tries resolvers in order, returning the first successful result.

func NewEnvCredentialResolver

func NewEnvCredentialResolver() (CredentialResolver, error)

NewEnvCredentialResolver creates a resolver that reads from SAFEDEP_API_KEY and SAFEDEP_TENANT_ID environment variables.

type CredentialSource

type CredentialSource int

CredentialSource identifies where a resolver found credentials.

const (
	CredentialSourceUnspecified CredentialSource = iota
	CredentialSourceEnvironment
	CredentialSourceKeychain

	// CredentialSourceWorkloadIdentity marks a workload credential that the
	// resolver gets from an exchange of the workload identity token, such as
	// a GitHub Actions OIDC token.
	CredentialSourceWorkloadIdentity
)

func (CredentialSource) String

func (s CredentialSource) String() string

type CredentialStore

type CredentialStore interface {
	SaveAPIKeyCredential(apiKey, tenantDomain string) error
	SaveTokenCredential(token, refreshToken, tenantDomain string) error
	Clear() error
	io.Closer
}

CredentialStore writes SafeDep Cloud credentials to the keychain.

func NewKeychainCredentialStore

func NewKeychainCredentialStore(opts ...KeychainOption) (CredentialStore, error)

NewKeychainCredentialStore creates a credential store backed by the keychain.

type CredentialType

type CredentialType int

CredentialType identifies the authentication plane.

const (
	CredentialTypeUnspecified CredentialType = iota
	CredentialTypeAPIKey                     // Data plane (api.safedep.io)
	CredentialTypeToken                      // Control plane (cloud.safedep.io)
)

type Credentials

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

Credentials holds SafeDep Cloud authentication details. Fields are private. Use constructors to create, getters to access.

func NewAPIKeyCredential

func NewAPIKeyCredential(apiKey, tenantDomain string) (*Credentials, error)

NewAPIKeyCredential creates data plane credentials. Returns error if apiKey is empty.

func NewTokenCredential

func NewTokenCredential(token, refreshToken, tenantDomain string) (*Credentials, error)

NewTokenCredential creates control plane credentials. Returns error if token is empty.

func NewWorkloadIdentityCredential

func NewWorkloadIdentityCredential(w *RefreshingWorkloadCredential) (*Credentials, error)

NewWorkloadIdentityCredential creates data plane credentials from a workload credential that refreshes itself. The tenant is the tenant of w.

func (*Credentials) GetAPIKey

func (c *Credentials) GetAPIKey() (string, error)

GetAPIKey returns the API key. Errors if not data plane credentials.

Workload identity credentials hold no fixed API key, so GetAPIKey returns ErrWorkloadCredential for them and makes no network call. Use Workload.

func (*Credentials) GetRefreshToken

func (c *Credentials) GetRefreshToken() (string, error)

GetRefreshToken returns the refresh token. Errors if not control plane credentials.

func (*Credentials) GetTenantDomain

func (c *Credentials) GetTenantDomain() (string, error)

GetTenantDomain returns the tenant domain. Returns error if empty.

func (*Credentials) GetToken

func (c *Credentials) GetToken() (string, error)

GetToken returns the access token. Errors if not control plane credentials.

func (*Credentials) IsControlPlane

func (c *Credentials) IsControlPlane() bool

IsControlPlane returns true if these are control plane credentials.

func (*Credentials) IsDataPlane

func (c *Credentials) IsDataPlane() bool

IsDataPlane returns true if these are data plane credentials.

func (*Credentials) Source

func (c *Credentials) Source() CredentialSource

Source returns where a resolver found the credentials. Credentials built directly with a constructor return CredentialSourceUnspecified.

func (*Credentials) Workload

func (c *Credentials) Workload() (w *RefreshingWorkloadCredential, ok bool)

Workload returns the workload credential of workload identity credentials. Pass it to grpc.WithPerRPCCredentials on a connection that the caller dials, and call its Revoke when the job ends. ok is false for other credentials.

type KeychainOption

type KeychainOption func(*keychainConfig)

KeychainOption configures keychain-based credential store and resolver.

func WithAppName

func WithAppName(name string) KeychainOption

WithAppName overrides the default application name for the keychain.

func WithInsecureFileFallback

func WithInsecureFileFallback() KeychainOption

WithInsecureFileFallback enables plaintext file storage when the OS keychain is unavailable.

func WithInsecureFileFallbackPath

func WithInsecureFileFallbackPath(path string) KeychainOption

WithInsecureFileFallbackPath sets a custom file path for the insecure file fallback. Implies WithInsecureFileFallback.

func WithKeychainHandle

func WithKeychainHandle(kc keychain.Keychain) KeychainOption

WithKeychainHandle injects an existing keychain instance. The caller owns the lifecycle (Close) when this option is used.

func WithProfile

func WithProfile(profile string) KeychainOption

WithProfile selects a named credential profile. Defaults to "default". Empty or whitespace-only values are normalized to DefaultProfile.

type RefreshingWorkloadCredential

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

RefreshingWorkloadCredential is a gRPC per-RPC credential that holds a workload credential and exchanges again before it expires. It sends the credential in the authorization header and the tenant in x-tenant-id.

It exchanges on the first RPC, not at construction. One exchange runs at a time, outside the lock, so a slow exchange never blocks an RPC that holds a valid credential. A caller with no valid credential waits for the exchange or for its own context. A failed exchange holds for workloadRefreshRetryDelay: callers with no valid credential get its error, and callers with a valid credential keep it until it expires. So a job that can no longer get an ID token works to the end of the credential life.

func NewRefreshingWorkloadCredential

func NewRefreshingWorkloadCredential(client *WorkloadExchangeClient, source WorkloadIdentitySource,
	req WorkloadExchangeRequest) *RefreshingWorkloadCredential

NewRefreshingWorkloadCredential returns a credential that exchanges a token from source with client.

func (*RefreshingWorkloadCredential) AccessToken

func (r *RefreshingWorkloadCredential) AccessToken(ctx context.Context) (string, error)

AccessToken returns a valid access token. It starts an exchange when the holder has no credential, or when the credential is close to its expiry.

func (*RefreshingWorkloadCredential) GetRequestMetadata

func (r *RefreshingWorkloadCredential) GetRequestMetadata(ctx context.Context, _ ...string) (map[string]string, error)

GetRequestMetadata implements credentials.PerRPCCredentials.

func (*RefreshingWorkloadCredential) GoString

func (r *RefreshingWorkloadCredential) GoString() string

GoString keeps the access token out of %#v.

func (*RefreshingWorkloadCredential) RequireTransportSecurity

func (r *RefreshingWorkloadCredential) RequireTransportSecurity() bool

RequireTransportSecurity implements credentials.PerRPCCredentials.

func (*RefreshingWorkloadCredential) Revoke

Revoke revokes the current credential. Later calls to AccessToken fail with ErrWorkloadCredentialRevoked, and no new exchange starts. Revoke waits for an exchange in flight, or for ctx, so that it revokes the credential of that exchange too. When Revoke fails, a later call tries again. A credential that an earlier refresh replaced is not revoked: it expires within the refresh margin.

func (*RefreshingWorkloadCredential) String

String describes the credential without its access token.

func (*RefreshingWorkloadCredential) TenantDomain

func (r *RefreshingWorkloadCredential) TenantDomain() string

TenantDomain returns the tenant that the credential is for.

type WorkloadCredential

type WorkloadCredential struct {
	AccessToken     string
	ExpiresAt       time.Time
	TenantDomain    string
	EndpointID      string
	CredentialID    string
	DisplayIdentity string
}

WorkloadCredential is a short-lived credential from ExchangeToken. Send AccessToken as an API key. Do not write AccessToken to a log. String omits it.

func (WorkloadCredential) GoString

func (c WorkloadCredential) GoString() string

GoString keeps the access token out of %#v.

func (WorkloadCredential) String

func (c WorkloadCredential) String() string

String describes the credential without its access token.

type WorkloadExchangeClient

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

WorkloadExchangeClient trades a workload identity token for a workload credential, and revokes a workload credential. Every SafeDep tool uses it, so that each tool exchanges the same way.

func NewWorkloadExchangeClient

func NewWorkloadExchangeClient(conn grpc.ClientConnInterface) *WorkloadExchangeClient

NewWorkloadExchangeClient returns an exchange client on conn. The WorkloadIdentityService is keyless: conn must send no API key and no JWT, or the server refuses the call.

func (*WorkloadExchangeClient) Exchange

Exchange gets a new token from source and trades it for a workload credential with the grant TOOL. It gets a new token for each exchange, because the server accepts a token one time only and a GitHub Actions ID token lives 5 minutes.

func (*WorkloadExchangeClient) Revoke

Revoke revokes cred at once. The server also succeeds for a credential that is already revoked or expired.

type WorkloadExchangeRequest

type WorkloadExchangeRequest struct {
	// TenantDomain is the tenant that the credential is for. Required.
	TenantDomain string

	// Lifetime is the life that the workload asks for, at most 6 hours. Zero
	// takes the maximum of the workload trust rule.
	Lifetime time.Duration

	// ToolName and ToolVersion name the tool that asks, as in "vet". The
	// server writes them to its log of the exchange. Both are optional.
	ToolName    string
	ToolVersion string
}

WorkloadExchangeRequest holds what a workload asks for in an exchange.

type WorkloadIdentitySource

type WorkloadIdentitySource interface {
	Token(ctx context.Context, audience string) (WorkloadToken, error)
}

WorkloadIdentitySource gets a token that a platform signs for the running workload, such as a GitHub Actions OIDC ID token.

Token returns a new token for each call. The exchange accepts a token one time only, so a caller must not keep a token for a later exchange.

func DetectWorkloadIdentitySource

func DetectWorkloadIdentitySource() (WorkloadIdentitySource, error)

DetectWorkloadIdentitySource returns the workload identity source of the environment. It returns an error that wraps ErrNoWorkloadIdentity when the environment has none. When a platform sets only part of its variables, the error names the missing one. It makes no network call.

func NewGitHubActionsSource

func NewGitHubActionsSource() (WorkloadIdentitySource, error)

NewGitHubActionsSource returns the source of GitHub Actions OIDC ID tokens. It reads ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN. It returns ErrNoWorkloadIdentity when neither is set, and an error that wraps ErrNoWorkloadIdentity and names the missing one when one is set.

The request URL must use https, because the request carries the request token. INSECURE_GRPC_CLIENT_USE_INSECURE_TRANSPORT, the switch for local development, also allows http.

type WorkloadToken

type WorkloadToken struct {
	Value string
	Type  controltowerv1.SubjectTokenType
}

WorkloadToken is a token that a platform signs for the running workload. Do not write Value to a log. String and GoString leave it out.

func (WorkloadToken) GoString

func (t WorkloadToken) GoString() string

GoString keeps the token value out of %#v.

func (WorkloadToken) String

func (t WorkloadToken) String() string

String describes the token without its value.

Directories

Path Synopsis
Package configsync fetches the resolved policy of an endpoint from SafeDep Cloud and keeps it in a local cache.
Package configsync fetches the resolved policy of an endpoint from SafeDep Cloud and keeps it in a local cache.

Jump to

Keyboard shortcuts

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