package admin
import "github.com/nsgo-dev/game/pkg/online/admin"Overview
Package admin is experimental: its API and documented formats may change in a minor release. See the API stability policy.
It is the operator foundation of the self-hosted services: who the operators are, what each may do, how they sign in, and an audit record of every call that changes something.
Operators are listed in operators.yaml (Operators), each with a role and an argon2id password hash, never a plaintext password. A role is a list of permission patterns, "service.action" strings such as "accounts.suspend"; the built-in roles viewer, support, moderator, operator and owner cover the common cases and the file may add its own. An operator with totp: required also signs in with a code from an authenticator app (RFC 6238); its shared secret lives in a separate file, operators.totp.yaml (TOTPSecrets), which stays out of version control.
A Server is the handler of a service's admin listener, a port of its own that is never the player-facing one. It serves sign-in (POST /admin/v1/session, which sets an HttpOnly, SameSite=Strict session cookie), sign-out, GET /admin/v1/whoami and GET /admin/v1/audit, and the routes a service registers with Handle, each behind one permission. A command-line tool or CI job authenticates with a bearer token for AdminAudience instead, signed by the account service's key. A state-changing request on a session must come from an allowed origin and carry the session's CSRF token in the X-CSRF-Token header. Every such request, refused or not, writes an audit.Record naming the operator.
Authorizer and Require let other handlers, such as gameserver.Inspector, use the same operators and permissions.
The package does not depend on NSGo, so a dedicated server or a service daemon links it without the platform layer.
Index
- Constants
- Variables
- func Allows(pattern, permission string) bool
- func BuiltinRole(name string) ([]string, bool)
- func BuiltinRoles() []string
- func HashPassword(password string, r io.Reader) (string, error)
- func LoadOperators(path string) (*Operators, *TOTPSecrets, error)
- func NewTOTPSecret(r io.Reader) (string, error)
- func TOTPCode(secret []byte, t time.Time) string
- func TOTPPath(operatorsPath string) string
- func TOTPURI(issuer, operator, secret string) string
- func TOTPUsedDir(operatorsPath string) string
- func VerifyPassword(password, hash string) (bool, error)
- type AuditLog
- type AuditWaiter
- type Authorizer
- type Call
- type Config
- type DenialRecorder
- type Duration
- type ListenOptions
- type Listener
- type Operator
- type Operators
- type Options
- type Principal
- type Route
- type Server
- func New(o Options) (*Server, error)
- func (s *Server) Authorize(r *http.Request) (*Principal, error)
- func (s *Server) CookieName() string
- func (s *Server) Handle(rt Route) (err error)
- func (s *Server) Mount(prefix string, h http.Handler) (err error)
- func (s *Server) RecordDenial(r *http.Request, p *Principal, reason, permission string)
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) SetOperators(ops *Operators, totp *TOTPSecrets) error
- type TOTPSecret
- type TOTPSecrets
Constants
const (
// DefaultSessionTTL is how long a session lasts from sign-in when Config.SessionTTL is zero.
DefaultSessionTTL = 8 * time.Hour
// DefaultIdleTimeout is how long a session lasts without a request when Config.IdleTimeout is zero.
DefaultIdleTimeout = 30 * time.Minute
// MaxSessionTTL is the longest Config.SessionTTL.
MaxSessionTTL = 24 * time.Hour
)Defaults and bounds of a session's lifetime.
const (
// MinPasswordLength is the fewest characters (Unicode code points) an operator password may have.
MinPasswordLength = 12
// MaxPasswordBytes is the longest operator password, in bytes.
MaxPasswordBytes = 1024
)Password rules for operators.
const (
// PermAuditRead lets an operator read the audit log (GET /admin/v1/audit).
PermAuditRead = "audit.read"
// PermServerRead lets an operator read a game server's runtime, match, room and peer views (gameserver.Inspector).
PermServerRead = "server.read"
// PermServerPprof lets an operator take runtime profiles of a game server (gameserver.Inspector's /admin/v1/pprof/ routes).
PermServerPprof = "server.pprof"
)Permissions of the routes this package serves itself and of gameserver.Inspector. A service names its own as "<service>.<action>", such as "accounts.suspend" or "cloudsave.restore".
const (
// RoleViewer reads everything a "<service>.read" permission covers and changes nothing.
RoleViewer = "viewer"
// RoleSupport is a viewer that also handles support requests: suspend accounts and revoke their sessions, export an account's data, read and restore cloud saves.
RoleSupport = "support"
// RoleModerator is a viewer that also acts on players' conduct: suspend accounts, revoke sessions, and delete or hide leaderboard entries.
RoleModerator = "moderator"
// RoleOperator may do everything on the accounts, cloud save, leaderboard and game server routes.
RoleOperator = "operator"
// RoleOwner may do everything, including what later services add.
RoleOwner = "owner"
)The built-in roles. operators.yaml may use them without defining them and may not redefine them.
const (
// SessionPath is where an operator signs in (POST) and out (DELETE).
SessionPath = "/admin/v1/session"
// WhoamiPath answers GET with the signed-in operator, its role and permissions.
WhoamiPath = "/admin/v1/whoami"
// AuditPath answers GET with audit records, for operators with PermAuditRead.
AuditPath = "/admin/v1/audit"
// RoutePrefix is the prefix of every admin route.
RoutePrefix = "/admin/v1/"
)The routes every Server serves itself.
const (
// CSRFHeader carries the session's CSRF token on every state-changing request made with a session cookie.
CSRFHeader = "X-CSRF-Token"
// CookieName is the session cookie's name for a Server without a Service; a Server with one names its cookie CookieName + "_" + Service, such as nsgo_admin_accounts, so the listeners of several services on one host keep their sessions apart.
CookieName = "nsgo_admin"
)Header and cookie names.
const (
// ActionSignIn is a successful sign-in.
ActionSignIn = "admin.signin"
// ActionSignInFailed is a refused sign-in: a wrong operator, password or TOTP code, a replayed code, or a locked operator.
ActionSignInFailed = "admin.signin.failed"
// ActionSignOut is a sign-out.
ActionSignOut = "admin.signout"
// ActionDenied is a refused request: no or an invalid session or token on a state-changing request, a failed CSRF check, or a missing permission. Its data names the reason and, for a missing permission, the permission.
ActionDenied = "admin.denied"
)Audit actions the Server writes itself.
const (
// DenialUnauthenticated is a state-changing request with no or an invalid session or token.
DenialUnauthenticated = "unauthenticated"
// DenialCSRF is a state-changing request on a session that failed the CSRF check.
DenialCSRF = "csrf"
// DenialPermission is a request whose operator lacks the permission.
DenialPermission = "permission"
)Reasons a DenialRecorder is given.
const (
// TOTPPeriod is the time step a code is valid for.
TOTPPeriod = 30 * time.Second
// TOTPDigits is the length of a code.
TOTPDigits = 6
)TOTP parameters: the defaults of RFC 6238 that every authenticator app supports.
const OperatorsVersion = 1OperatorsVersion is the operators file schema version this package reads and writes.
const TOTPRequired = "required"TOTPRequired is the value of Operator.TOTP that makes the operator sign in with a TOTP code as well as its password.
const TOTPSecretsVersion = 1TOTPSecretsVersion is the TOTP secrets file schema version this package reads and writes.
Variables
var (
// ErrUnauthenticated reports a request with no valid session or token.
ErrUnauthenticated = errors.New("admin: unauthenticated")
// ErrCSRF reports a state-changing request on a session that does not come from an allowed origin or does not carry the session's CSRF token.
ErrCSRF = errors.New("admin: CSRF check failed")
// ErrAuditUnavailable reports an operator's audit record that could not be queued in time, so the request it records was refused or, for a call already made, logged to Options.Logger instead.
)var ErrWeakPassword = fmt.Errorf("admin: a password needs %d to %d characters", MinPasswordLength, MaxPasswordBytes)ErrWeakPassword reports a password shorter than MinPasswordLength characters or longer than MaxPasswordBytes bytes.
Functions
func Allows(pattern, permission string) boolAllows reports whether the permission pattern grants permission. A pattern is "*" (everything), "<service>.*" (every action of a service), "*.<action>" (one action of every service, so "*.read" grants "accounts.read" but not "cloudsave.read.payload") or an exact permission.
func BuiltinRole(name string) ([]string, bool)BuiltinRole returns the permission patterns of the built-in role name, and false when there is no such built-in role.
func BuiltinRoles() []stringBuiltinRoles returns the names of the built-in roles, from the least to the most powerful.
func HashPassword(password string, r io.Reader) (string, error)HashPassword returns the argon2id hash of an operator password, in the PHC string format Operator.Password holds, with a random salt read from r. The cost is OWASP's recommendation (19 MiB of memory, 2 passes, 1 lane), as the account service's default.
func LoadOperators(path string) (*Operators, *TOTPSecrets, error)LoadOperators reads the operators file at path and, when it exists, the TOTP secrets file at TOTPPath(path), and checks that they match. The secrets file may be missing when no operator requires TOTP. Errors name the file, line and field.
func NewTOTPSecret(r io.Reader) (string, error)NewTOTPSecret returns a new random TOTP secret read from r, in the unpadded base32 that TOTPSecret.Secret and authenticator apps take.
func TOTPCode(secret []byte, t time.Time) stringTOTPCode returns the RFC 6238 code of secret at time t: TOTPDigits digits, HMAC-SHA1 and a TOTPPeriod time step, as authenticator apps compute it.
func TOTPPath(operatorsPath string) stringTOTPPath returns the path of the TOTP secrets file that belongs to the operators file at operatorsPath: the same name with ".totp.yaml" in place of its ".yaml" or ".yml" extension, or appended when it has neither, so operators.yaml keeps its secrets in operators.totp.yaml.
func TOTPURI(issuer, operator, secret string) stringTOTPURI returns the otpauth:// URI of an operator's secret that an authenticator app enrolls from, usually shown as a QR code: the account is "<issuer>:<operator>", with the issuer also as a parameter, SHA1, TOTPDigits digits and a TOTPPeriod period.
func TOTPUsedDir(operatorsPath string) stringTOTPUsedDir returns the directory, beside the operators file at operatorsPath, where the listeners that share that file record the TOTP codes they accepted (Options.TOTPUsed): the same name with ".totp-used" in place of its ".yaml" or ".yml" extension, so operators.yaml has operators.totp-used.
func VerifyPassword(password, hash string) (bool, error)VerifyPassword reports whether password matches hash, an argon2id hash in the PHC string format as HashPassword writes it, comparing in constant time.
Types
type AuditLog interface {
Log(audit.Record)
}AuditLog receives the records a Server writes. *audit.Writer is one.
type AuditWaiter interface {
LogWait(ctx context.Context, r audit.Record) error
}AuditWaiter is an AuditLog that can wait for room in its queue rather than drop a record. *audit.Writer is one. A Server whose AuditLog is one writes operators' records with LogWait: it refuses a sign-in whose record cannot be queued within ten seconds with 503, and writes the record of a call already made to Options.Logger instead.
type Authorizer interface {
Authorize(r *http.Request) (*Principal, error)
}Authorizer authenticates an admin request. It returns the operator behind the request, ErrUnauthenticated when there is none, or ErrCSRF when a state-changing request on a session fails the CSRF check; only a nil error lets the request proceed. *Server is one; gameserver.Inspector and the command registry take one.
type Call struct {
// Principal is the operator making the request.
Principal *Principal
// contains filtered or unexported fields
}Call is one authorized request to a Route: the operator and what the audit record will say.
func (c *Call) Set(key string, value any)Set adds a detail to the call's audit record. The keys method, path, status, via and remote are the Server's own.
func (c *Call) SetSubject(subject string)SetSubject names what the call acts on in its audit record, such as "account:123" or "board:weekly/acct-9".
type Config struct {
// Addr is the address the admin listener listens on, such as 127.0.0.1:9090. It must differ from the player-facing address; keep it on a private network or behind a proxy that only operators reach.
Addr string `yaml:"addr"`
// Operators is the path of the operators file (Operators). Its TOTP secrets file, when an operator needs one, is at TOTPPath of it.
Operators string `yaml:"operators"`
// Audit is the directory of the audit log, one JSON Lines file per UTC day (package audit).
Audit string `yaml:"audit"`
// AllowedOrigins are the web origins of an operator console allowed to call the listener from a browser with a session; a state-changing request on a session from any other origin, or with no origin, is refused. Command-line tools that use bearer tokens need no entry.
AllowedOrigins []string `yaml:"allowedOrigins,omitempty"`
// SessionTTL is how long a session lasts from sign-in, from 1m to MaxSessionTTL; zero means DefaultSessionTTL.
SessionTTL Duration `yaml:"sessionTTL,omitempty"`
// IdleTimeout ends a session that makes no request for this long, from 1m to the session TTL; zero means DefaultIdleTimeout or the session TTL, whichever is shorter.
IdleTimeout Duration `yaml:"idleTimeout,omitempty"`
}Config is the admin: block of a service daemon's configuration file (accountsd, cloudsaved, leaderboardd). Without it the daemon has no admin listener and serves no admin route.
admin:
addr: 127.0.0.1:9090
operators: operators.yaml
audit: audit
allowedOrigins:
- https://console.example.com
sessionTTL: 8h
idleTimeout: 30m
Relative paths are relative to the directory of the configuration file. Marshal writes the fields in this order, allowedOrigins only when it has entries and the durations only when set.
func (c *Config) Normalize()Normalize sets an empty AllowedOrigins to nil, so a parsed block marshals as it was written; a configuration's ParseConfig calls it.
func (c *Config) Validate(prefix string) errorValidate checks c, naming fields under prefix (such as "admin") in its errors.
type DenialRecorder interface {
RecordDenial(r *http.Request, p *Principal, reason, permission string)
}DenialRecorder is an Authorizer that also records refusals. Require calls it for a missing permission, a failed CSRF check and a state-changing request with no or an invalid session or token; p is nil when no operator is known.
type Duration time.DurationDuration is a time.Duration written in YAML as Go duration text ("30m", "8h").
func (d Duration) MarshalYAML() (any, error)MarshalYAML writes d as its shortest Go duration text: "30m" rather than "30m0s".
func (d *Duration) UnmarshalYAML(n *yaml.Node) errorUnmarshalYAML reads Go duration text.
type ListenOptions struct {
// Service names the service, such as "accounts".
Service string
// Tokens verifies operator bearer tokens; see Options.Tokens.
Tokens *authtoken.Verifier
// Routes are the service's operator routes, added with Server.Handle before the listener accepts connections.
Routes []Route
// Logger receives the listener's operational messages; nil discards them.
Logger *slog.Logger
}ListenOptions are what a service daemon passes to Listen besides its Config.
type Listener struct {
// Server is the listener's handler.
Server *Server
// contains filtered or unexported fields
}Listener is a running admin listener: a Server on its own address, with the audit log it writes and the operators file it reloads.
func Listen(ctx context.Context, c Config, base string, o ListenOptions) (*Listener, error)Listen starts the admin listener c describes: it loads the operators file and its TOTP secrets, opens the audit log, adds o.Routes and listens on c.Addr. Accepted TOTP codes are recorded in TOTPUsedDir of the operators file, created when first needed, so a code accepted by one listener sharing that file is refused by the others and after a restart. Relative paths in c are relative to base, the directory of the configuration file. The listener reloads the operators and secrets files when they change, keeping the files in force when the new ones do not load. Stop it with Shutdown.
func (l *Listener) Addr() stringAddr is the address the listener accepts connections on.
func (l *Listener) Err() <-chan errorErr delivers the error that stopped the listener serving, if it stops before Shutdown.
func (l *Listener) Reload() errorReload reads the operators and TOTP secrets files again and puts them in force, or returns why they do not load and keeps the files in force.
func (l *Listener) Shutdown(ctx context.Context) errorShutdown stops accepting connections, waits for the requests in flight as http.Server.Shutdown does, and flushes and closes the audit log.
type Operator struct {
// ID names the operator in audit records ("op:<id>") and tokens: 1 to 64 characters of a-z, 0-9, '.', '_' and '-', starting with a letter or digit.
ID string `yaml:"id"`
// Role is a built-in role or one of the file's Roles.
Role string `yaml:"role"`
// Password is the argon2id hash of the operator's password in the PHC string format, as HashPassword writes it; empty for an operator that signs in with bearer tokens only.
Password string `yaml:"password,omitempty"`
// TOTP is TOTPRequired when sign-in also needs a TOTP code, whose secret is in the TOTP secrets file, or empty.
TOTP string `yaml:"totp,omitempty"`
// TokensNotBefore, when set, is an RFC 3339 UTC time in whole seconds, such as 2026-11-30T12:00:00Z: bearer tokens of the operator issued before it are refused. game admin operator add sets it, so the tokens of an earlier operator with the same ID stay refused, and game admin operator revoke-tokens moves it to the present.
TokensNotBefore string `yaml:"tokensNotBefore,omitempty"`
}Operator is one operator of an operators file.
type Operators struct {
// Version is the schema version; it must be OperatorsVersion.
Version int `yaml:"version"`
// Operators are the operators, each under its own ID once.
Operators []Operator `yaml:"operators"`
// Roles are roles of the file's own, by name, each a list of permission patterns (see Allows). A name may not be one of BuiltinRoles.
Roles map[string][]string `yaml:"roles,omitempty"`
}Operators is the operators file, operators.yaml: who may use a service's admin listener, with which role, and how each operator signs in.
version: 1
operators:
- id: ada
role: owner
password: $argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g
totp: required
- id: ci
role: viewer
tokensNotBefore: 2026-11-30T12:00:00Z
roles:
support-lead:
- "*.read"
- accounts.*
An operator without a password cannot sign in with a session and uses bearer tokens only, as a CI job does. Unknown fields, duplicate keys and trailing documents are refused. Marshal writes the fields in the order above with 2-space indentation, the operators in the file's order and the roles sorted by name, so a file in that form reads back and writes again byte for byte.
func ParseOperators(data []byte) (*Operators, error)ParseOperators decodes and validates an operators file. Unknown fields, duplicate keys and trailing documents are refused, and errors name the line and field.
func (f *Operators) Marshal() ([]byte, error)Marshal validates f and encodes it as deterministic 2-space YAML.
func (f *Operators) Operator(id string) (Operator, bool)Operator returns the operator with id, and false when the file has none.
func (f *Operators) Permissions(role string) ([]string, bool)Permissions returns the permission patterns the role grants, built in or defined by the file, and false when the role is unknown.
func (f *Operators) Validate() errorValidate checks that f is a version 1 operators file: operators with valid, unique IDs, known roles, well-formed password hashes and a valid totp value, and roles with valid names and patterns that do not redefine a built-in role.
type Options struct {
// Service names the service the listener belongs to, such as "accounts": whoami reports it and the session cookie's name ends with it. Empty or 1 to 64 characters of a-z, 0-9, '.', '_' and '-'.
Service string
// Operators is the operators file. Required; SetOperators replaces it while the server runs.
Operators *Operators
// TOTP holds the secrets of the operators with totp: required; nil when none requires TOTP.
TOTP *TOTPSecrets
// TOTPUsed is a directory that records the TOTP codes accepted, one empty file per operator and time step, so a code accepted once is refused by every Server that shares the directory, including this one after a restart. Listen sets it to TOTPUsedDir of the operators file, which the services sharing that file share. Empty keeps the record in memory: a code is then refused again only by this Server until it stops.
TOTPUsed string
// Tokens verifies operator bearer tokens: a verifier for AdminAudience built from the account service's key set (authtoken.NewVerifierFor). Nil refuses bearer tokens, so operators sign in with sessions only.
Tokens *authtoken.Verifier
// Audit receives a record of every state-changing request and of every refusal. Required.
Audit AuditLog
// AuditDir is the directory GET /admin/v1/audit reads, the one Audit writes to; empty answers that route with 404.
AuditDir string
// AllowedOrigins are the web origins of an operator console; see Config.AllowedOrigins.
AllowedOrigins []string
// SessionTTL is how long a session lasts from sign-in; zero means DefaultSessionTTL.
SessionTTL time.Duration
// IdleTimeout ends a session idle this long; zero means DefaultIdleTimeout or SessionTTL, whichever is shorter.
IdleTimeout time.Duration
// Now is the clock; nil uses time.Now.
Now func() time.Time
// Rand fills session IDs and CSRF tokens; nil uses crypto/rand.
Rand io.Reader
// Logger receives operational errors; nil discards them.
Logger *slog.Logger
}Options configure a Server.
type Principal struct {
// Operator is the operator's ID in operators.yaml.
Operator string `json:"operator"`
// Role is the operator's role.
Role string `json:"role"`
// Permissions are the permission patterns the role grants.
Permissions []string `json:"permissions"`
// Via is how the request authenticated: "session" or "token".
Via string `json:"via"`
}Principal is an authenticated operator: who it is and what it may do.
func Require(a Authorizer, w http.ResponseWriter, r *http.Request, permission string) (*Principal, bool)Require authorizes r with a and checks that the principal has permission, answering 401 (no or an invalid session or token), 403 with "csrf" (a failed CSRF check) or 403 with "forbidden" (a missing permission) and returning false when it may not proceed. When a is a DenialRecorder, as *Server is, it records each refusal Server.Handle's routes record. A handler that uses Require for a state-changing request writes the audit record of a call it makes itself. A nil a refuses every request with 401.
func (p *Principal) Actor() stringActor is the principal as an audit.Record names it: "op:" and the operator's ID.
func (p *Principal) Can(permission string) boolCan reports whether one of the principal's patterns grants permission. A nil principal can do nothing.
type Route struct {
// Method is GET, POST, PUT, PATCH or DELETE.
Method string
// Path is an http.ServeMux path pattern under RoutePrefix, such as "/admin/v1/accounts/{id}/suspend"; the handler reads its wildcards with r.PathValue.
Path string
// Permission is the permission the route requires, "<service>.<action>".
Permission string
// Action is the audit record's action, "<service>.<action>"; empty means Permission.
Action string
// AuditReads also audits the route when its method is GET, for reads of personal data such as a save's payload.
AuditReads bool
// Handler serves the request once the operator is authorized. It names what it acted on with Call.SetSubject and adds details with Call.Set; the Server writes the audit record after it returns.
Handler func(w http.ResponseWriter, r *http.Request, c *Call)
}Route is an operator route a service adds with Handle.
type Server struct {
// contains filtered or unexported fields
}Server is the handler of a service's admin listener. It is safe for concurrent use; register routes with Handle before serving.
func (s *Server) Authorize(r *http.Request) (*Principal, error)Authorize returns the operator behind r: a bearer token for AdminAudience whose subject is "op:<id>" of an operator in the file, issued no earlier than the operator's TokensNotBefore, or a live session cookie of an operator whose password has not changed since sign-in. A state-changing request on a session must come from an allowed origin (or the listener's own) and carry the session's CSRF token; otherwise Authorize returns ErrCSRF with the session's operator, for the refusal's audit record.
func (s *Server) CookieName() stringCookieName returns the name of the Server's session cookie: CookieName, followed by "_" and Options.Service when it is set.
func (s *Server) Handle(rt Route) (err error)Handle adds a route. It refuses a route with an unknown method, a path outside RoutePrefix or one of the Server's own, an invalid permission or action, or no handler, and a pattern that conflicts with one already added.
func (s *Server) Mount(prefix string, h http.Handler) (err error)Mount serves h for every path under prefix, a path under RoutePrefix ending in "/" (such as "/admin/v1/pprof/") or a single path (such as "/admin/v1/runtime"), for a handler that authorizes its requests itself with the Server as its Authorizer, as gameserver.Inspector does. It refuses the Server's own paths and a pattern that conflicts with one already added.
func (s *Server) RecordDenial(r *http.Request, p *Principal, reason, permission string)RecordDenial writes an ActionDenied record of r, refused for reason (DenialUnauthenticated, DenialCSRF or DenialPermission); p is the operator, or nil for an anonymous request, whose records are throttled per remote host.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)ServeHTTP answers CORS preflight requests from the allowed origins, then serves the built-in routes and the ones added with Handle. Every response is marked uncacheable.
func (s *Server) SetOperators(ops *Operators, totp *TOTPSecrets) errorSetOperators replaces the operators and TOTP secrets in force, after checking that they match: a secret for every operator with totp: required and none for anyone else. Sessions of operators no longer in the file, or whose password changed, end with their next request.
type TOTPSecret struct {
// Operator is the ID of the operator in the operators file.
Operator string `yaml:"operator"`
// Secret is the shared key in unpadded base32.
Secret string `yaml:"secret"`
}TOTPSecret is one operator's TOTP secret.
type TOTPSecrets struct {
// Version is the schema version; it must be TOTPSecretsVersion.
Version int `yaml:"version"`
// Secrets are the operators' TOTP secrets, one per operator.
Secrets []TOTPSecret `yaml:"secrets"`
}TOTPSecrets is the TOTP secrets file, kept beside the operators file under the name TOTPPath gives and readable by the service alone:
version: 1
secrets:
- operator: ada
secret: GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
A secret is the shared key of an authenticator app in unpadded base32 (RFC 4648), 16 to 64 bytes once decoded. The file holds secrets in the clear, which a TOTP check needs, so it stays out of version control while the operators file may be reviewed. Unknown fields, duplicate keys and trailing documents are refused, and Marshal writes the secrets sorted by operator, so a file in that form reads back and writes again byte for byte.
func ParseTOTPSecrets(data []byte) (*TOTPSecrets, error)ParseTOTPSecrets decodes and validates a TOTP secrets file. Unknown fields, duplicate keys and trailing documents are refused, and errors name the line and field.
func (s *TOTPSecrets) Marshal() ([]byte, error)Marshal validates s and encodes it as deterministic 2-space YAML.
func (s *TOTPSecrets) Remove(operator string)Remove removes operator's secret, if any.
func (s *TOTPSecrets) Secret(operator string) ([]byte, bool)Secret returns the decoded TOTP secret of operator, and false when the file has none.
func (s *TOTPSecrets) Set(operator, secret string)Set sets operator's secret, keeping the secrets sorted by operator.
func (s *TOTPSecrets) Validate() errorValidate checks that s is a version 1 TOTP secrets file: one well-formed secret per operator ID.