credentials

package
v0.158.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 15 Imported by: ? 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

Overview

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.

Most 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. The building blocks are exported for callers that manage tokens themselves:

Identity tokens are usually single-use, so nothing here ever sends the same one twice: every exchange asks the source for a fresh token.

Index

Constants

View Source
const (
	// EnvFederationRuleID turns federation on. It holds the federation rule
	// ID ("wifr_...").
	EnvFederationRuleID = "KERNEL_FEDERATION_RULE_ID"
	// EnvIdentityTokenSource selects where identity tokens come from:
	// github_actions, gcp_metadata, aws_sts, file or env.
	EnvIdentityTokenSource = "KERNEL_IDENTITY_TOKEN_SOURCE"
	// EnvIdentityTokenFile is the path of a file holding the identity token.
	// It is read again for every exchange.
	EnvIdentityTokenFile = "KERNEL_IDENTITY_TOKEN_FILE"
	// EnvIdentityToken is a literal identity token. It can be exchanged once.
	EnvIdentityToken = "KERNEL_IDENTITY_TOKEN"
	// EnvIdentityTokenAudience is the audience the built-in sources request.
	// It defaults to the auth base URL.
	EnvIdentityTokenAudience = "KERNEL_IDENTITY_TOKEN_AUDIENCE"
	// EnvAuthBaseURL is the Kernel authorization server. It is required with
	// a custom API base URL.
	EnvAuthBaseURL = "KERNEL_AUTH_BASE_URL"
)

Environment variables that configure workload identity federation.

View Source
const (
	// DefaultAPIBaseURL is the production Kernel API.
	DefaultAPIBaseURL = "https://api.onkernel.com"
	// DefaultAuthBaseURL is the production Kernel authorization server. It is
	// used only together with [DefaultAPIBaseURL].
	DefaultAuthBaseURL = "https://auth.onkernel.com"
)
View Source
const (
	// Values of KERNEL_IDENTITY_TOKEN_SOURCE.
	SourceGitHubActions = "github_actions"
	SourceGCPMetadata   = "gcp_metadata"
	SourceAWSSTS        = "aws_sts"
	SourceFile          = "file"
	SourceEnv           = "env"
)

Variables

View Source
var ErrIdentityTokenConsumed = errors.New(
	"the static identity token was already used: an identity token can be exchanged only once, " +
		"so a fixed value (such as KERNEL_IDENTITY_TOKEN) cannot renew the Kernel access token; " +
		"use KERNEL_IDENTITY_TOKEN_FILE or another source that returns a fresh token for every exchange")

ErrIdentityTokenConsumed is returned by a Static identity-token source when it is asked for its token a second time.

Functions

func ClientOption

ClientOption returns the request option behind github.com/kernel/kernel-go-sdk/option.WithFederationTokenProvider; see there for how it behaves.

func EnvClientOption

func EnvClientOption() requestconfig.RequestOption

EnvClientOption returns the request option for the federation settings in the environment (see 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.

func FederationFromEnv

func FederationFromEnv() (IdentityTokenFunc, FederationOptions, error)

FederationFromEnv 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.

It returns a nil source and no error when KERNEL_FEDERATION_RULE_ID is not set. It does not look at KERNEL_API_KEY.

func RegisterIdentityTokenSource

func RegisterIdentityTokenSource(name string, newSource func(audience string) IdentityTokenFunc)

RegisterIdentityTokenSource 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:

import _ "github.com/kernel/kernel-go-sdk/lib/credentials/awssts"

newSource receives the configured audience, which is empty when the source should fall back to ResolveAudience. RegisterIdentityTokenSource panics if newSource is nil or name is already taken.

func ResolveAudience

func ResolveAudience(ctx context.Context, explicit string) (string, error)

ResolveAudience 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"). The federation rule's expected_audience must be set to the same value.

The built-in sources use it, and a custom IdentityTokenFunc can too.

Types

type AccessTokenProvider

type AccessTokenProvider func(ctx context.Context, forceRefresh bool) (*Token, error)

AccessTokenProvider mints an access token, usually over the network. Only Token.AccessToken has to be set; a token without Token.ExpiresAt is kept by a TokenCache until it is invalidated.

forceRefresh is true on the first call after 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.

A provider must be safe for concurrent use.

func NewFederationProvider

func NewFederationProvider(cfg FederationConfig) AccessTokenProvider

NewFederationProvider returns an 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 to reuse the result.

The identity-token provider can read the audience its token should carry with ResolveAudience.

type FederationConfig

type FederationConfig struct {
	// IdentityTokenProvider returns a fresh identity token for every
	// exchange. Required.
	IdentityTokenProvider IdentityTokenFunc
	// FederationRuleID is the federation rule ("wifr_...") to check the
	// identity token against. Required.
	FederationRuleID string
	// APIBaseURL is the Kernel API the access token will be used with. It
	// defaults to [DefaultAPIBaseURL].
	APIBaseURL string
	// Resource is the API the token is requested for. It defaults to the
	// origin of APIBaseURL, such as "https://api.onkernel.com".
	Resource string
	// AuthBaseURL is the Kernel authorization server. It defaults to
	// KERNEL_AUTH_BASE_URL, then to [DefaultAuthBaseURL] when APIBaseURL is
	// exactly the production API. For any other API it must be set: a custom
	// API is never paired with the production authorization server
	// implicitly.
	AuthBaseURL string
	// HTTPClient sends the token requests. It defaults to a client with a 30
	// second timeout. An [*http.Client] is used with redirects turned off;
	// any other implementation must not redirect or retry a request itself.
	HTTPClient HTTPDoer
	// UserAgent replaces the SDK's User-Agent header on token requests.
	UserAgent string
}

FederationConfig configures NewFederationProvider.

type FederationExchangeParams

type FederationExchangeParams struct {
	// Assertion is the identity token (a JWT) to exchange. Required. Most
	// providers issue single-use tokens, so an assertion that was already
	// sent, even in a request that failed, must not be sent again.
	Assertion string
	// FederationRuleID is the federation rule ("wifr_...") to check the
	// assertion against. Required.
	FederationRuleID string
	// Resource is the API the token is for, such as "https://api.onkernel.com"
	// with no trailing slash. When empty the server chooses.
	Resource string
	// AuthBaseURL is the Kernel authorization server. It defaults to
	// KERNEL_AUTH_BASE_URL, then to [DefaultAuthBaseURL].
	AuthBaseURL string
	// HTTPClient sends the request. It defaults to a client with a 30 second
	// timeout. An [*http.Client] is used with redirects turned off; any other
	// implementation must not redirect or retry the request itself.
	HTTPClient HTTPDoer
	// UserAgent replaces the SDK's User-Agent header.
	UserAgent string
}

FederationExchangeParams are the inputs of ExchangeFederationAssertion.

type FederationOptions

type FederationOptions struct {
	// FederationRuleID is the federation rule ("wifr_...") to check the
	// identity token against. Required.
	FederationRuleID string
	// Resource is the API the token is requested for. It defaults to the
	// origin of the client's base URL, such as "https://api.onkernel.com".
	Resource string
	// AuthBaseURL is the Kernel authorization server. It defaults to
	// KERNEL_AUTH_BASE_URL, then to https://auth.onkernel.com when the client
	// talks to the production API. A client with any other base URL must set
	// it.
	AuthBaseURL string
}

FederationOptions configures workload identity federation for a client.

type HTTPDoer

type HTTPDoer interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPDoer sends an HTTP request. *http.Client implements it.

type IdentityTokenFunc

type IdentityTokenFunc func(ctx context.Context) (string, error)

IdentityTokenFunc 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.

An IdentityTokenFunc must be safe for concurrent use and must return when ctx is done.

func File

func File(path string) IdentityTokenFunc

File 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.

Between 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.

func GCPMetadata

func GCPMetadata(audience string) IdentityTokenFunc

GCPMetadata 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.

audience is the aud claim to request; when empty, ResolveAudience decides.

func GitHubActions

func GitHubActions(audience string) IdentityTokenFunc

GitHubActions 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".

audience is the aud claim to request; when empty, ResolveAudience decides.

func Static

func Static(token string) IdentityTokenFunc

Static 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 instead of replaying a token the server would reject. A client built on it works until its first access token expires.

type Principal

type Principal struct {
	// Type is "service_account".
	Type string
	// ID is the service account ID.
	ID string
}

Principal identifies who a Token acts as.

type Token

type Token struct {
	// AccessToken is sent to the Kernel API as "Authorization: Bearer ...".
	AccessToken string
	// ExpiresAt is when the access token stops being valid. A federation
	// exchange always sets it; the zero value, from another provider, means
	// the expiry is unknown. There is no refresh token: exchange a fresh
	// identity token to get a new access token.
	ExpiresAt time.Time
	// Scope lists the granted permissions, separated by spaces.
	Scope string
	// OrgID is the organization the token belongs to.
	OrgID string
	// AccessScope is "project" for a token bound to one project.
	AccessScope string
	// ProjectID is the project of the federation rule. A request that names
	// another project is refused.
	ProjectID string
	// Principal is the service account the token acts as.
	Principal Principal
	// FederationRuleID is the rule that matched the identity token.
	FederationRuleID string
}

Token is a Kernel access token and what the authorization server said about it. A federation exchange fills in every field.

func ExchangeFederationAssertion

func ExchangeFederationAssertion(ctx context.Context, params FederationExchangeParams) (*Token, error)

ExchangeFederationAssertion trades an identity token for a Kernel access token in a single request to the authorization server. It needs no Kernel credential.

A refused exchange is reported as a *WorkloadIdentityError.

type TokenCache

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

TokenCache caches the token of an AccessTokenProvider and refreshes it before it expires.

  • With plenty of lifetime left, TokenCache.Token returns the cached token.
  • 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.
  • In the mandatory window, or with no token, it waits for a refresh and returns its error if it fails.

Concurrent callers share one refresh, and the provider is never called twice at the same time. A TokenCache is safe for concurrent use.

func NewTokenCache

func NewTokenCache(provider AccessTokenProvider) *TokenCache

NewTokenCache returns a TokenCache that gets its tokens from provider.

func (*TokenCache) Invalidate

func (c *TokenCache) Invalidate()

Invalidate drops the cached token, so the next TokenCache.Token call fetches a new one. Call it when the server rejects the token.

func (*TokenCache) Token

func (c *TokenCache) Token(ctx context.Context) (*Token, error)

Token returns a valid access token, refreshing it first when needed.

Cancelling 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.

type WorkloadIdentityError

type WorkloadIdentityError struct {
	// StatusCode is the HTTP status of the token endpoint's response. It is 0
	// when the failure happened before a response arrived.
	StatusCode int
	// Code is the OAuth error code, such as "invalid_grant".
	Code string
	// Description is the OAuth error_description.
	Description string
	// ErrorURI is the OAuth error_uri.
	ErrorURI string
	// RequestID identifies the token request in Kernel's logs, when the
	// response carried one.
	RequestID string
	// Hint suggests a fix for a failure with a well-known cause.
	Hint string
	// Message describes a failure that has no OAuth error.
	Message string
	// Err is the underlying error, if any.
	Err error
	// contains filtered or unexported fields
}

WorkloadIdentityError 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.

func (*WorkloadIdentityError) Error

func (e *WorkloadIdentityError) Error() string

func (*WorkloadIdentityError) Unwrap

func (e *WorkloadIdentityError) Unwrap() error

Directories

Path Synopsis
Package awssts provides an identity-token source for workloads running on AWS (ECS, Lambda, EC2, EKS): it asks AWS STS for a web identity token of the workload's IAM role with GetWebIdentityToken.
Package awssts provides an identity-token source for workloads running on AWS (ECS, Lambda, EC2, EKS): it asks AWS STS for a web identity token of the workload's IAM role with GetWebIdentityToken.

Jump to

Keyboard shortcuts

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