cloudidentity

package
v0.6.12 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package cloudidentity makes sandboxd an OIDC issuer for its sandboxes (plans/sandbox-cloud-identity.md). Code inside a sandbox gets a short-lived token signed by the deployment's key; the customer's cloud (AWS IAM, Azure federated credentials, GCP workload identity federation) trusts the published public keys and swaps the token for its own short-lived credentials. This is the IRSA / Workload Identity model without Kubernetes.

The package is a leaf: key generation, the key set and its rotation rules, the JWKS and discovery documents, the claim set and signing. It never seals, stores or replicates anything (internal/service does, through the store or the Raft FSM) and it never logs. The verifying half of OIDC, for other issuers' tokens, is internal/identity.

Security invariants this package carries (design section 7):

  • RS256 with RSA-2048 only (D1.2): the one algorithm AWS, GCP and Azure all accept. A key under 2048 bits is refused when parsed.
  • The private key is never serialised except by MarshalPrivateKey, whose only caller seals the result. KeyRecord holds the sealed bytes.
  • The subject is built only by Subject, from an owner ref and a role tag that ValidateRoleTag accepted; neither can carry ':' unescaped, so one owner's subject can never be read as another's (point 6).
  • Lifetime is fixed: nbf = issue - 60 s, exp = issue + 1 h (point 7).

Index

Constants

View Source
const (
	// Algorithm is the only signing algorithm (D1.2).
	Algorithm = "RS256"
	// KeyBits is the RSA modulus size of a generated key, and the floor a
	// parsed key must meet.
	KeyBits = 2048
	// RetiredKeyPublishedFor is how long a rotated-out key stays in the
	// JWKS: twice the token lifetime, so every token it signed expires
	// first, with an hour to spare for clouds that cache the JWKS.
	RetiredKeyPublishedFor = 2 * time.Hour
	// MaxKeys bounds the key set, active key included. Each rotation adds
	// one key and the retired ones drop out after RetiredKeyPublishedFor,
	// so only a rotation loop reaches it; past it a rotation is refused
	// rather than growing the replicated state.
	MaxKeys = 8
)
View Source
const (
	// TokenLifetime is how long a token is valid (point 7). A stolen token
	// gives its role for at most this long (point 2).
	TokenLifetime = time.Hour
	// NotBeforeSkew backdates nbf so a cloud whose clock runs behind ours
	// still accepts a fresh token (point 7).
	NotBeforeSkew = 60 * time.Second
	// DefaultAudience is the AWS STS audience: AWS is the first target (Q2).
	DefaultAudience = "sts.amazonaws.com"
	// DiscoveryPath and JWKSPath are served at the issuer's root, where
	// every cloud looks for them.
	DiscoveryPath = "/.well-known/openid-configuration"
	JWKSPath      = "/.well-known/jwks.json"
	// TokenDir and TokenFile are where toolboxd writes the token inside the
	// sandbox.
	TokenDir  = "/run/aerolvm/identity"
	TokenFile = TokenDir + "/token"
	// MaxTokenBytes bounds a token on the wire to toolboxd.
	MaxTokenBytes = 16 << 10
)
View Source
const (
	EnvTokenFile      = "AEROLVM_IDENTITY_TOKEN_FILE"
	EnvAWSTokenFile   = "AWS_WEB_IDENTITY_TOKEN_FILE"
	EnvAWSRoleARN     = "AWS_ROLE_ARN"
	EnvAzureTokenFile = "AZURE_FEDERATED_TOKEN_FILE"
	EnvAzureClientID  = "AZURE_CLIENT_ID"
	EnvAzureTenantID  = "AZURE_TENANT_ID"
)

The environment a sandbox with an identity gets (D1.6). Each cloud SDK finds the token through its own variable, with no code change inside.

Variables

View Source
var (
	// ErrKeySetInvalid is a key set that breaks an invariant: more than one
	// active key, a repeated key id, too many keys, or a public key that does
	// not match its id.
	ErrKeySetInvalid = errors.New("cloudidentity: invalid signing key set")
	// ErrTooManyKeys is a rotation that would hold more than MaxKeys keys.
	ErrTooManyKeys = fmt.Errorf("%w: too many keys; wait for rotated keys to expire (2 hours) before rotating again", ErrKeySetInvalid)
	// ErrWeakKey is a private key under KeyBits.
	ErrWeakKey = errors.New("cloudidentity: signing key is weaker than RSA-2048")
)
View Source
var (
	// ErrInvalid is a malformed identity request or role tag (400).
	ErrInvalid = errors.New("invalid identity")
	// ErrIssuerURL is a bad SB_IDENTITY_ISSUER_URL.
	ErrIssuerURL = errors.New("SB_IDENTITY_ISSUER_URL must be an https URL with no path, query or fragment")
)

Functions

func Discovery

func Discovery(issuer string) ([]byte, error)

Discovery is the OIDC discovery document of issuer. The clouds read only issuer, jwks_uri and the algorithms; the rest is what OIDC discovery requires so a strict client accepts it.

func GenerateKey

func GenerateKey(rand io.Reader) (*rsa.PrivateKey, error)

GenerateKey makes a new RSA-2048 signing key.

func JWKS

func JWKS(keys []KeyRecord) ([]byte, error)

JWKS is the public key set document of keys.

func KeyID

func KeyID(pub *rsa.PublicKey) (string, error)

KeyID is the key's RFC 7638 thumbprint, base64url: stable for a key, so every node derives the same id, and the JWKS never names one key twice.

func MarshalPrivateKey

func MarshalPrivateKey(key *rsa.PrivateKey) ([]byte, error)

MarshalPrivateKey is the private key as PKCS#8 DER, for the caller to seal at once. It is the only place the private key leaves memory.

func ParsePrivateKey

func ParsePrivateKey(der []byte) (*rsa.PrivateKey, error)

ParsePrivateKey reads what MarshalPrivateKey wrote, after the caller opened the seal.

func PublicJWK

func PublicJWK(pub *rsa.PublicKey, kid string) (json.RawMessage, error)

PublicJWK is the JWKS entry of pub under kid.

func SealAAD

func SealAAD(kid string) []byte

SealAAD binds a sealed private key to its key id, so one key's sealed bytes cannot be swapped in under another key's id.

func Subject

func Subject(ownerRef, roleTag string) string

Subject is the sub claim: what a customer's trust policy matches (D1.4).

func SubjectOwner

func SubjectOwner(ownerRef string) (owner, team string)

SubjectOwner is the owner part of the subject and the team claim for an owner ref. A team (owner "team:<name>", names are a-z, 0-9 and '-') reads "team:<name>"; the operator namespace (owner "") reads "operator"; any other owner (a managed account key) reads "account:<key>" with every byte outside A-Z, a-z, 0-9, '.' and '-' percent-escaped. The three forms cannot overlap and escaping is one-to-one, so distinct owners never share a subject (point 6).

func ValidMinRole

func ValidMinRole(r string) bool

ValidMinRole reports whether r may be a role tag's minimum caller role: runner or admin, the two roles that can create a sandbox at all (viewer and auditor cannot). runner is the role the design calls "developer".

func ValidateAudience

func ValidateAudience(aud string) error

ValidateAudience accepts 1-256 printable ASCII characters with no space. The audience is the sandbox's own choice: it does not take part in the trust decision on our side, only the cloud's.

func ValidateIssuerURL

func ValidateIssuerURL(raw string) (string, error)

ValidateIssuerURL returns the canonical issuer (no trailing slash). The clouds fetch <issuer>/.well-known/openid-configuration anonymously over public HTTPS and Azure compares iss byte for byte, so it must be HTTPS, carry a host, and have no path: the documents are served at the root.

func ValidateRoleTag

func ValidateRoleTag(tag string) error

ValidateRoleTag accepts 1-63 characters of a-z, 0-9, '-' and '_', starting with a letter or digit. No ':' can appear, so the tag cannot extend the subject past its own field.

Types

type Claims

type Claims struct {
	Issuer    string `json:"iss"`
	Subject   string `json:"sub"`
	Audience  string `json:"aud"`
	IssuedAt  int64  `json:"iat"`
	NotBefore int64  `json:"nbf"`
	Expiry    int64  `json:"exp"`
	ID        string `json:"jti"`
	Sandbox   string `json:"sandbox"`
	Team      string `json:"team,omitempty"`
	Role      string `json:"role"`
}

Claims is the token's claim set (D1.4).

func Verify

func Verify(raw string, jwks []byte, now time.Time) (Claims, error)

Verify checks raw against a JWKS document and returns its claims. sandboxd never needs it on the request path (only the sandbox receives a token); tests, the cluster check that a token one node signed verifies with the JWKS another node serves, and the live suite use it.

type IssueRequest

type IssueRequest struct {
	Issuer    string
	OwnerRef  string
	SandboxID string
	RoleTag   string
	Audience  string
	Now       time.Time
	// Rand is the jti source; nil is crypto/rand.
	Rand io.Reader
}

IssueRequest is what one token says.

type KeyRecord

type KeyRecord struct {
	ID              string          `json:"kid"`
	SealedPrivate   []byte          `json:"sealed_private"`
	PublicJWK       json.RawMessage `json:"public_jwk"`
	CreatedUnixNano int64           `json:"created_unix_nano"`
	// RetiredUnixNano is when a rotation replaced this key; 0 while it is
	// the active key.
	RetiredUnixNano int64 `json:"retired_unix_nano,omitempty"`
}

KeyRecord is one signing key at rest: the private half sealed by the caller (never in the clear here), the public half as a JWK, and its life. It is what the store and the Raft FSM hold.

func NewKeyRecord

func NewKeyRecord(key *rsa.PrivateKey, now time.Time, seal func(plain, aad []byte) ([]byte, error)) (KeyRecord, error)

NewKeyRecord builds the record of a freshly generated key: its id, its public JWK and the private key sealed by seal (which is given the AAD to bind). The plaintext DER is wiped once sealed.

func (KeyRecord) Active

func (r KeyRecord) Active() bool

Active reports whether r is the key that signs.

func (KeyRecord) Clone

func (r KeyRecord) Clone() KeyRecord

Clone copies r's byte slices.

func (KeyRecord) PublishedAt

func (r KeyRecord) PublishedAt(now time.Time) bool

PublishedAt reports whether r belongs in the JWKS at now.

type KeySet

type KeySet struct {
	Generation int64       `json:"generation"`
	Keys       []KeyRecord `json:"keys"`
}

KeySet is the deployment's signing keys. Generation counts writes: a writer names the generation it read and the write applies only if it is still current, so two nodes that both find no key, or both rotate, cannot both win.

func (KeySet) Active

func (s KeySet) Active() (KeyRecord, bool)

Active returns the key that signs.

func (KeySet) Clone

func (s KeySet) Clone() KeySet

Clone copies s deeply.

func (KeySet) Published

func (s KeySet) Published(now time.Time) []KeyRecord

Published returns the keys the JWKS lists at now, active key first.

func (KeySet) Rotate

func (s KeySet) Rotate(next KeyRecord, now time.Time) (KeySet, error)

Rotate returns s with next as the active key: the current active key is retired at now, and retired keys whose JWKS window has passed are dropped. Generation is left to the writer. next must be active.

func (KeySet) Validate

func (s KeySet) Validate() error

Validate checks the invariants every writer and the FSM apply rely on. An empty set is valid: it is the state before the first key.

type Request

type Request struct {
	RoleTag       string `json:"role_tag"`
	Audience      string `json:"audience,omitempty"`
	AWSRoleARN    string `json:"aws_role_arn,omitempty"`
	AzureClientID string `json:"azure_client_id,omitempty"`
	AzureTenantID string `json:"azure_tenant_id,omitempty"`
}

Request is the create option (D1.6).

func (Request) Env

func (r Request) Env() map[string]string

Env is the environment the request gives the sandbox.

func (Request) Normalize

func (r Request) Normalize() Request

Normalize trims every field and fills the default audience.

func (Request) Validate

func (r Request) Validate() error

Validate checks a normalized request. The Azure ids come as a pair: one without the other gives an SDK half a configuration.

type Signer

type Signer struct {
	KeyID string
	Key   *rsa.PrivateKey
}

Signer signs with one key.

func (Signer) Issue

func (s Signer) Issue(req IssueRequest) (Token, error)

Issue signs a token for one sandbox.

type Token

type Token struct {
	Raw    string
	KeyID  string
	Claims Claims
}

Token is a signed token and what the audit record names (D1.10). Raw is the bearer credential: it goes to toolboxd and nowhere else.

func (Token) Expires

func (t Token) Expires() time.Time

Expires is the token's exp.

Jump to

Keyboard shortcuts

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