admission

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 26 Imported by: 0 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 admission is the controller side of admission: it receives an agent's request over NATS, and admits, rejects or revokes its key.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAgentKeyNotFound means no key is stored for the machine ID. During
	// a rollout this is expected: no agent accepted before the store
	// existed has one.
	ErrAgentKeyNotFound = errors.New("no stored key for agent")

	// ErrNoPendingAgent means no enrollment request is waiting under the name
	// the caller gave. The API answers 404: there is nothing there to accept or
	// reject.
	ErrNoPendingAgent = errors.New("no pending agent")

	// ErrNoAcceptedAgent means no accepted agent has the hostname, or the
	// hostname and machine ID, the caller gave. The API answers 404.
	ErrNoAcceptedAgent = errors.New("no accepted agent")

	// ErrAgentKeyStoreUnavailable means the record could not be read or
	// decoded. It never resembles "no stored key", and is never treated as
	// verified.
	ErrAgentKeyStoreUnavailable = errors.New("agent key store unavailable")

	// ErrAgentKeySignatureMismatch means a key that is not this agent's
	// signed the message.
	ErrAgentKeySignatureMismatch = errors.New("agent signature mismatch")
)

The three causes of a failed lookup stay distinct so an operator can tell "this agent has not re-enrolled yet" from "something is forging messages" from "the store could not be read". Collapsing them hides the difference at exactly the moment it matters.

View Source
var (
	// ErrFingerprintMismatch is the answer to an admit whose fingerprint is
	// not the one the machine requested with: the operator is not looking
	// at the machine that asked.
	ErrFingerprintMismatch = errors.New("fingerprint does not match the request")

	// ErrNotFound is the answer to a get for a machine that osapi has no
	// record of.
	ErrNotFound = errors.New("no admission record")
)
View Source
var ErrJoinEncryptionKey = errors.New("the join request has no valid P-256 encryption key")

ErrJoinEncryptionKey is a join request whose encryption key is not a public P-256 key in pki.EncryptionKeyEncoding, such as the X25519 key of an older agent.

View Source
var ErrJoinSignature = errors.New("the join request is not signed by its key")

ErrJoinSignature is a join request whose signature is not by the key that it asks the controller to admit.

View Source
var ErrNoJoinTokens = errors.New("this controller takes no join")

ErrNoJoinTokens is a controller with no store of join tokens.

Functions

This section is empty.

Types

type AcceptedAgent

type AcceptedAgent struct {
	MachineID string            `json:"machine_id"`
	Hostname  string            `json:"hostname"`
	PublicKey ed25519.PublicKey `json:"public_key"`
	// EncryptionKey is the agent's public P-256 key, in
	// pki.EncryptionKeyEncoding. The
	// fingerprint covers it and PublicKey. A record admitted before agents
	// had one has none: that agent enrolls again.
	EncryptionKey string    `json:"encryption_key,omitempty"`
	Fingerprint   string    `json:"fingerprint"`
	AcceptedAt    time.Time `json:"accepted_at"`
	// JoinToken is the ID of the join token that admitted the agent, or
	// empty when an operator or auto_admit admitted it.
	JoinToken string `json:"join_token,omitempty"`
	// JoinLabels are the labels of that join token, which the agent took.
	JoinLabels map[string]string `json:"join_labels,omitempty"`
	// NATSUserKey is the public key (U...) of the agent's own NATS user,
	// which it sent at its join. A NATS server's auth callout admits a
	// connection with this key, and no other, as this agent.
	NATSUserKey string `json:"nats_user_key,omitempty"`

	// SupersededKey is the key replaced by the most recent rotation. It is
	// absent unless a rotation is inside its grace period.
	SupersededKey ed25519.PublicKey `json:"superseded_key,omitempty"`

	// SupersededUntil is the instant the superseded key stops being
	// accepted. Storing the instant rather than a duration means a restart
	// cannot silently extend the window.
	SupersededUntil time.Time `json:"superseded_until,omitempty"`
}

AcceptedAgent is the stored record of an accepted agent's public key. It outlives the pending record, which is deleted on acceptance, so every later message from that agent can be verified against the key the agent enrolled with.

Only enrollment acceptance creates a record. Only an acceptance, or a rotation that the recorded key signed (ServeRotate), replaces its keys: nothing else that an agent sends may introduce or change one.

type AgentKeyStore

type AgentKeyStore interface {
	LookupAgentKey(
		ctx context.Context,
		machineID string,
	) (*AcceptedAgent, error)
}

AgentKeyStore is the narrow lookup the verification callers depend on, so the job client and target resolution need not import this package wholesale. Satisfied by *Watcher.

type AgentUser

type AgentUser func(req pki.JoinRequest) (pki.JoinNATS, error)

AgentUser is the NATS user that a join gives the agent of req: one user for each agent, or in operator mode a JWT for the agent's own user key.

func StaticUser

func StaticUser(
	user pki.JoinNATS,
) AgentUser

StaticUser is the AgentUser that gives each agent user.

type CalloutRoles

type CalloutRoles struct {
	// Join is the permissions of a connection with a join token.
	Join bus.Permissions
	// Agent is the permissions of an admitted agent.
	Agent bus.Permissions
	// AgentTTL is how long an agent's connection lasts before the server
	// asks the callout again, or zero for as long as it stays connected.
	AgentTTL time.Duration
	// Tokens checks a join token.
	Tokens TokenChecker
}

CalloutRoles are what the auth callout gives each kind of connection.

type JoinListener

type JoinListener func(
	subject string,
	queue string,
	handler nats.MsgHandler,
) (*nats.Subscription, error)

JoinListener subscribes handler to subject in queue: the QueueSubscribe of the controller's NATS connection.

type JoinTokens

type JoinTokens interface {
	Consume(ctx context.Context, token string) (jointoken.Token, error)
}

JoinTokens takes a use of a join token: the store of join tokens.

type KVStore

type KVStore interface {
	KVGet(ctx context.Context, bucket string, key string) (jetstream.KeyValueEntry, error)
	KVPut(ctx context.Context, bucket string, key string, value []byte) (uint64, error)
	KVDelete(ctx context.Context, bucket string, key string) error
	KVKeys(ctx context.Context, bucket string, filters ...string) ([]string, error)
}

KVStore reads and writes the enrollment KV bucket. A *natsclient.Client is one.

type Mint

type Mint func(userKey string, machineID string) (string, error)

Mint is a JWT for the NATS user key of an admitted machine.

type NATSSubscriber

type NATSSubscriber interface {
	Subscribe(
		ctx context.Context,
		subject string,
		handler natsclient.MsgHandler,
	) (*nats.Subscription, error)
	PublishCore(ctx context.Context, subject string, data []byte) error
}

NATSSubscriber is the core NATS messaging of the enrollment watcher: it receives the enrollment requests and publishes the answers. A *natsclient.Client is one.

type PKIProvider

type PKIProvider interface {
	PublicKey() ed25519.PublicKey
}

PKIProvider defines the PKI operations needed by the enrollment watcher to provide the controller's public key in acceptance responses.

type PendingAgent

type PendingAgent struct {
	// JoinLabels are, for a join, the labels of its token. They are not
	// stored with a pending request.
	JoinLabels map[string]string `json:"-"`
	// NATSUserKey is, for a join, the agent's own NATS user key. It is not
	// stored with a pending request.
	NATSUserKey string `json:"-"`
	MachineID   string `json:"machine_id"`
	Hostname    string `json:"hostname"`
	PublicKey   []byte `json:"public_key"`
	// EncryptionKey is the agent's public P-256 key, in
	// pki.EncryptionKeyEncoding.
	EncryptionKey string    `json:"encryption_key"`
	Fingerprint   string    `json:"fingerprint"`
	RequestedAt   time.Time `json:"requested_at"`
}

PendingAgent represents an agent awaiting enrollment acceptance.

type Record

type Record struct {
	MachineID   string `json:"machine_id"`
	Hostname    string `json:"hostname"`
	Fingerprint string `json:"fingerprint"`
	// EncryptionKey is the machine's public P-256 key, which the
	// fingerprint covers.
	EncryptionKey string               `json:"encryption_key,omitempty"`
	State         types.AdmissionState `json:"state"`
	RequestedAt   time.Time            `json:"requested_at,omitempty"`
	AdmittedAt    time.Time            `json:"admitted_at,omitempty"`
	// DecidedAt is when a machine was rejected or revoked.
	DecidedAt time.Time `json:"decided_at,omitempty"`
	// Reason is why a machine was rejected.
	Reason string `json:"reason,omitempty"`
	// JoinToken is the ID of the join token that admitted the machine, on
	// an admitted record that a join made.
	JoinToken string `json:"join_token,omitempty"`
	// JoinLabels are the labels of that join token.
	JoinLabels map[string]string `json:"join_labels,omitempty"`
	// Previous is the state of the machine's earlier record, on a pending
	// record; PreviousFingerprint is that record's fingerprint.
	Previous            types.AdmissionState `json:"previous,omitempty"`
	PreviousFingerprint string               `json:"previous_fingerprint,omitempty"`
}

Record is one machine's admission: its identity, its state, and when it got there. A pending record carries the state and the fingerprint of the machine's earlier record, when it had one, so a returning machine, or one whose key changed, is a decision, not a surprise.

type Seen

type Seen interface {
	ListAgents(ctx context.Context) ([]job.AgentInfo, error)
	AgentsLastSeen(ctx context.Context) (map[string]time.Time, error)
}

Seen tells whether an admitted machine still reports: the agents in the registry now, and the last report of each machine.

type Timeline

type Timeline interface {
	WriteAgentTimelineEvent(ctx context.Context, machineID, hostname, event, message string) error
}

Timeline is where the watcher writes the lifecycle events of a machine: the timeline of the agent, under its machine ID. The job client is one.

type TokenChecker

type TokenChecker interface {
	Check(ctx context.Context, token string) (jointoken.Token, error)
}

TokenChecker checks a join token without taking a use of it.

type Watcher

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

Watcher monitors NATS for agent enrollment requests and manages pending agents in a JetStream KV bucket.

func NewWatcher

func NewWatcher(
	logger *slog.Logger,
	nc NATSSubscriber,
	enrollmentKV KVStore,
	enrollmentBucket string,
	pkiProvider PKIProvider,
	autoAdmit bool,
	namespace string,
) *Watcher

NewWatcher creates a new enrollment Watcher.

func (*Watcher) AcceptAgent

func (w *Watcher) AcceptAgent(
	ctx context.Context,
	machineID string,
) error

AcceptAgent accepts a pending agent by machine ID. It publishes an acceptance response containing the controller's public key to the agent's response subject and deletes the pending entry from KV.

func (*Watcher) Admit

func (w *Watcher) Admit(
	ctx context.Context,
	machineID string,
	fingerprint string,
) error

Admit admits a pending machine, in an admission.admit span. fingerprint must be the one the machine requested with, which the operator reads on the machine itself: a mismatch is ErrFingerprintMismatch, and nothing is admitted. An earlier rejection or revocation of the machine is cleared.

func (*Watcher) Callout

func (w *Watcher) Callout(
	r CalloutRoles,
) natscallout.Decide

Callout is how the auth callout decides a connection: a join token that admits now gets the join role until it expires, at most joinSessionTTL; an admitted machine's own NATS user key, with the server's nonce signed with it, gets the agent role. Anything else is refused. Each decision is in an admission.callout span and the audit log.

func (*Watcher) Delete

func (w *Watcher) Delete(
	ctx context.Context,
	machineID string,
) error

Delete removes a machine from admission, in an admission.delete span: its key, and each record of it. Unlike revoke, it keeps no record, so a machine that asks again is new. It is for a machine that goes away on purpose, such as a VM that is rebuilt.

func (*Watcher) DeleteStale

func (w *Watcher) DeleteStale(
	ctx context.Context,
	seen Seen,
	after time.Duration,
) ([]string, error)

DeleteStale deletes each admitted machine that has not reported for after: it is not in the registry, and its last report, or its admission when it never reported, is older than after. It returns the machine IDs that it deleted. When the registry or the last reports do not read, it deletes nothing: a machine that cannot be seen is not a machine that is gone.

func (*Watcher) Get

func (w *Watcher) Get(
	ctx context.Context,
	machineID string,
) (Record, error)

Get returns the admission record of a machine, or ErrNotFound, in an admission.get span.

func (*Watcher) Join

func (w *Watcher) Join(
	ctx context.Context,
	req pki.JoinRequest,
) (ed25519.PublicKey, error)

Join admits the machine of req at once, when req's token admits, in an admission.join span: the operator made the token, so the token is the decision that admit records. The admitted record names the token. It returns the controller's public key, which the agent keeps. A request that its key did not sign is ErrJoinSignature; one with no valid encryption key is ErrJoinEncryptionKey; a token that does not admit is one of jointoken's errors, and admits nothing.

func (*Watcher) KeyStore

func (w *Watcher) KeyStore() client.AgentKeyStore

KeyStore returns the watcher as the job client's agent key store, so response verification reads the same records acceptance writes and shares their cache.

func (*Watcher) List

func (w *Watcher) List(
	ctx context.Context,
) ([]Record, error)

List returns each machine's admission record, one per machine, in hostname order, in an admission.list span.

func (*Watcher) LookupAgentKey

func (w *Watcher) LookupAgentKey(
	ctx context.Context,
	machineID string,
) (*AcceptedAgent, error)

LookupAgentKey returns the stored record for a machine ID. A missing record and an unreadable store are different answers: the first is ErrAgentKeyNotFound, the second ErrAgentKeyStoreUnavailable.

func (*Watcher) Reject

func (w *Watcher) Reject(
	ctx context.Context,
	machineID string,
	reason string,
) error

Reject rejects a pending machine with a reason, in an admission.reject span, and keeps a record of it.

func (*Watcher) RejectAgent

func (w *Watcher) RejectAgent(
	ctx context.Context,
	machineID string,
	reason string,
) error

RejectAgent rejects a pending agent by machine ID. It publishes a rejection response to the agent's response subject and deletes the pending entry from KV.

func (*Watcher) RemoveAgentKey

func (w *Watcher) RemoveAgentKey(
	ctx context.Context,
	machineID string,
) error

RemoveAgentKey deletes an agent's stored record. After it returns, nothing signed by the removed key verifies.

func (*Watcher) RenameAgentKey

func (w *Watcher) RenameAgentKey(
	ctx context.Context,
	machineID string,
	hostname string,
) error

RenameAgentKey records hostname as the name that an accepted machine answers as. Only a hostname update that an operator ran through osapi calls it: the machine ID and the key stay the anchor, and an agent cannot move its own name (GHSA-j73r).

func (*Watcher) Revoke

func (w *Watcher) Revoke(
	ctx context.Context,
	machineID string,
) error

Revoke removes an admitted machine's key, in an admission.revoke span, and keeps a record of it. Nothing the machine signs verifies afterwards; to return, it requests admission again.

func (*Watcher) RunStaleCleanup

func (w *Watcher) RunStaleCleanup(
	ctx context.Context,
	seen Seen,
	after time.Duration,
) error

RunStaleCleanup runs DeleteStale every staleInterval until ctx is done.

func (*Watcher) ServeJoin

func (w *Watcher) ServeJoin(
	ctx context.Context,
	listen JoinListener,
	agent AgentUser,
) error

ServeJoin answers each join over NATS until ctx ends: it admits the machine as Join does, and replies with the controller's key and the NATS user that agent gives, which the agent connects with after the join.

func (*Watcher) ServeRenew

func (w *Watcher) ServeRenew(
	ctx context.Context,
	listen JoinListener,
	mint Mint,
) error

ServeRenew answers each renewal of an agent's NATS user until ctx ends: an admitted machine whose key signed the request gets a new JWT from mint. A machine that is not admitted gets none, so a revoked agent is cut from NATS when its JWT expires.

func (*Watcher) ServeRotate

func (w *Watcher) ServeRotate(
	ctx context.Context,
	listen JoinListener,
) error

ServeRotate answers each rotation of an agent's keys until ctx ends: an admitted machine whose current key, and whose new key, signed the request gets its admission moved to the new keys. The old signing key stays valid for the rotation grace period, as at a new admission, so a result that the agent signed just before it took the new keys is not refused.

func (*Watcher) SetAudit

func (w *Watcher) SetAudit(
	a audit.Writer,
)

SetAudit gives the watcher the audit log, which each change that it makes on its own writes an entry to: a join over NATS, an admission by auto_admit, a deletion by delete_after. Without it, a change is only logged.

func (*Watcher) SetJoinTokens

func (w *Watcher) SetJoinTokens(
	tokens JoinTokens,
)

SetJoinTokens gives the watcher the store of join tokens, which Join takes a use of. Called once at startup.

func (*Watcher) SetRotationGracePeriod

func (w *Watcher) SetRotationGracePeriod(
	d time.Duration,
)

SetRotationGracePeriod sets how long a replaced key keeps verifying after a rotation. Called once at startup from the controller's PKI configuration.

Without it a rotation rejects everything signed in the moments before the new key was accepted, which is the reason operators turn verification off.

func (*Watcher) SetTimeline

func (w *Watcher) SetTimeline(
	t Timeline,
)

SetTimeline gives the watcher the timeline of the agents, which each admission decision writes an event to. Without it, a decision is only logged.

func (*Watcher) Start

func (w *Watcher) Start(
	ctx context.Context,
) error

Start subscribes to the enrollment request subject and blocks until the context is cancelled. Returns nil on clean shutdown.

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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