Documentation
¶
Overview ¶
Package auth owns everything Outpost knows about people: users, groups, password hashes, sessions and the keys that sign identity tokens. It knows nothing about HTTP; the gateway builds on it.
It keeps its own database, auth.db, rather than sharing state.db. state.db is a cache of observed reality that `outpost apply` can rebuild from the manifests, and there is a test holding it to that. Users and password hashes are not observed reality: nothing can rebuild them, so they live somewhere that can be backed up and is never treated as disposable.
Index ¶
- Constants
- Variables
- func CleanClientName(name string) string
- func HashPassword(pw string, p Params) (string, error)
- func HashToken(tok string) string
- func JWKS(keys []SigningKey) ([]byte, error)
- func NeedsRehash(encoded string, p Params) bool
- func NewToken() (string, error)
- func NormalizeTailnetLogin(login string) string
- func Snapshot(src, dst string) error
- func ValidGroup(s string) error
- func ValidPassword(p string) error
- func ValidUsername(s string) error
- func VerifyPassword(pw, encoded string) (bool, error)
- type AccessToken
- type Grant
- type Params
- type Session
- type SignIn
- type SigningKey
- type Store
- func (s *Store) AddUser(u User, password string) error
- func (s *Store) Authenticate(username, password string) (User, error)
- func (s *Store) Close() error
- func (s *Store) CountAccessTokens(username string) (int, error)
- func (s *Store) CountAdmins() (int, error)
- func (s *Store) CreateAccessToken(username, name string, apps []string, ttl time.Duration) (string, AccessToken, error)
- func (s *Store) CreateGrant(username, app, clientID, clientName string) (access, refresh string, g Grant, err error)
- func (s *Store) CreateInternetAccessToken(username, name, app string, ttl time.Duration) (string, AccessToken, error)
- func (s *Store) CreateSession(username, app, parentToken, userAgent string) (string, error)
- func (s *Store) CreateSessionFrom(username, app, parentToken, userAgent, ip string) (string, error)
- func (s *Store) CurrentKey() (SigningKey, error)
- func (s *Store) EndOtherSignIns(username, keep string) (int, error)
- func (s *Store) EndSignIn(username, id string) error
- func (s *Store) GetUser(username string) (User, error)
- func (s *Store) ListAccessTokens(username string) ([]AccessToken, error)
- func (s *Store) ListGrants(username string) ([]Grant, error)
- func (s *Store) ListUsers() ([]User, error)
- func (s *Store) LookupAccessToken(secret string) (AccessToken, User, error)
- func (s *Store) LookupSession(token string) (Session, User, error)
- func (s *Store) MarkInternetUsed(id int64) (bool, error)
- func (s *Store) PruneExpired() (int, error)
- func (s *Store) PublishedKeys() ([]SigningKey, error)
- func (s *Store) RefreshGrant(refresh, clientID, app string) (access, next string, g Grant, err error)
- func (s *Store) RemoveUser(username string) error
- func (s *Store) RevokeAccessToken(id int64) (AccessToken, error)
- func (s *Store) RevokeFamily(token string) error
- func (s *Store) RevokeGrant(id int64) (Grant, error)
- func (s *Store) RevokeSession(token string) error
- func (s *Store) RevokeUserAccess(username string) (sessions, tokens int, err error)
- func (s *Store) RevokeUserSessions(username string) (int, error)
- func (s *Store) RotateKey() (SigningKey, error)
- func (s *Store) SchemaVersion() (string, error)
- func (s *Store) SetAdmin(username string, admin bool) error
- func (s *Store) SetDisabled(username string, disabled bool) error
- func (s *Store) SetPassword(username, password string) error
- func (s *Store) SetTailnetLogin(username, login string) error
- func (s *Store) SignIns(username string) ([]SignIn, error)
- func (s *Store) TouchAccessToken(t AccessToken) error
- func (s *Store) TouchFamily(token string) error
- func (s *Store) TouchSession(token string) error
- func (s *Store) UpdateGroups(username string, add, remove []string) ([]string, error)
- func (s *Store) UserForTailnetLogin(login string) (User, error)
- type User
Constants ¶
const AccessTokenPrefix = "opat_"
AccessTokenPrefix starts every personal access token. It is how the gateway tells one of its own from a bearer token that belongs to the app behind it.
const AccessTokenTouchEvery = time.Hour
AccessTokenTouchEvery is how often a token's last-used time moves. Scripts can call far more often than anyone needs that time to be accurate, and each move is a database write.
const GrantAccessTTL = time.Hour
GrantAccessTTL is how long an access token issued under a grant lasts. The client renews it with its refresh token, so it can be short.
const GrantIdleTTL = 90 * 24 * time.Hour
GrantIdleTTL is how long a grant lasts without a refresh. Each refresh extends it, so a client in use stays connected and one that has gone away lapses.
const KeyGracePeriod = 24 * time.Hour
KeyGracePeriod is how long a retired key stays in the JWKS. Identity tokens live for a minute, so a day is far more than any token needs; the slack is for apps that cache the key set.
const MinPasswordLen = 12
MinPasswordLen is the only rule a password has to meet. Length is what makes a password hard to guess; composition rules mostly make it hard to remember.
const PortalSessionTTL = 30 * 24 * time.Hour
PortalSessionTTL is how long a session lasts without being used.
const RefreshAfter = 24 * time.Hour
RefreshAfter is how stale a session's expiry has to be before a touch slides it forward. Sliding on every request would mean a database write per request for no practical gain.
const RefreshTokenPrefix = "oprt_"
RefreshTokenPrefix starts every OAuth refresh token. It differs from AccessTokenPrefix so a refresh token is never taken for an access token: the gateway only claims bearer tokens that start with opat_.
Variables ¶
var ( ErrUserExists = errors.New("user already exists") ErrNoSuchUser = errors.New("no such user") ErrBadCredentials = errors.New("wrong username or password") )
var DefaultParams = Params{Memory: 64 * 1024, Time: 3, Threads: 1, SaltLen: 16, KeyLen: 32}
DefaultParams are the settings new hashes use.
var ErrAmbiguousTailnetLogin = errors.New("tailnet login matches more than one user's email")
ErrAmbiguousTailnetLogin is a tailnet login that no user is linked to and more than one user has as their email, so it can't be said whose it is.
var ErrInvalidGrant = errors.New("invalid grant")
ErrInvalidGrant covers a refresh token that was never issued, has been replaced, belongs to a lapsed or revoked grant or a disabled user, or was presented by another client or for another app, and a grant CreateGrant won't make for what it was asked. The token endpoint answers them all with invalid_grant; any other error is the server's, not the client's.
var ErrNoSuchAccessToken = errors.New("no such access token")
ErrNoSuchAccessToken covers a token that was never issued, has expired, was revoked, or belongs to a disabled user. Callers treat them all the same, and a client isn't told which.
var ErrNoSuchGrant = errors.New("no such connected client")
ErrNoSuchGrant is a grant id that doesn't exist, or no longer does.
var ErrNoSuchSession = errors.New("no such session")
ErrNoSuchSession covers a token that was never issued, has expired, was revoked, or belongs to a disabled user. Callers treat them all the same: send the browser to log in.
var ErrRefreshReused = errors.New("refresh token reused; the grant was revoked")
ErrRefreshReused is a refresh token that was already exchanged, presented again. Rotation means only one party can hold the current token, so a second use is a copy: the grant has been revoked, and RefreshGrant returns it so the caller can say so.
Functions ¶
func CleanClientName ¶ added in v0.8.0
CleanClientName makes a name from a client's metadata document fit to show: control characters out, trimmed, and cut to clientNameMax runes. The name is the client's own claim, so callers show the client's host beside it.
func HashPassword ¶
HashPassword hashes pw with p, in PHC string format: $argon2id$v=19$m=65536,t=3,p=1$<salt>$<key>.
func HashToken ¶
HashToken is what the database stores in place of a token, so a copy of auth.db doesn't yield usable cookies. A plain SHA-256 is enough: the input is 256 random bits, not something a dictionary could guess.
func JWKS ¶
func JWKS(keys []SigningKey) ([]byte, error)
JWKS renders the public halves of keys as a JSON Web Key Set (RFC 8037), which is what an app fetches to verify X-Outpost-Identity.
func NeedsRehash ¶
NeedsRehash reports whether encoded was made with settings other than p, so a successful login can upgrade it.
func NewToken ¶
NewToken returns a fresh random token: 32 bytes, base64url without padding, so it can go in a cookie or a query string as is.
func NormalizeTailnetLogin ¶ added in v0.4.0
NormalizeTailnetLogin is a Tailscale login name in the form it is stored and compared in. Tailscale's own comparison ignores case.
func Snapshot ¶ added in v0.2.0
Snapshot copies the auth database at src to dst, a new file readable only by its owner, for `outpost update --self` to keep before a new daemon starts.
This is the one place the CLI opens auth.db itself rather than asking the daemon, and it opens it read-only. The copy has to be taken before the new daemon gets to migrate the file, and a daemon from v0.1.0, the one being updated from, has nothing on its socket that could take it. VACUUM INTO gives a consistent copy of a database another process has open, the WAL included, which copying the file would not.
func ValidGroup ¶
ValidGroup reports whether s can be used as a group name. Groups follow the username rule because they travel the same way, in X-Outpost-Groups.
func ValidPassword ¶
ValidPassword checks a new password's length, counted in characters.
func ValidUsername ¶
ValidUsername reports whether s can be used as a username.
func VerifyPassword ¶
VerifyPassword reports whether pw matches encoded. A wrong password is (false, nil); an error means the stored hash itself is unusable.
Types ¶
type AccessToken ¶
type AccessToken struct {
ID int64
Username string
Name string
Apps []string // sorted; empty means every app the user may reach
CreatedAt time.Time
ExpiresAt time.Time // zero means never
LastUsedAt time.Time // zero means never; up to AccessTokenTouchEvery behind
// Internet marks a token made to be used from the internet, through an
// app's Funnel, as well as on the tailnet. Only such a token is accepted
// there, so no token made before it was asked for gains that reach. One is
// always scoped to exactly one app and always expires.
Internet bool
// InternetUsedAt is when the token was first used from the internet;
// zero means never. Only LookupAccessToken fills it in.
InternetUsedAt time.Time
}
AccessToken is one personal access token as callers see it. It carries no hash and no secret.
func (AccessToken) Expired ¶
func (t AccessToken) Expired(now time.Time) bool
Expired reports whether the token had run out by now.
func (AccessToken) Reaches ¶
func (t AccessToken) Reaches(app string) bool
Reaches reports whether the token's scope covers an app. It says nothing about whether the user may open the app, which is decided at each request.
type Grant ¶ added in v0.8.0
type Grant struct {
ID int64
Username string
App string
ClientID string // the URL of the client's metadata document
ClientName string
CreatedAt time.Time
// RefreshedAt is when the client last renewed its access token; zero
// until it first does.
RefreshedAt time.Time
// ExpiresAt is when the grant lapses unless it is refreshed first.
ExpiresAt time.Time
}
Grant is one OAuth client's access to one app's MCP endpoint, as one user. It carries no hash and no secret.
type Params ¶
Params are argon2id's cost settings. They're stored in every hash, so they can be raised later without invalidating existing passwords.
type Session ¶
type Session struct {
Username string
App string // empty for the portal session
CreatedAt time.Time
ExpiresAt time.Time
}
Session is one live login.
type SignIn ¶
type SignIn struct {
// ID names the sign-in to the account page. It is the portal session's
// stored hash, which can't be turned back into the token.
ID string
UserAgent string
// IP is the address the sign-in came from, "" for one from before
// addresses were kept.
IP string
CreatedAt time.Time
// LastSeen is the latest use of the portal session or any app under it.
LastSeen time.Time
// Apps are the apps opened in it, by name, sorted.
Apps []string
}
SignIn is one login: a portal session and the app sessions it handed out, which end with it.
type SigningKey ¶
type SigningKey struct {
ID string // kid: base64url(sha256(pub))[:16]
Private ed25519.PrivateKey
CreatedAt time.Time
RetiredAt time.Time // zero while current
}
SigningKey is one Ed25519 key for identity tokens.
func GenerateKey ¶
func GenerateKey(now time.Time) (SigningKey, error)
GenerateKey makes a new signing key.
func (SigningKey) Public ¶
func (k SigningKey) Public() ed25519.PublicKey
Public returns the key's public half.
type Store ¶
type Store struct {
// Params are the argon2id settings for new hashes. Tests lower them.
Params Params
// contains filtered or unexported fields
}
Store is the SQLite-backed auth store. It is safe for concurrent use.
func (*Store) AddUser ¶
AddUser creates a user. An empty password creates one who can't log in until a password is set, so an account can be made before it's handed over.
func (*Store) Authenticate ¶
Authenticate checks a username and password. Every failure, whether the user is unknown, disabled, has no password or gave the wrong one, takes the same time and returns ErrBadCredentials, so the answer reveals nothing about which accounts exist.
func (*Store) CountAccessTokens ¶
CountAccessTokens reports how many unexpired tokens a user has, so whatever is about to end them can say so.
func (*Store) CountAdmins ¶
CountAdmins reports how many enabled admins there are.
func (*Store) CreateAccessToken ¶
func (s *Store) CreateAccessToken(username, name string, apps []string, ttl time.Duration) (string, AccessToken, error)
CreateAccessToken issues a token for a user and returns its secret, which is never stored and can't be recovered. No apps means every app the user may reach. A ttl of zero means it doesn't expire.
func (*Store) CreateGrant ¶ added in v0.8.0
func (s *Store) CreateGrant(username, app, clientID, clientName string) (access, refresh string, g Grant, err error)
CreateGrant records that username let a client use app's MCP endpoint, and returns the grant with its first access token and refresh token. The access token is an internet token scoped to app alone, so the gateway checks it exactly as it checks one made with `outpost token create --internet`.
func (*Store) CreateInternetAccessToken ¶ added in v0.8.0
func (s *Store) CreateInternetAccessToken(username, name, app string, ttl time.Duration) (string, AccessToken, error)
CreateInternetAccessToken issues a token that also works from the internet, for one app and with an expiry. Both are required here and not only by the CLI, because what the internet can reach with a leaked token is the whole of the risk: an unscoped or everlasting one would be all of it.
func (*Store) CreateSession ¶
CreateSession starts a session and returns its token, which is never stored. A portal session has no app and no parent. An app session names the app and the portal session it came from; ending the portal session ends it.
func (*Store) CreateSessionFrom ¶
CreateSessionFrom is CreateSession, also keeping the client address the sign-in came from, so the user can tell their sign-ins apart by something other than what their browser claims to be.
func (*Store) CurrentKey ¶
func (s *Store) CurrentKey() (SigningKey, error)
CurrentKey returns the key new tokens are signed with, generating the first one on demand.
func (*Store) EndOtherSignIns ¶
EndOtherSignIns ends every sign-in a user has except keep, the one they are using, and reports how many ended.
func (*Store) EndSignIn ¶
EndSignIn ends one of a user's sign-ins, by its ID, with every app session under it. A sign-in that is already over, or isn't theirs, is ErrNoSuchSession, so one user can't end another's by guessing.
func (*Store) ListAccessTokens ¶
func (s *Store) ListAccessTokens(username string) ([]AccessToken, error)
ListAccessTokens returns one user's tokens, or everyone's when username is empty, oldest first. Expired tokens stay listed until revoked, so whoever is working out why a script stopped can see the reason. Tokens an OAuth grant issued are left out: they renew hourly, and ListGrants shows the grant.
func (*Store) ListGrants ¶ added in v0.8.0
ListGrants returns one user's grants, or everyone's when username is empty, oldest first. Lapsed grants stay listed until revoked or until the next grant is made, so whoever is working out why a client stopped can see why.
func (*Store) LookupAccessToken ¶
func (s *Store) LookupAccessToken(secret string) (AccessToken, User, error)
LookupAccessToken returns the token a secret names and the user it belongs to, as they are now: the user's groups and admin bit are never a copy from when the token was made.
func (*Store) LookupSession ¶
LookupSession returns the session a token names and the user it belongs to. An app session is only as alive as its parent.
func (*Store) MarkInternetUsed ¶ added in v0.8.0
MarkInternetUsed records that a token has been used from the internet and reports whether this was the first time, so the activity feed says so once however many requests race to be first.
func (*Store) PruneExpired ¶
PruneExpired deletes expired sessions, and app sessions whose parent is gone, and reports how many rows went.
func (*Store) PublishedKeys ¶
func (s *Store) PublishedKeys() ([]SigningKey, error)
PublishedKeys returns the keys an app should accept: the current one, then any retired within KeyGracePeriod, newest first.
func (*Store) RefreshGrant ¶ added in v0.8.0
func (s *Store) RefreshGrant(refresh, clientID, app string) (access, next string, g Grant, err error)
RefreshGrant exchanges a refresh token for a new access token and a new refresh token, and the old one stops working. clientID and app must be the grant's. A refresh token that was already exchanged revokes the grant and returns ErrRefreshReused with it; anything else wrong is ErrInvalidGrant.
func (*Store) RemoveUser ¶
RemoveUser deletes a user; their groups, sessions and access tokens go with them.
func (*Store) RevokeAccessToken ¶
func (s *Store) RevokeAccessToken(id int64) (AccessToken, error)
RevokeAccessToken ends one token and returns what it was.
func (*Store) RevokeFamily ¶
RevokeFamily ends the login a session belongs to: its portal session and every app session under it. Logging out from any app host means this. A token that names no live session is not an error.
func (*Store) RevokeGrant ¶ added in v0.8.0
RevokeGrant ends a grant and every access token issued under it, and returns what it was.
func (*Store) RevokeSession ¶
RevokeSession ends a session and every app session derived from it. Revoking a session that doesn't exist is not an error: logging out twice should just work.
func (*Store) RevokeUserAccess ¶
RevokeUserAccess ends every session and access token a user has and reports how many of each. Counts are of live ones only: expired rows awaiting a prune were already over, and reporting them as ended would overstate what this did.
func (*Store) RevokeUserSessions ¶
RevokeUserSessions ends every session and access token a user has and reports how many sessions.
func (*Store) RotateKey ¶
func (s *Store) RotateKey() (SigningKey, error)
RotateKey retires the current key, makes a new one current, and deletes keys retired longer ago than KeyGracePeriod.
func (*Store) SchemaVersion ¶
SchemaVersion reports the schema version recorded in the database.
func (*Store) SetDisabled ¶
SetDisabled turns a user's access off or back on. Disabling ends their sessions and access tokens; enabling doesn't restore them.
func (*Store) SetPassword ¶
SetPassword replaces a user's password and ends every session and access token they have, so a password changed because it leaked actually locks the holder out: anyone who knew it could have had a token made in the meantime.
func (*Store) SetTailnetLogin ¶ added in v0.4.0
SetTailnetLogin links a Tailscale login to a user, so a connection from a device signed in to that login counts as them; "" removes the link. A login can be linked to one user at a time.
func (*Store) TouchAccessToken ¶
func (s *Store) TouchAccessToken(t AccessToken) error
TouchAccessToken records that a token was used, if the time recorded is due to move, so a busy script isn't a database write per request.
func (*Store) TouchFamily ¶
TouchFamily records that a session was used, sliding it and, for an app session, its portal session too, each on TouchSession's terms. Using any app counts as using the login, so someone who only ever opens one app isn't sent back to the login page when the untouched portal session runs out.
func (*Store) TouchSession ¶
TouchSession records that a session was used. Its expiry slides forward to a full PortalSessionTTL, but only once it was last set more than RefreshAfter ago.
func (*Store) UpdateGroups ¶
UpdateGroups adds and removes group memberships and returns the result. Adding a group the user is already in, or removing one they aren't, is not an error.
func (*Store) UserForTailnetLogin ¶ added in v0.4.0
UserForTailnetLogin finds the user a Tailscale login belongs to. A user explicitly linked to it wins. Failing that, it is the one user with no link of their own whose email is that login: someone linked elsewhere has said which login is theirs, and two users sharing an email can't both be it.
It returns the user whatever their state; the caller decides what a disabled one may do.
type User ¶
type User struct {
Username string
DisplayName string
Email string
Admin bool
Disabled bool
Groups []string // sorted
HasPassword bool
CreatedAt time.Time
LastLoginAt time.Time
Sessions int // live sessions, for `user list`
// TailnetLogin is the Tailscale login linked to this user, lower case,
// "" if none; see UserForTailnetLogin.
TailnetLogin string
}
User is one person who can log in, as callers see them. It carries no hash.