admin

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 21 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 admin provisions mash endpoints: the permission template a NATS user needs, and the streams, consumer and directory record behind it. mash never mints users or holds account seeds; the operator's own tooling issues the user with these permissions.

Index

Constants

View Source
const (
	AllowTag = "allow"
	DenyTag  = "deny"
	// NoDenyTag is the placeholder deny tag EVERY user carries, whether or not its zone has a deny exception.
	// nats-server refuses to authenticate a user whose scoped key has a {{tag(deny)}} template in a deny list and
	// that has no deny tag ("generated invalid subject"; allow lists just drop the line), and every zone key carries
	// that template from its first compile, so every user needs one deny tag: this one. Its value "_none" is a valid
	// subject token, and no endpoint or zone name can be "_none" (names start with a letter), so
	// agents.mail.*.<owner>._none addresses nothing. Because every user carries it from the start, the first real deny
	// exception of a zone changes only the JWTs of the endpoints it names, never the zone key.
	NoDenyTag = DenyTag + ":_none"
)

Tag names a user's JWT carries to widen or narrow what its zone's signing key grants, and the templates that expand them. A tag is "<name>:<zone>.<endpoint>" (or "<name>:<zone>.*"), lower case, and its value must be a valid subject tail: it is placed in a permission subject as it stands.

Variables

View Source
var (
	// ErrRecordOtherUser: the directory record's user is not the key given.
	ErrRecordOtherUser = errors.New("its record belongs to another user key (left in place)")
	// ErrRecordChanged: the record was replaced or changed between the read and the delete.
	ErrRecordChanged = errors.New("the record changed; left in place")
	// ErrNoRecord: there is no directory record, so nothing proves who owns the name (or its inbox stream).
	ErrNoRecord = errors.New("it has no directory record, so nothing proves the key owns it (left in place)")
)

The refusals of DeprovisionIfUser: each leaves the record, the lease and the inbox as they were.

View Source
var ErrLockExpiring = errors.New("the name lock is about to expire")

ErrLockExpiring is the cause of a bound context that ended because its lock was about to expire.

Functions

func IsPartial added in v0.3.3

func IsPartial(err error) bool

IsPartial reports whether err says the endpoint's NATS user was revoked but the removal did not complete: the credentials are dead and the same command run again finishes the removal.

func IsRefusal added in v0.3.3

func IsRefusal(err error) bool

IsRefusal reports whether err is a refusal of DeprovisionIfUser: the call touched nothing. Any other error from it may come after the record was deleted (the lease fence or the inbox delete failed, or the connection broke).

func NSCFlags

func NSCFlags(owner, name string) []string

NSCFlags renders Permissions as `nsc add user` flags.

func Permissions

func Permissions(owner, name string) jwt.Permissions

Permissions is the complete permission set of endpoint name under owner (spec section 8). Anything not listed is denied.

func PermissionsTo added in v0.3.2

func PermissionsTo(owner, name string, recipients []string) jwt.Permissions

PermissionsTo is Permissions with the three peer-addressing publish lines (mail, prompt and status to any endpoint of the owner) narrowed to recipients: one line per recipient and verb, agents.<verb>.*.<owner>.<recipient>. A nil recipients keeps the wildcard lines, so PermissionsTo(owner, name, nil) is Permissions. The wildcard mail line comes twice, the legacy 5-token form and the zoned 6-token form (ADR 0054); the recipient form keeps its one legacy line per recipient. An empty non-nil slice grants no mail, prompt or status line at all; the fixed lines (own heartbeat, inbox, directory read, lease) remain, so the block is never empty. Recipients must be valid endpoint names: they are placed in subjects as they are.

func ZonePermissions added in v0.3.2

func ZonePermissions(owner, zone string, wildcardZones []string) jwt.Permissions

ZonePermissions is the permission template of the scoped signing key of zone under owner. Only MAIL carries the zone token (ADR 0054): agents.mail.<kind>.<owner>.<zone>.<name>. Prompt, status and heartbeat keep SAP's five-token subjects, so the key grants those as they are. Every endpoint of the zone is a user signed by this key and gets, by expansion, its own copy of the fixed per-endpoint lines ({{name()}} is the user's name) and these peer-addressing lines:

  • one MAIL publish line per wildcard zone: agents.mail.*.<owner>.<zone>.*, so every endpoint of the zone may mail every endpoint of each wildcardZones entry;
  • the mail exception line agents.mail.*.<owner>.{{tag(allow)}}, one subject per "allow:" tag of the user; a user with no allow tag gets none;
  • the mail deny line agents.mail.*.<owner>.{{tag(deny)}}, one subject per "deny:" tag of the user: a deny beats any allow, so a user's deny tags remove peers from what the mail wildcards grant. The key carries it always, so adding a zone's first deny exception never changes the key. nats-server refuses a user with no deny tag under this template, so every user carries NoDenyTag at least;
  • two fixed, open lines, agents.prompt.*.<owner>.* and agents.status.*.<owner>.*: live prompts and status probes to any endpoint of the owner are not policed until a later decision (ADR 0054).

The endpoint's own prompt and status subscriptions are the five-token sap.For subjects with {{name()}}. Nothing else addresses a peer. The block is never empty. The templates need the scoped-key user to carry empty permissions of its own. zone names the key; no line spells it out except through the mail wildcards it is a recipient of.

Types

type Admin

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

Admin provisions endpoints with the account's admin credentials.

func New

func New(nc *nats.Conn, owner string) (*Admin, error)

New returns an Admin for owner.

func (*Admin) ApplyLimits added in v0.3.1

func (a *Admin) ApplyLimits(ctx context.Context, names ...string) ([]string, error)

ApplyLimits raises the configured limits on existing inboxes in place with a stream update: max_bytes and max_age where they are below the configured value, and max_consumers where it differs. With no names it covers every directory endpoint. Lowering max_bytes or max_age is refused with an error naming the endpoint and field (nothing changes for that endpoint), because it could discard stored mail; the other endpoints are still processed and the errors are joined. It returns one line per endpoint saying what changed.

func (*Admin) Conn added in v0.3.3

func (a *Admin) Conn() *nats.Conn

Conn is the connection the Admin was made with. The caller owns it.

func (*Admin) Deprovision

func (a *Admin) Deprovision(ctx context.Context, name string) (err error)

Deprovision fences name's lease with a tombstone, then removes its directory record and inbox stream. The fence comes first: a session that is live or starting cannot take the lease back once its endpoint is gone (#10).

func (*Admin) DeprovisionDrained added in v0.3.3

func (a *Admin) DeprovisionDrained(ctx context.Context, name, id string, seq uint64) (err error)

DeprovisionDrained is Deprovision for an inbox that was suspended and read through sequence seq (the last_seq that Suspend reported); id is the suspension id Suspend reported. Under the name's lock it reads the stream fresh and refuses, touching nothing, unless the inbox is still suspended, carries a suspension id equal to id (an empty id never matches, so a re-provisioned endpoint of the same name is safe from an old command) and its last sequence is exactly seq: another admin's Resume, and any mail stored after it, make the check fail instead of losing mail. A name with no inbox stream is refused: nothing proves it is the one drained.

func (*Admin) DeprovisionIfUser added in v0.3.2

func (a *Admin) DeprovisionIfUser(ctx context.Context, name, user string) (err error)

DeprovisionIfUser is Deprovision for a record that must still belong to user (a public user key): it reads the record's value and revision, refuses unless its user equals user, and deletes the record with a revision guard (Purge with LastRevision), so a record replaced between the read and the delete is never removed. A revision conflict re-reads the record (up to setMetaTries times): a metadata-only change by another admin leaves the user unchanged, so the delete is retried on the new revision; a changed user, a vanished record or exhausted retries refuse.

Order: guard and guarded record delete first, then the lease fence and the inbox delete. A refused call therefore touches nothing: no tombstone, no stream delete. The whole call runs under the name's lock (ADR-0048), so another admin's Provision of the name waits until the fence and the inbox delete are done and is never fenced and never has its inbox deleted. For sessions the gap between the record delete and the fence is safe because a session cannot hold a record-less name: Open re-reads the directory record after taking the lease and gives the lease back when it is gone (see Open), and a session that already held the lease is stopped by the tombstone at its next refresh, exactly as in Deprovision. The cost of this order against Deprovision's is that a failure between the two steps leaves a record-less name with an inbox and no fence; re-running `deprovision` (without --user) finishes it.

With no record nothing proves ownership, so it refuses even when the inbox stream exists (a provision that failed before writing its record): remove that stream with a plain deprovision.

func (*Admin) EnsureInbox

func (a *Admin) EnsureInbox(ctx context.Context, name string) ([]string, error)

EnsureInbox makes sure name's inbox stream and its durable consumer exist, creating whichever is missing with the same configuration Provision uses. It is for an endpoint whose directory record already exists (Provision refuses those) and reports what it had to create: "stream", "consumer", both, or neither. An existing stream or consumer is only checked, never updated: one that differs from that configuration in any field mail depends on is an error naming the field, because fixing it in place could discard stored mail (a lower MaxBytes or MaxAge would). The user decides to deprovision it, which removes whatever the inbox holds, and provisions again.

func (*Admin) Exists added in v0.3.3

func (a *Admin) Exists(ctx context.Context, name string) (bool, error)

Exists reports whether name has a directory record, an inbox stream or a live lease (not just the tombstone a deprovision leaves): any of them is something a deprovision removes or fences. Deprovision itself stays idempotent (rollbacks rely on it); a CLI verb asks this first to refuse a name that was never there.

func (*Admin) Init

func (a *Admin) Init(ctx context.Context) error

Init creates the directory and lease buckets. It is idempotent. A bucket from before buckets had a size cap (no MaxBytes) is bounded in place with a stream update, keeping its keys; a bucket whose MaxBytes is smaller than the configured limit is raised to it; a larger one is kept (a limit is never lowered), and nothing is purged.

func (*Admin) List

func (a *Admin) List(ctx context.Context) ([]store.Record, error)

List returns every directory record, sorted by name.

func (*Admin) Provision

func (a *Admin) Provision(ctx context.Context, name, user, account, note string, meta Meta) (rec store.Record, err error)

Provision creates name's inbox stream, its consumer and, last, its directory record, so a half-done provision can simply be re-run.

func (*Admin) Resume added in v0.3.3

func (a *Admin) Resume(ctx context.Context, name string) (err error)

Resume restores the subjects Suspend saved and clears its metadata. It is idempotent: an inbox that is not suspended is left as it is. Stale metadata on live subjects is cleared and the subjects kept; parked subjects with no usable saved list are an error, never a guess.

func (*Admin) SetLimits added in v0.3.1

func (a *Admin) SetLimits(l store.Limits) error

SetLimits sets the caps Init, Provision and EnsureInbox use (default: store.DefaultLimits). It validates them.

func (*Admin) SetMeta

func (a *Admin) SetMeta(ctx context.Context, name string, u MetaUpdate) (store.Record, error)

SetMeta changes name's role, host and labels, only those given. It merges into the stored JSON object, so every other field, including ones a newer mash wrote, survives, and writes with a compare-and-set against the revision it read, re-reading and retrying if another write got in between.

func (*Admin) SetUser added in v0.3.3

func (a *Admin) SetUser(ctx context.Context, name, account, oldUser, newUser string) (store.Record, error)

SetUser is a compare-and-set of name's directory record's user key from oldUser to newUser (public user keys), for a key rotation. It takes the name's lock like SetMeta, reads the record and writes it back against the revision it read, re-reading and retrying if another write got in between, and keeps every other field. It refuses a name with no record, a record whose account is not account, and a record whose user is neither oldUser nor newUser. It is idempotent: a record that already carries newUser is returned as it is.

func (*Admin) SetUserLocked added in v0.3.3

func (a *Admin) SetUserLocked(ctx context.Context, l NameLock, name, account, oldUser, newUser string) (store.Record, error)

SetUserLocked is SetUser for a caller that already holds name's lock l (from WithNameLock): it does not take the lock again, and re-checks it before the write.

func (*Admin) SetZone added in v0.3.3

func (a *Admin) SetZone(ctx context.Context, name, zone string) (_ store.Record, err error)

SetZone moves the existing endpoint name into zone without touching stored mail. It first appends the zone's mail filter to the inbox stream's subjects (an update that changes nothing else and purges nothing, so mail that a sender not yet updated publishes to the legacy subject still lands), then rewrites the directory record's zone and mail subject against the revision it read, keeping every other field. It is idempotent: an endpoint already in zone is returned as it is. An endpoint in another zone is refused, as no endpoint returns to legacy or changes zone in this version.

func (*Admin) Suspend added in v0.3.3

func (a *Admin) Suspend(ctx context.Context, name string) (_ SuspendState, err error)

Suspend parks name's inbox stream: it saves the stream's subjects in its metadata and replaces them with the one subject mash.suspended.<name>, so a sender's publish finds no stream. Only the subjects and metadata change and nothing is purged. It also stores a fresh random suspension id. It is idempotent: a suspended inbox is reported as it is, with its existing id. The state's LastSeq is read after the update.

func (*Admin) Suspended added in v0.3.3

func (a *Admin) Suspended(ctx context.Context, name string) (SuspendState, error)

Suspended reads whether name's inbox is suspended, since when, and the stream's message count and last sequence.

func (*Admin) UserOf added in v0.3.3

func (a *Admin) UserOf(ctx context.Context, name string) (user, account string, err error)

UserOf reads name's directory record and returns its user key and account. It returns ErrNoRecord when there is none. It does not take the name's lock; inside WithNameLock use UserOfLocked (the read is the same).

func (*Admin) UserOfLocked added in v0.3.3

func (a *Admin) UserOfLocked(ctx context.Context, l NameLock, name string) (user, account string, err error)

UserOfLocked is UserOf for a caller that holds name's lock l (from WithNameLock); it refuses a lock that is not held or not name's.

func (*Admin) WithNameLock added in v0.3.3

func (a *Admin) WithNameLock(ctx context.Context, name string, fn func(ctx context.Context, l NameLock) error) (err error)

WithNameLock takes name's lock, runs fn with a context that ends before the lock expires and releases the lock. fn does its reads and writes through UserOfLocked and SetUserLocked (the lock is not reentrant: SetUser or UserOf inside fn would wait for it) and re-checks the lock with Check before any write of its own. An error from fn that is the context ending because the lock was about to expire is worded to say so.

func (*Admin) WithRevoker added in v0.3.3

func (a *Admin) WithRevoker(h RevokeHook) *Admin

WithRevoker returns a copy of a whose Deprovision, DeprovisionIfUser and DeprovisionDrained call h, when it is not nil, with the user key of the directory record read under the lock (see RevokeHook). Plain Deprovision calls it only when the name has a readable record. a itself is unchanged.

type Meta

type Meta struct {
	Role, Host  string
	Labels      map[string]string
	Description string
	Caps        []string
	// Zone, when set, provisions the endpoint into that zone: a 6-token mail subject, and an inbox that takes both
	// the zone and the legacy subject (ADR 0054). Empty is the legacy 5-token subject.
	Zone string
}

Meta is a record's optional directory metadata.

type MetaUpdate

type MetaUpdate struct {
	Role, Host  *string
	Labels      map[string]string
	Description *string
	AddCaps     []string
	DropCaps    []string
	ClearCaps   bool
}

MetaUpdate names the metadata fields SetMeta changes; a nil field is left alone and a pointer to "" clears it. Labels is applied per key: a value sets that label, an empty value clears it, other labels are left alone. Description is set like Role. Caps are applied as a merge: AddCaps are added, DropCaps removed, and ClearCaps removes every capability first (then AddCaps still apply).

type NameLock added in v0.3.3

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

NameLock is a held name lock (ADR 0048, ADR 0058), handed to the func WithNameLock runs. It is valid only inside that func.

func (NameLock) Check added in v0.3.3

func (n NameLock) Check(ctx context.Context) error

Check refuses unless the lock is still held and not about to expire (ADR 0058). Call it immediately before a write the lock protects that Admin does not make itself, such as a file.

type RevokeHook added in v0.3.3

type RevokeHook func(ctx context.Context, user string) error

RevokeHook revokes the NATS user key user (a public key) of an endpoint that is about to be removed. It runs under the endpoint's name lock, after every guard of the removal has passed and before anything is removed; an error aborts the removal with nothing removed.

type SuspendState added in v0.3.3

type SuspendState struct {
	Suspended bool
	Since     string // RFC 3339 UTC; empty when not suspended
	ID        string // names this one suspension; empty when not suspended or when parked by hand without one
	Msgs      uint64
	LastSeq   uint64
}

SuspendState is whether an endpoint's inbound mail is parked (ADR 0057), when, and where its inbox stands. Msgs and LastSeq are the stream's, read fresh; while the state holds, LastSeq is final.

Jump to

Keyboard shortcuts

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