auth

package
v0.17.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// LabelAgentTask is the metadata label identifying the associated AgentTask.
	LabelAgentTask = "divergedev.com/agent-task"
	// LabelRevoked is the metadata label marking a token secret as revoked.
	LabelRevoked = "divergedev.com/revoked"
	// ManagedByLabel is the standard Kubernetes management label.
	ManagedByLabel = "app.kubernetes.io/managed-by"
	// TokenIndexSecretName is the fixed Secret name per namespace used to index active
	// AgentTask capability tokens so diverge-server RBAC can restrict Secret reads via resourceNames.
	TokenIndexSecretName = "diverge-agenttask-tokens"
)
View Source
const MinMacaroonRootKeyLen = 32

MinMacaroonRootKeyLen is the minimum required length in bytes for a Macaroon HMAC root key.

Variables

View Source
var (
	ErrInvalidSignature = errors.New("invalid token signature")
	ErrTokenExpired     = errors.New("token has expired")
	ErrCaveatFailed     = errors.New("caveat check failed")
	ErrInvalidCaveat    = ErrCaveatFailed
	ErrMalformedToken   = errors.New("malformed token")
)
View Source
var (
	// ErrTokenNotFound is returned when a requested capability token does not exist in the store.
	ErrTokenNotFound = errors.New("token not found")
	// ErrTokenRevoked is returned when attempting to retrieve or verify a revoked capability token.
	ErrTokenRevoked = errors.New("token has been revoked")
)
View Source
var ModelTiers = map[string][]string{
	"smart": {
		"gemini-2.5-pro",
		"claude-3-7-sonnet",
	},
	"fast": {
		"gemini-2.5-flash",
		"gpt-4o-mini",
	},
	"lite": {
		"gemini-flash-lite",
	},
}

ModelTiers maps capability tier names to recommended underlying model identifiers.

Functions

func ResolveModelTier

func ResolveModelTier(tier string) []string

ResolveModelTier looks up default model names for a capability tier.

func SecretName

func SecretName(taskID string) string

SecretName returns the deterministic Kubernetes Secret name for an AgentTask capability token.

func TaskLabelValue

func TaskLabelValue(taskID string) string

TaskLabelValue returns a Kubernetes-valid label value (<= 63 chars) for an AgentTask identifier.

Types

type Attenuator

type Attenuator interface {
	Attenuate(ctx context.Context, token Token, caveats ...Caveat) (Token, error)
}

Attenuator appends restrictive caveats to an existing token without re-contacting the issuer.

type AuthEvent

type AuthEvent struct {
	Type      AuthEventType `json:"type"`
	TaskID    string        `json:"task_id"`
	Namespace string        `json:"namespace"`
	Principal string        `json:"principal"`
	Success   bool          `json:"success"`
	Reason    string        `json:"reason,omitempty"`
	Timestamp time.Time     `json:"timestamp"`
}

AuthEvent records a security-sensitive capability event for auditing and compliance.

type AuthEventType

type AuthEventType string

AuthEventType defines the category of security/capability events.

const (
	EventMint      AuthEventType = "mint"
	EventAttenuate AuthEventType = "attenuate"
	EventVerify    AuthEventType = "verify"
	EventRevoke    AuthEventType = "revoke"
)

type Caveat

type Caveat struct {
	Key   string   `json:"key"`
	Op    CaveatOp `json:"op"`
	Value string   `json:"value"`
}

Caveat represents a restriction appended to a token.

type CaveatOp

type CaveatOp string

CaveatOp defines operators for checking caveats.

const (
	OpEqual    CaveatOp = "="
	OpIn       CaveatOp = "in"
	OpLessThan CaveatOp = "<"
	OpBefore   CaveatOp = "before"
	OpGlob     CaveatOp = "glob"
)

type CaveatValidator

type CaveatValidator interface {
	Validate(ctx context.Context, caveat Caveat, claims Claims) error
}

CaveatValidator evaluates caveats against token claims with strict fail-closed typing.

type Claims

type Claims struct {
	TaskID         string    `json:"task_id"`
	Namespace      string    `json:"namespace,omitempty"`
	RepoURL        string    `json:"repo_url"`
	Branch         string    `json:"branch"`
	AllowedTools   []string  `json:"allowed_tools,omitempty"`
	AllowedModels  []string  `json:"allowed_models,omitempty"`
	MaxCostUSD     float64   `json:"max_cost_usd,omitempty"`
	MaxTokens      int64     `json:"max_tokens,omitempty"`
	TokensConsumed int64     `json:"tokens_consumed,omitempty"`
	ExpiresAt      time.Time `json:"expires_at"`
}

Claims encapsulates the authorized attributes of an AgentTask token.

type CredentialBroker

type CredentialBroker interface {
	BrokerCredentials(ctx context.Context, repoURL string) (*VCSCredentials, error)
}

CredentialBroker supplies short-lived VCS credentials for git clone operations.

type InMemoryTokenStore

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

InMemoryTokenStore provides an in-memory, thread-safe implementation of TokenStore. Ideal for unit tests, local CLI mock mode, and standalone testing.

func NewInMemoryTokenStore

func NewInMemoryTokenStore() *InMemoryTokenStore

NewInMemoryTokenStore initializes a thread-safe InMemoryTokenStore.

func (*InMemoryTokenStore) DeleteToken

func (s *InMemoryTokenStore) DeleteToken(_ context.Context, taskID, namespace string) error

DeleteToken removes the token from storage.

func (*InMemoryTokenStore) GetToken

func (s *InMemoryTokenStore) GetToken(_ context.Context, taskID, namespace string) ([]byte, error)

GetToken retrieves the token or returns ErrTokenNotFound/ErrTokenRevoked.

func (*InMemoryTokenStore) IsRevoked

func (s *InMemoryTokenStore) IsRevoked(_ context.Context, taskID, namespace string) bool

IsRevoked checks if the token has been marked revoked.

func (*InMemoryTokenStore) RevokeToken

func (s *InMemoryTokenStore) RevokeToken(_ context.Context, taskID, namespace string) error

RevokeToken marks the token as revoked.

func (*InMemoryTokenStore) SaveToken

func (s *InMemoryTokenStore) SaveToken(_ context.Context, taskID, namespace string, token []byte) error

SaveToken persists the raw token bytes.

type KubernetesSecretTokenStore

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

KubernetesSecretTokenStore implements TokenStore using Kubernetes corev1.Secret resources.

func NewKubernetesSecretTokenStore

func NewKubernetesSecretTokenStore(c client.Client, scheme *runtime.Scheme) *KubernetesSecretTokenStore

NewKubernetesSecretTokenStore initializes a KubernetesSecretTokenStore.

func (*KubernetesSecretTokenStore) DeleteToken

func (s *KubernetesSecretTokenStore) DeleteToken(ctx context.Context, taskID, namespace string) error

DeleteToken removes the token Secret and clears its entry in TokenIndexSecretName.

func (*KubernetesSecretTokenStore) GetToken

func (s *KubernetesSecretTokenStore) GetToken(ctx context.Context, taskID, namespace string) ([]byte, error)

GetToken reads the token from the Kubernetes Secret (or from TokenIndexSecretName when indexOnly is enabled).

func (*KubernetesSecretTokenStore) IsRevoked

func (s *KubernetesSecretTokenStore) IsRevoked(ctx context.Context, taskID, namespace string) bool

IsRevoked inspects whether the token Secret (or TokenIndexSecretName when indexOnly is enabled) is marked revoked.

func (*KubernetesSecretTokenStore) RevokeToken

func (s *KubernetesSecretTokenStore) RevokeToken(ctx context.Context, taskID, namespace string) error

RevokeToken marks the token Secret and TokenIndexSecretName entry as revoked.

func (*KubernetesSecretTokenStore) SaveToken

func (s *KubernetesSecretTokenStore) SaveToken(ctx context.Context, taskID, namespace string, token []byte) error

SaveToken creates or updates the <task-name>-token Kubernetes Secret and syncs the namespace token index.

func (*KubernetesSecretTokenStore) WithIndexOnly

WithIndexOnly configures the store to read token state exclusively from the namespace-scoped TokenIndexSecretName ("diverge-agenttask-tokens") Secret, allowing callers like diverge-server to operate with RBAC restricted via resourceNames.

type LoggerTokenAuditor

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

LoggerTokenAuditor logs audit events to structured logger.

func NewLoggerTokenAuditor

func NewLoggerTokenAuditor(logger *slog.Logger) *LoggerTokenAuditor

NewLoggerTokenAuditor constructs a LoggerTokenAuditor.

func (*LoggerTokenAuditor) RecordEvent

func (a *LoggerTokenAuditor) RecordEvent(_ context.Context, event AuthEvent) error

RecordEvent logs an AuthEvent.

type Macaroon

type Macaroon struct {
	TokenID   string   `json:"id"`
	Location  string   `json:"location"`
	CaveatSeq []Caveat `json:"caveats"`
	Signature string   `json:"signature"` // hex-encoded
}

Macaroon implements Token using HMAC-SHA256 caveat chaining.

func (*Macaroon) Caveats

func (m *Macaroon) Caveats() []Caveat

Caveats returns the ordered caveat chain embedded in the Macaroon.

func (*Macaroon) ID

func (m *Macaroon) ID() string

ID returns the Macaroon's task identifier.

func (*Macaroon) Serialize

func (m *Macaroon) Serialize() ([]byte, error)

Serialize encodes the Macaroon as JSON bytes.

type MacaroonProvider

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

MacaroonProvider implements Minter, Attenuator, and Verifier.

func NewMacaroonProvider

func NewMacaroonProvider(rootKey []byte) *MacaroonProvider

NewMacaroonProvider initializes a provider with a 32-byte secret root key.

func (*MacaroonProvider) Attenuate

func (p *MacaroonProvider) Attenuate(_ context.Context, token Token, caveats ...Caveat) (Token, error)

Attenuate appends additional caveats to an existing token.

func (*MacaroonProvider) Mint

func (p *MacaroonProvider) Mint(_ context.Context, claims Claims) (Token, error)

Mint creates a fresh root Macaroon.

func (*MacaroonProvider) Verify

func (p *MacaroonProvider) Verify(_ context.Context, raw []byte, required Claims) error

Verify validates that the signature chain is intact and all caveats hold true.

func (*MacaroonProvider) VerifyAndExtract

func (p *MacaroonProvider) VerifyAndExtract(_ context.Context, raw []byte) (*Macaroon, Claims, error)

VerifyAndExtract validates the cryptographic HMAC chain, expiration, and caveat syntax of a serialized Macaroon and extracts the effective Claims embedded in its caveat sequence.

type Minter

type Minter interface {
	Mint(ctx context.Context, claims Claims) (Token, error)
}

Minter creates root authorization tokens for AgentTasks.

type NoopTokenAuditor

type NoopTokenAuditor struct{}

NoopTokenAuditor discards audit events.

func (*NoopTokenAuditor) RecordEvent

func (a *NoopTokenAuditor) RecordEvent(_ context.Context, _ AuthEvent) error

RecordEvent discards the provided AuthEvent and returns nil.

type Provider

type Provider interface {
	Minter
	Attenuator
	Verifier
}

Provider combines token issuance, attenuation, and verification capabilities.

type Token

type Token interface {
	ID() string
	Serialize() ([]byte, error)
	Caveats() []Caveat
}

Token represents a cryptographic credential that can be serialized and attenuated.

type TokenAuditor

type TokenAuditor interface {
	RecordEvent(ctx context.Context, event AuthEvent) error
}

TokenAuditor is an interface for streaming authentication/authorization events to an audit sink.

type TokenStore

type TokenStore interface {
	SaveToken(ctx context.Context, taskID, namespace string, token []byte) error
	GetToken(ctx context.Context, taskID, namespace string) ([]byte, error)
	DeleteToken(ctx context.Context, taskID, namespace string) error
	RevokeToken(ctx context.Context, taskID, namespace string) error
	IsRevoked(ctx context.Context, taskID, namespace string) bool
}

TokenStore manages persistence, lookup, and revocation of capability tokens.

type VCSCredentials

type VCSCredentials struct {
	Username string
	Token    string
	AuthType string // "bearer", "basic", "ssh"
}

VCSCredentials encapsulates short-lived repository access credentials.

type Verifier

type Verifier interface {
	Verify(ctx context.Context, raw []byte, required Claims) error
}

Verifier checks token validity, signature chain, and required caveats.

Jump to

Keyboard shortcuts

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