workloadid

package
v0.0.0-...-4819cfd Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 20 Imported by: 1

Documentation

Overview

Package workloadid mints and verifies Miren workload identity tokens.

Every Miren cluster is its own OIDC issuer. Code running in a sandbox can ask the cluster for a short-lived JWT scoped to some audience, and whoever receives that token can check it against the cluster's published keys. This package holds both halves so services stop carrying their own copies:

  • Minting: Minter asks the sandbox's token server for a token, and Keeper keeps one audience's token fresh in the background.
  • Verifying: Verifier checks a token from one of a fixed set of trusted clusters, built on Validator, which verifies any OIDC issuer.

Miren uses this package in its own services. You're welcome to use it too, but it lives under x/ because its API may change between versions.

Index

Constants

View Source
const (
	// EnvTokenURL is the sandbox's token server endpoint.
	EnvTokenURL = "MIREN_IDENTITY_TOKEN_URL"
	// EnvTokenSecret is the bearer secret the token server expects from this
	// sandbox. Anything holding it can mint the sandbox's identity, so don't
	// pass it on to child processes that don't need it.
	EnvTokenSecret = "MIREN_IDENTITY_TOKEN_SECRET"
	// EnvTokenPath is a file holding a token for [APIAudience], kept fresh by
	// the cluster.
	EnvTokenPath = "MIREN_IDENTITY_TOKEN_PATH"
)

The environment a sandbox is given for minting its own tokens.

View Source
const APIAudience = "miren"

APIAudience is the audience of the identity token mounted into every sandbox, and the only one a cluster's own API accepts. Tokens for anything else should be minted with that service's own audience.

Variables

This section is empty.

Functions

func BearerToken

func BearerToken(r *http.Request) (string, error)

BearerToken returns the token from r's "Authorization: Bearer" header.

func PeekIssuer

func PeekIssuer(token string) (string, error)

PeekIssuer reads a token's iss claim without verifying anything. The value is only good for choosing which issuer to verify against; it means nothing until that issuer's keys have verified the token.

Types

type Claims

type Claims struct {
	jwt.RegisteredClaims
	OrganizationID string `json:"organization_id,omitempty"`
	ClusterID      string `json:"cluster_id,omitempty"`
	App            string `json:"app,omitempty"`
	// Service is the service within App that holds the token, such as "web".
	// The cluster sets it from the sandbox; the workload cannot choose it.
	// Authorize a particular service by checking App and Service together.
	// Don't confuse it with the audience, which names who the token is for.
	// Empty on system tokens, on sandboxes outside any service, and on tokens
	// from clusters that predate the claim.
	Service      string       `json:"service,omitempty"`
	SandboxID    string       `json:"sandbox_id"`
	IdentityType IdentityType `json:"identity_type,omitempty"`
	// SystemWorkload names the Miren-owned workload a system token identifies,
	// such as "telemetrywriter". Empty on sandbox tokens.
	SystemWorkload string `json:"system_workload,omitempty"`
	// Role is the authorization role the cluster resolved for the sandbox's
	// app. Only sandbox tokens carry it.
	Role string `json:"role,omitempty"`
}

Claims is the payload of a Miren workload identity token.

type IdentityType

type IdentityType string

IdentityType names the kind of principal a token represents.

const (
	// IdentityTypeSandbox is a customer workload running in a sandbox.
	IdentityTypeSandbox IdentityType = "sandbox"
	// IdentityTypeSystem is a Miren-owned workload, named by SystemWorkload.
	IdentityTypeSystem IdentityType = "system"
)

type Keeper

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

Keeper keeps a token for one audience fresh in the background, for code that presents the same token over and over (a proxy adding a header, a file a binary re-reads).

Code that needs a token now and then, such as to exchange it for something else, is better served calling Minter.Mint each time.

func NewKeeper

func NewKeeper(m *Minter, audience string, ttl time.Duration, logger *slog.Logger) *Keeper

NewKeeper returns a Keeper that mints tokens for audience lasting about ttl. It holds no token until Keeper.Refresh or Keeper.Run gets one.

func (*Keeper) Audience

func (k *Keeper) Audience() string

Audience is the audience this Keeper mints for.

func (*Keeper) OnUpdate

func (k *Keeper) OnUpdate(fn func(string))

OnUpdate registers fn to be called with every token minted after this call.

func (*Keeper) Refresh

func (k *Keeper) Refresh(ctx context.Context) error

Refresh mints a new token now and installs it. Call it once before handing the Keeper's token to anything, so a sandbox that can't mint fails at startup rather than on first use.

func (*Keeper) Run

func (k *Keeper) Run(ctx context.Context)

Run refreshes the token until ctx is done. It mints immediately if there is no token yet, then again at half of each token's remaining lifetime, so a briefly unreachable token server has the other half to come back. Failures back off and retry rather than giving up.

func (*Keeper) Token

func (k *Keeper) Token() string

Token returns the current token, or "" if none has been minted yet.

type Minter

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

Minter gets workload identity tokens for the sandbox it runs in.

func NewMinter

func NewMinter(cfg MinterConfig) (*Minter, error)

NewMinter returns a Minter for cfg, which needs a TokenURL or a TokenPath.

func NewMinterFromEnv

func NewMinterFromEnv() (*Minter, error)

NewMinterFromEnv is NewMinter(MinterConfigFromEnv()).

func (*Minter) Mint

func (m *Minter) Mint(ctx context.Context, audience string, ttl time.Duration) (string, error)

Mint returns a token for audience that lives for about ttl. The cluster clamps ttl to between a minute and a day; zero asks for its default of an hour. An empty audience means APIAudience.

Without a token server, Mint can only return the mounted token, which is for APIAudience alone, so asking it for any other audience is an error rather than a token the receiver would refuse.

type MinterConfig

type MinterConfig struct {
	// TokenURL is the token server endpoint. Required for any audience
	// other than APIAudience.
	TokenURL string
	// TokenSecret is sent as a bearer token to TokenURL.
	TokenSecret string
	// TokenPath is the mounted APIAudience token, used when TokenURL is unset.
	TokenPath string
	// HTTPClient makes token server requests. The default has a 15 second
	// timeout.
	HTTPClient *http.Client
}

MinterConfig says where a Minter gets tokens. A sandbox's environment carries all three values; see MinterConfigFromEnv.

func MinterConfigFromEnv

func MinterConfigFromEnv() MinterConfig

MinterConfigFromEnv reads a MinterConfig from the sandbox environment.

type Validator

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

Validator verifies OIDC JWTs from any issuer, fetching and caching each issuer's discovery document and key set.

It knows nothing about which issuers to trust; callers pass the issuer they expect on every call. For Miren workload identity tokens, use Verifier, which adds a trusted-issuer list and Miren's claims on top.

func NewValidator

func NewValidator(opts ...ValidatorOption) *Validator

NewValidator returns a Validator with an empty cache.

func (*Validator) Validate

func (v *Validator) Validate(ctx context.Context, token, issuer, audience string, claims jwt.Claims) error

Validate checks that token was signed by issuer, has not expired, and names audience, then decodes its claims into claims (a jwt.MapClaims or a struct embedding jwt.RegisteredClaims).

An unknown key ID or bad signature triggers one refetch of the issuer's key set, since that is what a key rotation looks like, but no more than once a minute per issuer.

type ValidatorOption

type ValidatorOption func(*Validator)

ValidatorOption configures a Validator.

func RequireKeyID

func RequireKeyID() ValidatorOption

RequireKeyID refuses tokens without a kid header. Without it, a token with no kid is checked against the issuer's only key, or a key whose algorithm matches, which some third-party issuers rely on.

func WithHTTPClient

func WithHTTPClient(c *http.Client) ValidatorOption

WithHTTPClient sets the client used to fetch discovery documents and key sets. The default has a 10 second timeout.

type Verifier

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

Verifier checks Miren workload identity tokens from a fixed set of trusted clusters.

func NewVerifier

func NewVerifier(cfg VerifierConfig) (*Verifier, error)

NewVerifier validates cfg and returns a Verifier.

func (*Verifier) Verify

func (v *Verifier) Verify(ctx context.Context, token string) (*Claims, error)

Verify checks a token and returns its claims.

The issuer is read from the token before anything is verified, because it decides which key set the signature is checked against. That value is untrusted: it only selects one of the issuers already in the trusted set, and a token naming any other issuer is refused without a network call.

func (*Verifier) VerifyRequest

func (v *Verifier) VerifyRequest(r *http.Request) (*Claims, error)

VerifyRequest verifies the bearer token in r's Authorization header.

type VerifierConfig

type VerifierConfig struct {
	// TrustedIssuers are the issuer URLs of the clusters whose tokens are
	// accepted. They must be exact URLs, never patterns; see
	// RequireOrganization for why.
	TrustedIssuers []string

	// Audience is the value callers must mint their tokens for: this service.
	Audience string

	// RequireOrganization, when set, also requires the token's
	// organization_id to match.
	//
	// While TrustedIssuers is a list of exact URLs this is defence in depth.
	// Each issuer belongs to one cluster, which belongs to one organization,
	// so pinning the issuer already pins the organization. That stops being
	// true the moment the trusted set holds a pattern or a shared multi-tenant
	// anchor, and then this check is the one doing the work.
	RequireOrganization string

	// Validator does the underlying verification. Leave it nil for a fresh
	// one that requires a kid header; pass one to share its key cache or
	// HTTP client.
	Validator *Validator
}

VerifierConfig describes who a Verifier is and whom it trusts.

Jump to

Keyboard shortcuts

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