{"modulePath":"github.com/kernel/kernel-go-sdk","version":"v0.159.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package credentials\n\nPackage credentials implements workload identity federation for the Kernel API: a workload trades a token from its own identity provider (GitHub Actions, AWS, Google Cloud, Kubernetes, any OIDC issuer) for a short-lived Kernel access token instead of storing an API key.\n\nMost callers never use this package directly. A client picks federation up from the environment (KERNEL\\_FEDERATION\\_RULE\\_ID plus an identity-token source), or from [github.com/kernel/kernel-go-sdk/option.WithFederationTokenProvider](/github.com/kernel/kernel-go-sdk/option#WithFederationTokenProvider). The building blocks are exported for callers that manage tokens themselves:\n\n  - [ExchangeFederationAssertion](#ExchangeFederationAssertion) performs one exchange.\n  - [NewFederationProvider](#NewFederationProvider) performs an exchange with a fresh identity token on every call, and [TokenCache](#TokenCache) caches and refreshes the result.\n  - [File](#File), [Static](#Static), [GitHubActions](#GitHubActions) and [GCPMetadata](#GCPMetadata) are identity-token sources. AWS lives in the awssts subpackage so that this package does not depend on the AWS SDK.\n\nIdentity tokens are usually single-use, so nothing here ever sends the same one twice: every exchange asks the source for a fresh token.\n\n## Constants\n\n```go\nconst (\n\t// EnvFederationRuleID turns federation on. It holds the federation rule\n\t// ID (\"wifr_...\").\n\tEnvFederationRuleID = \"KERNEL_FEDERATION_RULE_ID\"\n\t// EnvIdentityTokenSource selects where identity tokens come from:\n\t// github_actions, gcp_metadata, aws_sts, file or env.\n\tEnvIdentityTokenSource = \"KERNEL_IDENTITY_TOKEN_SOURCE\"\n\t// EnvIdentityTokenFile is the path of a file holding the identity token.\n\t// It is read again for every exchange.\n\tEnvIdentityTokenFile = \"KERNEL_IDENTITY_TOKEN_FILE\"\n\t// EnvIdentityToken is a literal identity token. It can be exchanged once.\n\tEnvIdentityToken = \"KERNEL_IDENTITY_TOKEN\"\n\t// EnvIdentityTokenAudience is the audience the built-in sources request.\n\t// It defaults to the auth base URL.\n\tEnvIdentityTokenAudience = \"KERNEL_IDENTITY_TOKEN_AUDIENCE\"\n\t// EnvAuthBaseURL is the Kernel authorization server. It is required with\n\t// a custom API base URL.\n\tEnvAuthBaseURL = \"KERNEL_AUTH_BASE_URL\"\n)\n```\nEnvironment variables that configure workload identity federation.\n\n```go\nconst (\n\t// DefaultAPIBaseURL is the production Kernel API.\n\tDefaultAPIBaseURL = \"https://api.onkernel.com\"\n\t// DefaultAuthBaseURL is the production Kernel authorization server. It is\n\t// used only together with [DefaultAPIBaseURL].\n\tDefaultAuthBaseURL = \"https://auth.onkernel.com\"\n)\n```\n\n```go\nconst (\n\t// Values of KERNEL_IDENTITY_TOKEN_SOURCE.\n\tSourceGitHubActions = \"github_actions\"\n\tSourceGCPMetadata   = \"gcp_metadata\"\n\tSourceAWSSTS        = \"aws_sts\"\n\tSourceFile          = \"file\"\n\tSourceEnv           = \"env\"\n)\n```\n\n## Variables\n\n```go\nvar ErrIdentityTokenConsumed = errors.New(\n\t\"the static identity token was already used: an identity token can be exchanged only once, \" +\n\t\t\"so a fixed value (such as KERNEL_IDENTITY_TOKEN) cannot renew the Kernel access token; \" +\n\t\t\"use KERNEL_IDENTITY_TOKEN_FILE or another source that returns a fresh token for every exchange\")\n```\nErrIdentityTokenConsumed is returned by a [Static](#Static) identity-token source when it is asked for its token a second time.\n\n## Functions\n\n```go\nfunc ClientOption(provider IdentityTokenFunc, opts FederationOptions) requestconfig.RequestOption\n```\nClientOption returns the request option behind [github.com/kernel/kernel-go-sdk/option.WithFederationTokenProvider](/github.com/kernel/kernel-go-sdk/option#WithFederationTokenProvider); see there for how it behaves.\n\n```go\nfunc EnvClientOption() requestconfig.RequestOption\n```\nEnvClientOption returns the request option for the federation settings in the environment (see [FederationFromEnv](#FederationFromEnv)). It does nothing when KERNEL\\_API\\_KEY is set, which takes precedence, or when KERNEL\\_FEDERATION\\_RULE\\_ID is not. A federation setup that is incomplete fails the requests that would have used it.\n\n```go\nfunc FederationFromEnv() (IdentityTokenFunc, FederationOptions, error)\n```\nFederationFromEnv reads the federation settings from the environment: KERNEL\\_FEDERATION\\_RULE\\_ID plus an identity-token source. The source is the one KERNEL\\_IDENTITY\\_TOKEN\\_SOURCE names. Without that variable it is KERNEL\\_IDENTITY\\_TOKEN\\_FILE, then KERNEL\\_IDENTITY\\_TOKEN, then GitHub Actions when the job exposes an OIDC token.\n\nIt returns a nil source and no error when KERNEL\\_FEDERATION\\_RULE\\_ID is not set. It does not look at KERNEL\\_API\\_KEY.\n\n```go\nfunc RegisterIdentityTokenSource(name string, newSource func(audience string) IdentityTokenFunc)\n```\nRegisterIdentityTokenSource makes an identity-token source selectable with KERNEL\\_IDENTITY\\_TOKEN\\_SOURCE=name. It is meant to be called from the init function of a package that the application imports for that purpose, as database/sql drivers are:\n\n\timport _ \"github.com/kernel/kernel-go-sdk/lib/credentials/awssts\"\n\nnewSource receives the configured audience, which is empty when the source should fall back to [ResolveAudience](#ResolveAudience). RegisterIdentityTokenSource panics if newSource is nil or name is already taken.\n\n```go\nfunc ResolveAudience(ctx context.Context, explicit string) (string, error)\n```\nResolveAudience returns the audience an identity token should be issued for: explicit when it is set, else KERNEL\\_IDENTITY\\_TOKEN\\_AUDIENCE, else the URL of the authorization server the token is about to be sent to, which a federation provider passes through ctx (for example \"[https://auth.onkernel.com](https://auth.onkernel.com)\"). The federation rule's expected\\_audience must be set to the same value.\n\nThe built-in sources use it, and a custom [IdentityTokenFunc](#IdentityTokenFunc) can too.\n\n## Types\n\n```go\ntype AccessTokenProvider func(ctx context.Context, forceRefresh bool) (*Token, error)\n```\nAccessTokenProvider mints an access token, usually over the network. Only [Token.AccessToken](#Token.AccessToken) has to be set; a token without [Token.ExpiresAt](#Token.ExpiresAt) is kept by a [TokenCache](#TokenCache) until it is invalidated.\n\nforceRefresh is true on the first call after [TokenCache.Invalidate](#TokenCache.Invalidate): the server has just rejected the previous token, so a provider that keeps its own cache must bypass it. Providers without one can ignore the flag.\n\nA provider must be safe for concurrent use.\n\n```go\nfunc NewFederationProvider(cfg FederationConfig) AccessTokenProvider\n```\nNewFederationProvider returns an [AccessTokenProvider](#AccessTokenProvider) that exchanges an identity token for a Kernel access token. Every call asks cfg.IdentityTokenProvider for a fresh token and makes a new exchange; wrap the provider in a [TokenCache](#TokenCache) to reuse the result.\n\nThe identity-token provider can read the audience its token should carry with [ResolveAudience](#ResolveAudience).\n\n```go\ntype FederationConfig struct {\n\t// IdentityTokenProvider returns a fresh identity token for every\n\t// exchange. Required.\n\tIdentityTokenProvider IdentityTokenFunc\n\t// FederationRuleID is the federation rule (\"wifr_...\") to check the\n\t// identity token against. Required.\n\tFederationRuleID string\n\t// APIBaseURL is the Kernel API the access token will be used with. It\n\t// defaults to [DefaultAPIBaseURL].\n\tAPIBaseURL string\n\t// Resource is the API the token is requested for. It defaults to the\n\t// origin of APIBaseURL, such as \"https://api.onkernel.com\".\n\tResource string\n\t// AuthBaseURL is the Kernel authorization server. It defaults to\n\t// KERNEL_AUTH_BASE_URL, then to [DefaultAuthBaseURL] when APIBaseURL is\n\t// exactly the production API. For any other API it must be set: a custom\n\t// API is never paired with the production authorization server\n\t// implicitly.\n\tAuthBaseURL string\n\t// HTTPClient sends the token requests. It defaults to a client with a 30\n\t// second timeout. An [*http.Client] is used with redirects turned off;\n\t// any other implementation must not redirect or retry a request itself.\n\tHTTPClient HTTPDoer\n\t// UserAgent replaces the SDK's User-Agent header on token requests.\n\tUserAgent string\n}\n```\nFederationConfig configures [NewFederationProvider](#NewFederationProvider).\n\n```go\ntype FederationExchangeParams struct {\n\t// Assertion is the identity token (a JWT) to exchange. Required. Most\n\t// providers issue single-use tokens, so an assertion that was already\n\t// sent, even in a request that failed, must not be sent again.\n\tAssertion string\n\t// FederationRuleID is the federation rule (\"wifr_...\") to check the\n\t// assertion against. Required.\n\tFederationRuleID string\n\t// Resource is the API the token is for, such as \"https://api.onkernel.com\"\n\t// with no trailing slash. When empty the server chooses.\n\tResource string\n\t// AuthBaseURL is the Kernel authorization server. It defaults to\n\t// KERNEL_AUTH_BASE_URL, then to [DefaultAuthBaseURL].\n\tAuthBaseURL string\n\t// HTTPClient sends the request. It defaults to a client with a 30 second\n\t// timeout. An [*http.Client] is used with redirects turned off; any other\n\t// implementation must not redirect or retry the request itself.\n\tHTTPClient HTTPDoer\n\t// UserAgent replaces the SDK's User-Agent header.\n\tUserAgent string\n}\n```\nFederationExchangeParams are the inputs of [ExchangeFederationAssertion](#ExchangeFederationAssertion).\n\n```go\ntype FederationOptions struct {\n\t// FederationRuleID is the federation rule (\"wifr_...\") to check the\n\t// identity token against. Required.\n\tFederationRuleID string\n\t// Resource is the API the token is requested for. It defaults to the\n\t// origin of the client's base URL, such as \"https://api.onkernel.com\".\n\tResource string\n\t// AuthBaseURL is the Kernel authorization server. It defaults to\n\t// KERNEL_AUTH_BASE_URL, then to https://auth.onkernel.com when the client\n\t// talks to the production API. A client with any other base URL must set\n\t// it.\n\tAuthBaseURL string\n}\n```\nFederationOptions configures workload identity federation for a client.\n\n```go\ntype HTTPDoer interface {\n\tDo(*http.Request) (*http.Response, error)\n}\n```\nHTTPDoer sends an HTTP request. [\\*http.Client](/net/http#Client) implements it.\n\n```go\ntype IdentityTokenFunc func(ctx context.Context) (string, error)\n```\nIdentityTokenFunc returns an identity token (a JWT) from the workload's own identity provider. It is called once per exchange and must return a fresh token every time: most providers issue single-use tokens, and Kernel rejects a token it has already seen.\n\nAn IdentityTokenFunc must be safe for concurrent use and must return when ctx is done.\n\n```go\nfunc File(path string) IdentityTokenFunc\n```\nFile returns an identity-token source that reads the token from path on every call, so a token that is rotated on disk, such as a Kubernetes projected service account token, is picked up. Surrounding whitespace is trimmed and an empty file is an error.\n\nBetween rotations every call returns the same token, so the issuer must allow a token to be exchanged more than once, as Kernel does for Kubernetes by default. With a single-use issuer, something has to write a new token to the file before each exchange.\n\n```go\nfunc GCPMetadata(audience string) IdentityTokenFunc\n```\nGCPMetadata returns an identity-token source for Google Cloud (Compute Engine, GKE, Cloud Run, Cloud Functions). It asks the metadata server for an ID token of the default service account on every call.\n\naudience is the aud claim to request; when empty, [ResolveAudience](#ResolveAudience) decides.\n\n```go\nfunc GitHubActions(audience string) IdentityTokenFunc\n```\nGitHubActions returns an identity-token source for a GitHub Actions job. It asks the runner for a new OIDC token on every call, which works for the whole job. The workflow must grant \"permissions: id-token: write\".\n\naudience is the aud claim to request; when empty, [ResolveAudience](#ResolveAudience) decides.\n\n```go\nfunc Static(token string) IdentityTokenFunc\n```\nStatic returns an identity-token source that returns token once per process. Any later call, by this source or by another one made for the same token, fails with [ErrIdentityTokenConsumed](#ErrIdentityTokenConsumed) instead of replaying a token the server would reject. A client built on it works until its first access token expires.\n\n```go\ntype Principal struct {\n\t// Type is \"service_account\".\n\tType string\n\t// ID is the service account ID.\n\tID string\n}\n```\nPrincipal identifies who a [Token](#Token) acts as.\n\n```go\ntype Token struct {\n\t// AccessToken is sent to the Kernel API as \"Authorization: Bearer ...\".\n\tAccessToken string\n\t// ExpiresAt is when the access token stops being valid. A federation\n\t// exchange always sets it; the zero value, from another provider, means\n\t// the expiry is unknown. There is no refresh token: exchange a fresh\n\t// identity token to get a new access token.\n\tExpiresAt time.Time\n\t// Scope lists the granted permissions, separated by spaces.\n\tScope string\n\t// OrgID is the organization the token belongs to.\n\tOrgID string\n\t// AccessScope is \"project\" for a token bound to one project.\n\tAccessScope string\n\t// ProjectID is the project of the federation rule. A request that names\n\t// another project is refused.\n\tProjectID string\n\t// Principal is the service account the token acts as.\n\tPrincipal Principal\n\t// FederationRuleID is the rule that matched the identity token.\n\tFederationRuleID string\n}\n```\nToken is a Kernel access token and what the authorization server said about it. A federation exchange fills in every field.\n\n```go\nfunc ExchangeFederationAssertion(ctx context.Context, params FederationExchangeParams) (*Token, error)\n```\nExchangeFederationAssertion trades an identity token for a Kernel access token in a single request to the authorization server. It needs no Kernel credential.\n\nA refused exchange is reported as a [\\*WorkloadIdentityError](#WorkloadIdentityError).\n\n```go\ntype TokenCache struct {\n\t// contains filtered or unexported fields\n}\n```\nTokenCache caches the token of an [AccessTokenProvider](#AccessTokenProvider) and refreshes it before it expires.\n\n  - With plenty of lifetime left, [TokenCache.Token](#TokenCache.Token) returns the cached token.\n  - In the advisory window it still returns the cached token and starts a refresh in the background. A failed background refresh is dropped and not repeated for a few seconds.\n  - In the mandatory window, or with no token, it waits for a refresh and returns its error if it fails.\n\nConcurrent callers share one refresh, and the provider is never called twice at the same time. A TokenCache is safe for concurrent use.\n\n```go\nfunc NewTokenCache(provider AccessTokenProvider) *TokenCache\n```\nNewTokenCache returns a [TokenCache](#TokenCache) that gets its tokens from provider.\n\n```go\nfunc (c *TokenCache) Invalidate()\n```\nInvalidate drops the cached token, so the next [TokenCache.Token](#TokenCache.Token) call fetches a new one. Call it when the server rejects the token.\n\n```go\nfunc (c *TokenCache) Token(ctx context.Context) (*Token, error)\n```\nToken returns a valid access token, refreshing it first when needed.\n\nCancelling ctx stops the wait, not the refresh: other callers may be waiting on the same refresh, and the identity token it spent cannot be used again.\n\n```go\ntype WorkloadIdentityError struct {\n\t// StatusCode is the HTTP status of the token endpoint's response. It is 0\n\t// when the failure happened before a response arrived.\n\tStatusCode int\n\t// Code is the OAuth error code, such as \"invalid_grant\".\n\tCode string\n\t// Description is the OAuth error_description.\n\tDescription string\n\t// ErrorURI is the OAuth error_uri.\n\tErrorURI string\n\t// RequestID identifies the token request in Kernel's logs, when the\n\t// response carried one.\n\tRequestID string\n\t// Hint suggests a fix for a failure with a well-known cause.\n\tHint string\n\t// Message describes a failure that has no OAuth error.\n\tMessage string\n\t// Err is the underlying error, if any.\n\tErr error\n\t// contains filtered or unexported fields\n}\n```\nWorkloadIdentityError reports a failure to obtain a Kernel access token through workload identity federation: a misconfiguration, an identity-token source that failed, or a token endpoint that refused the exchange.\n\n```go\nfunc (e *WorkloadIdentityError) Error() string\n```\n\n```go\nfunc (e *WorkloadIdentityError) Unwrap() error\n```\n\n","path":"github.com/kernel/kernel-go-sdk/lib/credentials","name":"credentials","synopsis":"Package credentials implements workload identity federation for the Kernel API: a workload trades a token from its own identity provider (GitHub Actions, AWS, Google Cloud, Kubernetes, any OIDC issuer) for a short-lived Kernel access token instead of storing an API key.","isRedistributable":true}
