admin

package
v0.5.9 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 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 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 (

	// For mashctl: the cause of the leftovers of an earlier removal, and the fallback.
	CauseEarlierRemovalStuck = causeEarlierStuck
	CauseUnknown             = causeUnknown
)

The causes a partial removal names, in plain words (each 28 characters or fewer). A cause is the last step that failed after the user key was revoked; mashctl prints it and never the error behind it.

View Source
const (
	// AdoptUnchanged is Adopt's action when the marker already names the submitter and the same exempt set: nothing
	// is written.
	AdoptUnchanged = "unchanged"
	// AdoptExemptUpdated is Adopt's action when the marker names the submitter and only the exempt set changed: a new
	// revision is written (marker action adopt).
	AdoptExemptUpdated = "exempt-updated"
)

The values of Adopt's action result when it writes nothing.

View Source
const (
	StateAcked       = "acked"                                   // at or below the consumer's ack floor
	StateUndelivered = "undelivered"                             // above the consumer's last delivered stream sequence
	StateAckUnsure   = "delivered-unacked-or-acked-out-of-order" // delivered, above the ack floor: NATS does not say which
)

Delivery states of a stored message, derived only from the consumer's cursors.

View Source
const AccountLockName = "_policy-account"

AccountLockName is the pseudo-name of the account-wide policy lock. It is not a valid endpoint name (the underscore), so its lock key limits-lock._policy-account is no name's lock.

View Source
const AccountLockWait = 30 * time.Second

AccountLockWait is how long a command waits for the account lock before it refuses (see WithAccountLockWait).

View Source
const DefaultInspectLimit = 20

DefaultInspectLimit is how many messages an inspection returns when no limit is given.

View Source
const InspectSchema = "mash-inbox-inspect@1"

InspectSchema is the schema string of the JSON `mashctl endpoint inbox` used to print. It is a contract with the readers of that output and changes only when a field is removed or changes meaning.

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 (
	// ErrSubmitterInvalid is returned for a submitter that is not an nkey public key.
	ErrSubmitterInvalid = errors.New("mash: adoption: the submitter is not an nkey public key")
	// ErrSubmitterIsAccount is returned for a submitter equal to the account's own public key.
	ErrSubmitterIsAccount = errors.New("mash: adoption: the submitter is the account's own key; it must be a key mash does not hold")
	// ErrExemptInvalid is returned for an exempt key that is not an nkey user public key.
	ErrExemptInvalid = errors.New("mash: adoption: an exempt key is not an nkey user public key")
	// ErrAdoptionChanged is returned when another writer changed the marker too often for the write to land.
	ErrAdoptionChanged = errors.New("mash: adoption: the marker was changed by another writer; run the command again")
)

Typed errors of Adopt. None of them echoes the value it refused.

View Source
var (
	ErrKeyRevoked        = store.ErrKeyRevoked
	ErrKeyBoundElsewhere = store.ErrKeyBoundElsewhere
	ErrKeyPurposeChanged = store.ErrKeyPurposeChanged
)

ErrKeyRevoked, ErrKeyBoundElsewhere and ErrKeyPurposeChanged are the refusals of RecordIssuedChecked.

View Source
var (
	// ErrNotAdopted is returned when a rotation is asked of an account that has no adoption marker.
	ErrNotAdopted = errors.New("mash: adoption: the account is not adopted")
	// ErrNextIsCurrent is returned for a next submitter equal to the current one.
	ErrNextIsCurrent = errors.New("mash: adoption: the next submitter is the current submitter")
	// ErrNextIsMashKey is returned for a next submitter that is a key mash holds: the admin user that adopted the
	// account or one of the exempt users.
	ErrNextIsMashKey = errors.New("mash: adoption: the next submitter is a key mash holds")
	// ErrNextPending is returned when a next submitter is already pending and a different one is asked for.
	ErrNextPending = errors.New("mash: adoption: a different next submitter is already pending")
	// ErrNextMismatch is returned by a promotion when the marker's pending next submitter is not the key asked for
	// (it was changed by a recovery adopt, or never set).
	ErrNextMismatch = errors.New("mash: adoption: the marker's pending next submitter is not the key to promote")
	// ErrMarkerMoved is returned by a rotation write when the marker's revision is not the one the caller verified
	// its document under (a recovery adopt or another writer replaced the marker in between). Nothing is written.
	ErrMarkerMoved = errors.New("mash: adoption: the marker changed since it was read")
)

Typed errors of the planned rotation. None of them echoes a key.

View Source
var ErrAccountBusy = errors.New("mash: another policy change or an adoption is in progress; nothing was changed")

ErrAccountBusy is returned when the account lock stayed held by another policy change or an adoption for the whole wait. Nothing was changed.

View Source
var ErrAlreadyProvisioned = errors.New("already provisioned")

ErrAlreadyProvisioned is wrapped by the error of a Provision that found the address's directory record present.

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.

View Source
var ErrLockLost = errors.New("the lock was lost or is about to expire")

ErrLockLost is wrapped by the error of an operation that stopped because its lock was lost to another admin or was about to expire. Nothing further was changed, and running the command again is safe.

View Source
var ErrMarkerFinalOtherUser = errors.New("its name is already retired (INV-002) by a final retired marker for another user key (left as it is)")

ErrMarkerFinalOtherUser: the name's retired marker is final (the name is burned, INV-002) yet a live record carries another user key. Nothing is removed and the name stays refused.

View Source
var ErrNotRecorded = errors.New("mash: issue record: key not recorded")

ErrNotRecorded is returned by MarkRevoked for a key the issue record does not hold: mash never issued it (or the record's bucket does not exist). A caller that revokes a key mash may not have issued treats it as no finding.

View Source
var InboxDeleteFault func() error

InboxDeleteFault is a test seam for tests in other packages: when it is not nil and returns an error, the inbox stream delete of a removal fails with that error instead of calling the server. Nil in production. A server has no way to refuse the delete of a stream that exists, so this is the only way to reach that step.

View Source
var InspectLimits = []string{
	"per-message delivery count and ack time are not kept by JetStream or mash; the consumer's num_redelivered is the aggregate",
	"a message above the consumer's ack floor and at or below its last delivered sequence is delivered and either not acknowledged yet or acknowledged out of order: JetStream does not report acknowledgements above the ack floor",
}

InspectLimits are the things an inspection cannot say, in the words the output carries.

Functions

func CheckIssuersKept added in v0.5.0

func CheckIssuersKept(account, adminUser, adminIssuer string, exemptIssuers map[string][]string, kept map[string]bool) error

CheckIssuersKept refuses when the admin user, or any connected exempt user, is signed by a key that is not kept. account is the account's own identity key, which always counts as kept; kept holds the signing keys that stay: every scoped key the key store holds for an owner group of any range, and the list set's (reconcile.KeptSigners). adminIssuer is the `iss` of the admin credentials' user JWT; exemptIssuers maps the public key of each connected exempt user to every issuer CONNZ reported for it, one per connection (two connections of one user may carry JWTs signed by different keys, and every one of them must be kept). An empty issuer is not known to be kept, so it is refused. The error is an *IssuersNotKeptError naming every user and key, sorted; nothing is changed.

func CheckProvision added in v0.4.0

func CheckProvision(rule *namerule.Rule, addr sap.Address) error

CheckProvision applies rule to the address addr, as provisioning does. A refusal is an error that names the rule and carries its message. An address that is not valid passes here: the code that follows refuses it on its own terms.

func ClampRange added in v0.5.0

func ClampRange(from, to, first, last uint64) (lo, hi uint64, ok bool)

ClampRange is the inclusive range [lo, hi] a request for from..to (0 unset) covers in a stream holding first..last. ok is false when nothing of it is in the stream.

func DeliveryState added in v0.5.0

func DeliveryState(seq uint64, c *InspectedConsumer) string

DeliveryState is the state of the message at stream sequence seq given the consumer (nil when there is none). It is derived from the cursors alone.

func IsJetStreamNotEnabled added in v0.5.5

func IsJetStreamNotEnabled(err error) bool

IsJetStreamNotEnabled reports whether err is the server's "jetstream not enabled" answer (API error code 10076) or its per-account form (10039). It uses the typed errors, never the message text.

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 JetStreamNotEnabledHint added in v0.5.5

func JetStreamNotEnabledHint(err error, limit int64) error

JetStreamNotEnabledHint wraps err with the likely cause when it is the JetStream-not-enabled error, and returns every other error (and nil) untouched. nats-server gives JetStream 75% of the free disk by default and silently leaves an account without JetStream when its JWT disk limit does not fit. limit is the account's JWT disk limit in bytes, or 0 when it is not known (the number is then left out). The original error stays reachable with errors.Is and errors.As.

func NSCFlags

func NSCFlags(a sap.Address) []string

NSCFlags renders Permissions as `nsc add user` flags. An invalid address gives none.

func PartialCause added in v0.5.9

func PartialCause(err error) (cause string, ok bool)

PartialCause returns the plain-words cause (28 characters or fewer, no punctuation) of a partial removal: ok is false when err is not one (see IsPartial). The error behind it is only on Unwrap.

func Permissions

func Permissions(a sap.Address) *jwt.Permissions

Permissions is the complete permission set of the endpoint at a (ADR 0145, spec section 8). Anything not listed is denied, and there is no response permission: it would grant publishing to any reply subject the endpoint receives, so a request it sends itself with a reply subject of $JS.API.STREAM.DELETE.<victim> would let it delete another inbox.

Publish: mail, prompt and status to any endpoint of the same owner (agents.<verb>.<owner>.*.*, the owner a literal token), and the fixed lines: its own exact heartbeat, replies to the inboxes of its own owner (_INBOX.<owner>.>), the service API, and the JetStream and KV subjects of its own inbox, the directory and its lease, all keyed by its own flat key. Subscribe: its private reply prefix (_INBOX.<owner>.<flat>.>), its own prompt and status subjects, $SRV.>, and the heartbeats of its own owner (agents.hb.<owner>.*.*).

The owner is a literal in every peer line, never a wildcard, so no line reaches another owner's endpoints. a must be valid (sap.NewAddress); for one that is not, Permissions returns nil, because an empty permission set would allow everything.

func RewordUnavailable added in v0.5.5

func RewordUnavailable(msg string) string

RewordUnavailable puts a hint in front of the raw NATS text in an already formatted message: the lost-quorum hint for "JetStream system temporarily unavailable", and, for "stream is offline" (err_code 10118), a line saying the server that holds the stream or bucket is down. It leaves a message that has a hint, or carries neither text, as it is.

func SetBeforeHook added in v0.5.0

func SetBeforeHook(f func(step string)) (restore func())

SetBeforeHook installs a function called with the step name at the start of every Before, and returns the call that removes it. It is for tests, which use it to lose the lock right before a chosen write.

func ValidateGrant added in v0.4.0

func ValidateGrant(subject string) error

ValidateGrant checks one subject grant: a grant that applies to the agents. subject space must not carry '*' or '>' in the owner token position, which is token index 2 of agents.<verb>.<owner>.<group>.<instance>, or at or before it. A grant is accepted only if every token is a literal or a lone '*', '>' appears only as the last token, no token is empty or has whitespace, and no token mixes a wildcard character with other text. A grant that starts with a wildcard applies to the agents. space too, so it is held to the same rule. An agents. grant needs at least four tokens (verb and owner are named, and something follows). Subjects outside the agents. space pass the structural checks only.

func ValidateNextSubmitter added in v0.5.0

func ValidateNextSubmitter(account string, m store.Marker, next string, held []string) error

ValidateNextSubmitter reports why next may not become the next submitter of the account whose marker is m: it must be an nkey public key, not the account's own key, not the current submitter and not a key mash holds: the admin user recorded in the marker, the exempt users and held, the public keys of the key store (operator, system, account and admin keys: see ctlkeys.Authority.HeldKeys). It never echoes a key.

Types

type AccountLock added in v0.5.0

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

AccountLock is a held account lock. Release it (defer it; a second Release does nothing); a nil *AccountLock is a lock that is not needed (a command with no server), and all its methods are no-ops.

func (*AccountLock) Before added in v0.5.0

func (k *AccountLock) Before(ctx context.Context, step string) error

Before is Held for a named step: a guarded command calls it immediately before each write or irreversible step (a record, a key file, a creds file, a revocation, the policy file, the account JWT push) and stops when it returns an error, which names the step that was not taken. A nil lock is a no-op.

A check cannot close the window between it and the write: a lock lost in those microseconds (one request) can still let one write through. The next guarded command reads the marker again.

func (*AccountLock) Held added in v0.5.0

func (k *AccountLock) Held(ctx context.Context) error

Held returns nil only while the lock is still this holder's: its key still has the revision this holder wrote and its expiry is not close. Call it immediately before each write the lock protects; on an error stop, for the lock may have been taken by an adoption.

func (*AccountLock) Release added in v0.5.0

func (k *AccountLock) Release()

Release stops the refresh and removes the lock, if it is still this holder's. It is safe to call on a nil lock.

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, the owner token its issue records carry when they name none.

func (*Admin) Adopt added in v0.5.0

func (a *Admin) Adopt(ctx context.Context, account, submitter, by string, exempt []string) (store.Marker, string, error)

Adopt registers submitter as the one key that may hand in list sets for account, over the admin connection. by is the public key of the admin user running the command. The first call creates the marker (action adopt). A call with a different submitter is the recovery rotation: it replaces the marker at the revision it read (action recover), clears any pending next_submitter, and the old submitter is refused from then on. A call with the submitter already registered and the same exempt set writes nothing and returns AdoptUnchanged; with another exempt set it writes a new revision (action adopt) and returns AdoptExemptUpdated. A recovery rotation also refreshes the exempt set. exempt is the public keys of the users the later reconcile must never touch (see store.Marker.Exempt). The read and the write are made under the account lock (see AccountLock), and the write is a compare-and-set on the marker's last revision, retried when another writer got there first. The bucket is created, hardened, when it does not exist.

func (*Admin) Adoption added in v0.5.0

func (a *Admin) Adoption(ctx context.Context) (m store.Marker, found bool, err error)

Adoption reads the adoption marker. found is false when the account is not adopted: the bucket does not exist, or it holds no marker. Any other outcome is an error, never "not adopted": a bucket that is not as mash makes it, a read that fails and a value that cannot be understood all return an error, so a caller refuses (fail closed). It never creates or changes anything, and it reads the latest revision each time, so there is nothing to cache.

func (*Admin) AdoptionRev added in v0.5.0

func (a *Admin) AdoptionRev(ctx context.Context) (m store.Marker, rev uint64, found bool, err error)

AdoptionRev is Adoption with the revision of the marker that was read (0 when not adopted). A rotation write is bound to it (SetNextSubmitter, PromoteSubmitter).

func (*Admin) ApplyLimits added in v0.3.1

func (a *Admin) ApplyLimits(ctx context.Context, addrs ...sap.Address) ([]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 addresses 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) ApplyLimitsDry added in v0.5.6

func (a *Admin) ApplyLimitsDry(ctx context.Context, dry bool, addrs ...sap.Address) ([]string, error)

ApplyLimitsDry is ApplyLimits; with dry set it reads the streams, changes none and returns the lines of what would change.

func (*Admin) Audit added in v0.4.0

func (a *Admin) Audit(ctx context.Context) (AuditSnapshot, error)

Audit reads the directory, the inbox streams and the lease keys and changes nothing. A value that does not parse is reported in BadRecords, not as an error, so one damaged record does not hide the rest. A key or stream that disappears while it is read is skipped.

func (*Admin) CheckInbox added in v0.5.0

func (a *Admin) CheckInbox(ctx context.Context, addr sap.Address) (InboxCheck, error)

CheckInbox reads whether addr has the inbox mail depends on, and creates nothing and writes no record. The address is served by its own inbox, inbox-<flat>, when the directory holds a record under its flat key. A stream or consumer that exists but differs from the configuration mail depends on is an error naming the field, the same check EnsureInbox makes; nothing is 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, addr sap.Address) (err error)

Deprovision removes addr's directory record and inbox stream and fences its lease with a tombstone. The fence comes first: a session that is live or starting cannot take the lease back once its endpoint is gone (#10). The address's retired marker goes pending -> purge -> final (see beginRetire): the marker is written pending before the user is revoked or anything is removed, and made final once the record is purged.

func (*Admin) DeprovisionDrained added in v0.3.3

func (a *Admin) DeprovisionDrained(ctx context.Context, addr sap.Address, 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.

The address's retired marker goes pending -> revoke and purge -> final exactly as in Deprovision (see beginRetire), and a re-run after a stop that followed the purge finishes it.

func (*Admin) DeprovisionIfUser added in v0.3.2

func (a *Admin) DeprovisionIfUser(ctx context.Context, addr sap.Address, 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. The one exception is a key with a retired marker, the remains of an interrupted removal, which it finishes; with no marker it changes nothing.

func (*Admin) EndpointState added in v0.5.6

func (a *Admin) EndpointState(ctx context.Context, addr sap.Address, withWaiting bool) (EndpointState, error)

EndpointState reads addr's state. It reads the inbox stream (and its deliver consumer when withWaiting) and the lease key, and writes nothing. An address with no inbox stream is not suspended and has nothing waiting.

func (*Admin) EnsureInbox

func (a *Admin) EnsureInbox(ctx context.Context, addr sap.Address) ([]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, addr sap.Address) (bool, error)

Exists reports whether addr 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) HasRecord added in v0.5.5

func (a *Admin) HasRecord(ctx context.Context, addr sap.Address) (bool, error)

HasRecord reports whether the directory holds a readable record under addr's flat key that is addr itself, and reads nothing else. A record that cannot be read is an error.

func (*Admin) InboxMessages added in v0.5.6

func (a *Admin) InboxMessages(ctx context.Context, addr sap.Address) (uint64, error)

InboxMessages is how many messages addr's inbox stream holds; 0 when it has no inbox stream. It writes nothing.

func (*Admin) Init

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

Init creates the directory, lease, retired-name and issue-record 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. The lease bucket does not allow rollup: Init creates it hardened and hardens an existing one (see store.HardenLeaseBucket), and fails if it cannot.

func (*Admin) InspectInbox added in v0.5.0

func (a *Admin) InspectInbox(ctx context.Context, addr sap.Address, opts InspectOptions) (*InboxInspection, error)

InspectInbox reads the stored messages of inbox-<flat> of addr and the delivery state of its `deliver` consumer. It uses only STREAM.INFO, a direct get by sequence and CONSUMER.INFO of the existing consumer (and directory key reads to name senders), so it changes nothing: it never creates, binds or fetches from a consumer and never acknowledges.

func (*Admin) IsBurned added in v0.5.5

func (a *Admin) IsBurned(ctx context.Context, addr sap.Address) (bool, error)

IsBurned reports whether addr's flat key has a retired marker, pending or final (INV-002): the address is never reassigned. It reads the marker without taking the name's lock; Provision checks again under it.

func (*Admin) Issued added in v0.5.0

func (a *Admin) Issued(ctx context.Context) (recs []store.Issued, present bool, err error)

Issued reads the issue record: the latest entry of each key, sorted by key; a record with no purpose reads as store.PurposeIssue. present is false when the bucket does not exist (nothing was ever recorded). An entry that cannot be read or decoded is an error: a check must not pass over a record it cannot read.

func (*Admin) IssuedBucketProof added in v0.5.0

func (a *Admin) IssuedBucketProof(ctx context.Context) (ok bool, why string, err error)

IssuedBucketProof says whether the issue record can prove that no record of a user was lost, so that a user missing from it was never recorded: the bucket exists and is hardened as mash makes it (store.VerifyIssuedBucket: refuses delete, purge and rollup, no TTL, discards new messages when full), and its stream metadata carries the history marker store.IssuedMarkerKey as "full" or "raised:N:S". why says what is missing when ok is false. An error is a read that failed: the caller must not take it for either answer.

func (*Admin) IssuedByKey added in v0.5.0

func (a *Admin) IssuedByKey(ctx context.Context, publicKey string) (rec store.Issued, found bool, err error)

IssuedByKey returns the latest issue record of publicKey. found is false when the key is not recorded or the bucket does not exist (nothing was ever recorded: jetstream.ErrBucketNotFound and ErrKeyNotFound, and only those, mean absent); any other failure (network, permission, cancelled context, JetStream) and an entry that cannot be read or decoded is an error.

func (*Admin) IssuedHistoryByKey added in v0.5.0

func (a *Admin) IssuedHistoryByKey(ctx context.Context, publicKey string) (t IssuedTimes, found bool, err error)

IssuedHistoryByKey reads every retained revision of publicKey's issue record (up to the bucket's history cap, store.IssuedHistory) and returns the issue times they hold. found is false when the key is not recorded or the bucket does not exist (jetstream.ErrBucketNotFound and ErrKeyNotFound, and only those, mean absent). Any other failure, a revision that cannot be decoded or names another key, a revision that is not a plain write, and a revision whose issued_at is missing or not a time (*MalformedIssuedAtError) is an error: a check must not pass over a revision it cannot read. A key whose retained history cannot be shown complete from the bucket's marker (see store.IssuedMarkerKey) is an *IncompleteHistoryError.

func (*Admin) List

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

List returns every directory record that parses, sorted by name, and the records that do not. A record that fails store.ParseRecord is skipped, never fatal: the caller must report each BadRecord (the key and the error), never silently.

func (*Admin) LockAccount added in v0.5.0

func (a *Admin) LockAccount(ctx context.Context) (*AccountLock, error)

LockAccount takes the account lock, waiting up to AccountLockWait for its holder. It returns ErrAccountBusy when the wait ends with the lock still held.

func (*Admin) MarkRevoked added in v0.5.0

func (a *Admin) MarkRevoked(ctx context.Context, publicKey string, at time.Time) error

MarkRevoked sets revoked_at (RFC 3339, UTC) on the record of publicKey if it is unset: it reads the record and writes it back with a revision check, retrying when it loses a race, so a concurrent RecordIssued loses no field. It never clears or moves a revoked_at already set, so it is idempotent. A key the record does not hold returns ErrNotRecorded. It is called after a revocation succeeded; the revocation does not depend on it.

func (*Admin) MissingBuckets added in v0.5.6

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

MissingBuckets names the buckets Init makes that do not exist yet. It reads and changes nothing.

func (*Admin) PromoteSubmitter added in v0.5.0

func (a *Admin) PromoteSubmitter(ctx context.Context, next string, expectedRev, ownRev uint64) (store.Marker, uint64, error)

PromoteSubmitter makes next, which must be the marker's pending next submitter, the submitter and clears the pending key (action rotate): the planned rotation's second half. It is bound to expectedRev and ownRev as SetNextSubmitter is. A marker that already names next as the submitter with none pending writes nothing, so a retry after a lost answer is safe. A marker whose pending key is anything else (a recovery adopt replaced it) is ErrNextMismatch and is not changed.

func (*Admin) Provision

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

Provision provisions the endpoint at addr (ADR 0145). The configured name rule is applied first, to all three tokens of addr, before the keys are validated and before anything is read or written. It creates the directory record keyed by addr's flat key, the inbox stream inbox-<flat> filtered on addr's exact mail subject, and the durable consumer. The record's agent is the harness, sap.AgentName.

The flat key's lock is held for the whole call, record and stream alike, so a deprovision of the same address cannot interleave with it. The record is written last, so a provision that stopped part-way is finished by running the same call again; a finished one is refused as already provisioned. A retired address is refused (INV-002): the deprovision writes a durable marker into the no-TTL bucket store.RetiredBucket (key = flat key; value: store.Retired, its tokens, the retired user public key, the time and a state, never a seed) as pending before it revokes or removes anything, and makes it final once the record is purged. This call checks it under the flat key's lock; a pending marker blocks exactly like a final one. A deprovision deletes only the pending marker its own call wrote, when it refuses before the purge; there is no release path for a marker that outlives a call: releasing one would need a contract ruling and an audit record. The bucket must hold room for one more marker and must have no TTL, or provisioning is refused.

func (*Admin) RecordIssued added in v0.5.0

func (a *Admin) RecordIssued(ctx context.Context, r store.Issued) error

RecordIssued appends r to the issue record: one write under the user's public key. A second issue of the same key adds a revision (the bucket keeps store.IssuedHistory of them); nothing is ever removed. It fills IssuedAt (now, UTC) when empty, Owner from the Admin's owner when empty and Purpose (store.PurposeIssue) when empty; an unknown purpose is refused. The write is a compare-and-set: it keeps a revoked_at that a concurrent or earlier MarkRevoked set. Callers record before they hand the creds out, so a user that can connect is always in the record; an error means the user must not be issued.

func (*Admin) RecordIssuedChecked added in v0.5.0

func (a *Admin) RecordIssuedChecked(ctx context.Context, r store.Issued) error

RecordIssuedChecked is RecordIssued with the issue service's conditions made part of every compare-and-set attempt: when the record the write would follow has revoked_at set it fails with store.ErrKeyRevoked, and when that record is bound to another address it fails with store.ErrKeyBoundElsewhere, and when the write would move the key between the sender class (issue, rotation) and the probe class it fails with store.ErrKeyPurposeChanged; in each case nothing is written. The conditions are tested against the revision the write is made at, so a MarkRevoked or a second issuer's write that lands between a caller's earlier lookup and this write is seen, not overwritten. A caller hands a credential out only after this returns nil.

func (*Admin) ResolveInbox added in v0.5.0

func (a *Admin) ResolveInbox(ctx context.Context, address string) (InboxTarget, error)

ResolveInbox finds the directory record address names and the inbox stream to read. It reads the one directory key and nothing else: it lists no keys and creates no consumer.

func (*Admin) Resume added in v0.3.3

func (a *Admin) Resume(ctx context.Context, addr sap.Address) (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) RetireState added in v0.5.5

func (a *Admin) RetireState(ctx context.Context, addr sap.Address) (string, error)

RetireState reports the state of addr's retired marker: "" when it has none, else "pending" or "final". It reads the marker without taking the name's lock.

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, addr sap.Address, u MetaUpdate) (store.Record, error)

SetMeta changes addr'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) SetNextSubmitter added in v0.5.0

func (a *Admin) SetNextSubmitter(ctx context.Context, next string, expectedRev, ownRev uint64, held []string) (store.Marker, uint64, error)

SetNextSubmitter records next as the pending next submitter (action rotate): the planned rotation's first half. The current submitter stays in force until PromoteSubmitter, but is the only key refused from then on by a reader that expects the next one. The write is a compare-and-set on expectedRev, the marker revision the caller verified its document under: a marker at any other revision is ErrMarkerMoved and nothing is written (a recovery adopt decides then). Setting the key that is already pending writes nothing, but only when the marker is at expectedRev or at ownRev, the revision of the caller's own earlier write (0 for none). It returns the marker and its revision. Every revision stays in the bucket's history as the audit trail. The marker's other fields, the exempt set among them, are kept. held is the public keys mash holds (see ValidateNextSubmitter): next among them is ErrNextIsMashKey and nothing is written; a caller that cannot read the key store must not call at all (fail closed).

func (*Admin) SetUser added in v0.3.3

func (a *Admin) SetUser(ctx context.Context, addr sap.Address, 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, addr sap.Address, 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) Suspend added in v0.3.3

func (a *Admin) Suspend(ctx context.Context, addr sap.Address) (_ SuspendState, err error)

Suspend parks addr's inbox stream: it saves the stream's subjects in its metadata and replaces them with the one subject mash.suspended.<flat>, 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 and settled, so it is the final one.

func (*Admin) Suspended added in v0.3.3

func (a *Admin) Suspended(ctx context.Context, addr sap.Address) (SuspendState, error)

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

func (*Admin) UseClock added in v0.5.5

func (a *Admin) UseClock(f func() time.Time)

UseClock sets the clock this Admin's locks read. For tests: lets a test give two Admins clocks that disagree. Copies made from a (the With methods) keep it.

func (*Admin) UserOf added in v0.3.3

func (a *Admin) UserOf(ctx context.Context, addr sap.Address) (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, addr sap.Address) (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) WithAccountLockWait added in v0.5.0

func (a *Admin) WithAccountLockWait(d time.Duration) *Admin

WithAccountLockWait returns a copy of a that waits d, not AccountLockWait, for the account lock. a itself is unchanged.

func (*Admin) WithNameLock added in v0.3.3

func (a *Admin) WithNameLock(ctx context.Context, addr sap.Address, 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) WithNameRule added in v0.4.0

func (a *Admin) WithNameRule(rule *namerule.Rule) *Admin

WithNameRule returns a copy of a whose Provision applies rule to the address it provisions, before the directory is read (docs/name-rule.md). A nil rule accepts everything. a itself is unchanged.

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 AuditBadRecord added in v0.4.0

type AuditBadRecord struct {
	Key   string
	Error string
	User  string // the raw value's "user" field if it still yields one; used only to claim the creds, never trusted
}

AuditBadRecord is a directory key whose value does not parse as a record.

type AuditConsumer added in v0.4.0

type AuditConsumer struct {
	Pending    uint64 // messages not yet delivered
	AckPending int    // delivered and not yet acknowledged

	DeliverPolicy  string   // all, last, new, by_start_sequence, by_start_time or last_per_subject
	StartSeq       uint64   // the configured start sequence (0 unless by_start_sequence)
	StartTime      string   // the configured start time, RFC 3339 UTC (empty unless by_start_time)
	FilterSubjects []string // the configured filter subject(s), sorted; empty when unfiltered
	AckFloor       uint64   // the stream sequence at or below which every message is acknowledged
	Delivered      uint64   // the highest stream sequence delivered

	DeliveredConsumer uint64     // the consumer sequence of the last delivery
	AckFloorConsumer  uint64     // the consumer sequence of the ack floor
	DeliveredLast     *time.Time // when the last delivery was made; nil when the server reports none
	AckFloorLast      *time.Time // when the ack floor last moved; nil when the server reports none
	NumRedelivered    int        // messages redelivered and not yet acknowledged
	Created           time.Time  // when the consumer was created; zero when the server reports none
}

AuditConsumer is the drain state of an inbox stream's durable consumer (store.Consumer).

type AuditLease added in v0.4.0

type AuditLease struct {
	Key       string
	Tombstone bool
}

AuditLease is one lease key. Tombstone is the fence a deprovision leaves until it expires.

type AuditRetired added in v0.4.0

type AuditRetired struct {
	Present     bool
	Markers     []AuditRetiredMarker // sorted by key
	Bytes       uint64               // bytes the bucket's stream stores
	MaxBytes    int64                // the bucket's configured cap; 0 when it reports none
	ConfigError string               // store.VerifyRetiredStatus's refusal, empty when the bucket is as mash makes it
}

AuditRetired is the retired-name bucket as the server holds it. Present is false when there is no bucket (no retirement ever happened, or the deployment predates it); the audit never creates it.

type AuditRetiredMarker added in v0.4.0

type AuditRetiredMarker struct {
	Key    string
	Marker store.Retired
	Error  string // set when the value does not parse; Marker is then empty
}

AuditRetiredMarker is one key of the retired-name bucket: the marker, or why its value could not be read.

type AuditSnapshot added in v0.4.0

type AuditSnapshot struct {
	Records    []store.Record // sorted by directory key
	BadRecords []AuditBadRecord
	Streams    []AuditStream // every inbox-* stream, sorted by name
	Leases     []AuditLease  // every lease key except the admin locks, sorted by key
	Retired    AuditRetired  // the retired-name bucket

	LeaseRollup bool   // the lease bucket exists and its stream still allows rollup writes (it has not been hardened)
	LeaseError  string // the lease bucket exists and its stream configuration could not be read; empty otherwise
}

AuditSnapshot is mash's side of the population as the server holds it, each list sorted. It is read only.

type AuditStream added in v0.4.0

type AuditStream struct {
	Name      string // the stream name, inbox-<key>
	Msgs      uint64
	FirstSeq  uint64
	LastSeq   uint64
	Bytes     uint64    // bytes the stream stores
	MaxBytes  int64     // the stream's configured byte cap; 0 or less when it reports none
	Created   time.Time // when the stream was created; zero when the server reports none
	LastTime  time.Time // when the stream last stored a message; zero for a stream that never held one
	Subjects  []string  // as configured; for a suspended stream the parked subject
	Suspended bool
	Deliver   *AuditConsumer // nil when the stream has no deliver consumer
}

AuditStream is what the server shows of one inbox stream.

type BadRecord added in v0.5.5

type BadRecord struct {
	Key   string `json:"key"`
	Error string `json:"error"`
}

BadRecord is a directory key whose value fails store.ParseRecord: the readers skip it, with a warning that names it.

func (BadRecord) Warn added in v0.5.5

func (b BadRecord) Warn(w io.Writer, prog string)

Warn writes the warning a reader owes for a skipped record: its key and why, on one line.

type Cursor added in v0.5.0

type Cursor struct{ Stream, Consumer uint64 }

Cursor is a stream sequence and the consumer sequence that goes with it.

type EndpointState added in v0.5.6

type EndpointState struct {
	// Online is whether a live session holds the endpoint's lease. The lease expires after store.LeaseTTL, so an
	// endpoint whose session ended is offline within that time.
	Online bool
	// Suspended is whether the endpoint's inbox is parked (ADR 0057).
	Suspended bool
	// Waiting is how many stored messages the deliver consumer has not yet delivered; with no consumer, every stored
	// message. It is read only when asked for.
	Waiting uint64
}

EndpointState is what the server holds about one endpoint besides its directory record.

type InboxCheck added in v0.5.0

type InboxCheck struct {
	// Stream is the inbox stream that receives the address's mail; empty when the address has no directory record or
	// its record has no stream.
	Stream string
	// Consumer is whether the stream has the durable consumer the mail reader uses.
	Consumer bool
	// Suspended is whether the inbox is parked (ADR 0057): its stream receives no mail until it is resumed. A
	// suspended inbox is still the endpoint's own, so its saved configuration is checked like any other.
	Suspended bool
}

InboxCheck is what CheckInbox found for an address.

func (InboxCheck) Exists added in v0.5.0

func (c InboxCheck) Exists() bool

Exists is whether mail to the address has a stream and a consumer to land in.

type InboxInspection added in v0.5.0

type InboxInspection struct {
	Stream   InspectedStream
	Consumer *InspectedConsumer
	Messages []InspectedMessage
}

InboxInspection is what InspectInbox read. Consumer is nil when the stream has no `deliver` consumer.

type InboxTarget added in v0.5.0

type InboxTarget struct {
	Address string // as the caller gave it
	Flat    string // the flat key of the inbox stream that is read
	Stream  string // inbox-<flat>
}

InboxTarget is the inbox an address names.

type IncompleteHistoryError added in v0.5.0

type IncompleteHistoryError struct {
	Key      string
	Retained int
}

IncompleteHistoryError is returned by IssuedHistoryByKey for a key whose retained history cannot be shown to be complete: an older revision may have been dropped from the bucket before its history limit was raised.

func (*IncompleteHistoryError) Error added in v0.5.0

func (e *IncompleteHistoryError) Error() string

type InspectOptions added in v0.5.0

type InspectOptions struct {
	From, To uint64
	Limit    int
}

InspectOptions bound an inspection. From and To are an inclusive stream-sequence range (0 is unset) and Limit caps the messages (0 is DefaultInspectLimit). With From set the first Limit messages from it are returned; otherwise the last Limit messages up to To (or the last sequence). Either way the result is oldest first.

type InspectedConsumer added in v0.5.0

type InspectedConsumer struct {
	Name           string
	AckFloor       Cursor
	Delivered      Cursor
	NumPending     uint64
	NumRedelivered int
	NumAckPending  int
}

InspectedConsumer is what CONSUMER.INFO says of the `deliver` consumer.

type InspectedMessage added in v0.5.0

type InspectedMessage struct {
	Seq      uint64
	MsgID    string
	Sender   string
	Trust    string
	StoredAt time.Time
	Size     int
	Kind     string
	State    string
}

InspectedMessage is one stored message and its delivery state.

type InspectedStream added in v0.5.0

type InspectedStream struct {
	Name     string
	FirstSeq uint64
	LastSeq  uint64
	Messages uint64
	Bytes    uint64
}

InspectedStream is the stream's own counters.

type IssuedTimes added in v0.5.0

type IssuedTimes struct {
	// Latest is the newest revision's issued_at; Max is the greatest issued_at over all retained revisions. They differ
	// when a re-record of the same key (a reissue that keeps the key) carries an earlier time than a revision before it,
	// as after a clock rollback.
	Latest, Max time.Time
	// Revisions is how many revisions the bucket still holds of the key.
	Revisions int
	// Truncated is true when the history is at the bucket's cap: the oldest revisions may have been dropped, so Max
	// may not cover every credential ever recorded for the key.
	Truncated bool
}

IssuedTimes is every issue time the record keeps of one key.

type IssuerProblem added in v0.5.0

type IssuerProblem struct {
	// Role is "admin" (the user of the admin credentials) or "exempt" (a connected user the adoption marker exempts).
	Role string `json:"role"`
	// User is the user's public key ("" for the admin user when its key is not known to the caller).
	User string `json:"user"`
	// Issuer is the signing key that signed the user's JWT: the one that does not stay.
	Issuer string `json:"issuer"`
}

IssuerProblem is one user whose JWT is signed by a signing key that does not stay in the account JWT.

type IssuersNotKeptError added in v0.5.0

type IssuersNotKeptError struct {
	Problems []IssuerProblem
}

IssuersNotKeptError is returned by CheckIssuersKept: the users it names would stop working when the signing key that signed them leaves the account JWT. The fix is to reissue them under the account key first.

func (*IssuersNotKeptError) Error added in v0.5.0

func (e *IssuersNotKeptError) Error() string

type MalformedIssuedAtError added in v0.5.0

type MalformedIssuedAtError struct {
	Key, Value string
	Revision   uint64
}

MalformedIssuedAtError is returned by IssuedHistoryByKey for a revision whose issued_at is missing or not an RFC 3339 time.

func (*MalformedIssuedAtError) Error added in v0.5.0

func (e *MalformedIssuedAtError) Error() string

type Meta

type Meta struct {
	Role, Host  string
	Labels      map[string]string
	Description string
	Caps        []string
}

Meta is a record's optional directory metadata.

type MetaUpdate

type MetaUpdate struct {
	Role, Host  *string
	Note        *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 RefusedError added in v0.5.0

type RefusedError struct{ Msg string }

RefusedError is a refusal of an inspection that is the caller's to fix (an unknown endpoint, no stream), as against a failure to read the server.

func (*RefusedError) Error added in v0.5.0

func (e *RefusedError) Error() string

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