Documentation
¶
Overview ¶
Package auth is the sign-in library of the core module: argon2id passwords, cookie sessions with CSRF tokens (implementing server.Authenticator), TOTP and email two-step codes, the login rate limit, the Login flow of core INV-8 and the user and two-step rules of INV-7. The HTTP handlers are thin: they decode a request, call this package and encode the result.
Conventions: errors meant for the client are *apierr.Error (the codes of docs/API_CONVENTIONS.md 3.3); anything else is an internal failure for the handler to log and turn into a 500. Every mutation writes core_audit in its own transaction (audit.Append); audit details never carry passwords, codes or tokens. Methods that take a *sql.Tx run in the caller's transaction (so the caller can add its own changes); the others open their own with store.DB.Write. Password and key derivation always happen outside a write transaction: the single writer connection is never held for the length of an argon2 run.
Index ¶
- Constants
- Variables
- func ClearCookies() []*http.Cookie
- func DeviceCookie(value string) *http.Cookie
- func HasInvisible(s string) bool
- func MaskEmail(email string) string
- func NewTOTPSecret() ([]byte, error)
- func NewTempPassword() (string, error)
- func OTPAuthURI(account string, secret []byte) string
- func SecretBase32(secret []byte) string
- func TOTPCode(secret []byte, step int64) string
- func TOTPStep(t time.Time) int64
- func ValidatePassword(password, email string) *apierr.Error
- func ValidateUserFields(name, rawEmail string, role routes.Role) (string, *apierr.Error)
- func VerifyTOTP(secret []byte, code string, now time.Time, lastStep int64) (step int64, ok bool)
- type CodeMailer
- type Config
- type EmailCodes
- func (c *EmailCodes) Available(ctx context.Context) bool
- func (c *EmailCodes) Choosable(ctx context.Context) bool
- func (c *EmailCodes) Discard(ctx context.Context, tx *sql.Tx, userID string) error
- func (c *EmailCodes) Send(ctx context.Context, userID, email string, reuseFresh bool) (Sent, error)
- func (c *EmailCodes) Verify(ctx context.Context, userID, input string) error
- type Found
- type Info
- type Issued
- type LoginRequest
- type LoginResult
- type NewUser
- type Params
- type ProvenMailer
- type Pruned
- type SSOIdentity
- type Sent
- type Service
- func (s *Service) BeginBackupPasswordAttempt(ip netip.Addr) (refund func(), err error)
- func (s *Service) BeginSetupAttempt(ip netip.Addr) (refund func(), err error)
- func (s *Service) ChangeOwnPassword(ctx context.Context, userID, currentSessionID, current, next string) (Issued, error)
- func (s *Service) CheckAdmin(ctx context.Context, tx *sql.Tx, actorID, actorSessionID string) error
- func (s *Service) ConfirmEmail2FA(ctx context.Context, userID, currentSessionID, code string) (Issued, error)
- func (s *Service) ConfirmTOTP(ctx context.Context, userID, currentSessionID, code string) (Issued, error)
- func (s *Service) ConsoleReset(ctx context.Context, email string) (temp string, sessionsEnded int, err error)
- func (s *Service) CountSSOUsers(ctx context.Context) (int, error)
- func (s *Service) CreateUser(ctx context.Context, tx *sql.Tx, actor string, in NewUser) (User, error)
- func (s *Service) DisableTwoFA(ctx context.Context, userID, currentSessionID, password string) (Issued, error)
- func (s *Service) GetUser(ctx context.Context, id string) (User, error)
- func (s *Service) HashPassword(ctx context.Context, password, email string) (string, error)
- func (s *Service) ListUsers(ctx context.Context) ([]User, error)
- func (s *Service) Login(ctx context.Context, req LoginRequest) (LoginResult, error)
- func (s *Service) NewDevice(ctx context.Context, userID string) string
- func (s *Service) NewTempCredential(ctx context.Context) (password, hash string, err error)
- func (s *Service) Prune(ctx context.Context) (Pruned, error)
- func (s *Service) RefuseSSO(ctx context.Context, issuer, why string) error
- func (s *Service) ResendCode(ctx context.Context, email, password string, ip netip.Addr, ...) (Sent, error)
- func (s *Service) ResetPassword(ctx context.Context, actorID, actorEmail, actorSessionID, targetID string) (string, error)
- func (s *Service) ResetTwoFA(ctx context.Context, actorID, actorEmail, actorSessionID, targetID string) error
- func (s *Service) SSOSignIn(ctx context.Context, in SSOIdentity) (Issued, error)
- func (s *Service) StartEmail2FA(ctx context.Context, userID, keepSessionID, password string) (Sent, error)
- func (s *Service) StartTOTP(ctx context.Context, userID, keepSessionID, password string) (TOTPSetup, error)
- func (s *Service) UpdateOwnName(ctx context.Context, userID, keepSessionID, name string) error
- func (s *Service) UpdateUser(ctx context.Context, actorID, actorEmail, actorSessionID, targetID string, ...) (User, error)
- func (s *Service) ValidDevice(ctx context.Context, userID, cookie string) bool
- func (s *Service) VerifyOwnPassword(ctx context.Context, userID, password, wrongMsg string) error
- func (s *Service) VerifyTwoStep(ctx context.Context, userID, code, purpose, summary string) (StepUp, error)
- type Sessions
- func (s *Sessions) Authenticate(r *http.Request) (server.Principal, error)
- func (s *Sessions) CheckCSRF(r *http.Request, p server.Principal) error
- func (s *Sessions) Create(ctx context.Context, tx *sql.Tx, userID, device string, ip netip.Addr) (Issued, error)
- func (s *Sessions) CurrentID(r *http.Request) (string, error)
- func (s *Sessions) List(ctx context.Context, userID string) ([]Info, error)
- func (s *Sessions) Logout(ctx context.Context, token string) error
- func (s *Sessions) Lookup(ctx context.Context, token string) (Found, error)
- func (s *Sessions) Replace(ctx context.Context, tx *sql.Tx, userID, currentID string) (Issued, error)
- func (s *Sessions) Revoke(ctx context.Context, actorEmail, userID, sessionID string) error
- func (s *Sessions) RevokeAllForUser(ctx context.Context, tx *sql.Tx, userID string) (int, error)
- func (s *Sessions) RevokeOthers(ctx context.Context, actorEmail, userID, keepID string) (int, error)
- type StepUp
- type StepUpMailer
- type TOTPSetup
- type User
- type UserPatch
Constants ¶
const ( CodeInvalidCredentials = "invalid_credentials" //nolint:gosec // an error code, not a credential CodeTwofaRequired = "twofa_required" CodeDisabled = "disabled" CodeInvalidCode = "invalid_code" CodeWrongCode = "wrong_code" CodeNoCode = "no_code" CodeCodeExpired = "code_expired" CodeTooManyTries = "too_many_tries" CodeResendTooSoon = "resend_too_soon" CodeTooManyCodes = "too_many_codes" CodeRateLimited = "rate_limited" CodeWeakPassword = "weak_password" CodeWrongPassword = "wrong_password" CodeSamePassword = "same_password" CodeNotEmailMethod = "not_email_method" CodeAlreadyOn = "already_on" CodeNotOn = "not_on" CodeNoPending = "no_pending" CodeEmailNotReady = "email_channel_not_ready" CodeSelfDisable = "self_disable" CodeSelfReset = "self_reset" CodeLastAdmin = "last_admin" CodeDuplicate = "duplicate" CodeInvalidName = "invalid_name" CodeInvalidEmail = "invalid_email" CodeInvalidRole = "invalid_role" CodeTempExpired = "temp_password_expired" CodeTwofaReset = "twofa_reset_required" // 403: the authenticator key cannot be opened (a restore without the decryption key) CodeSSOUser = "sso_user" CodeBusy = "server_busy" // 503: too many password checks at once (the 409 `busy` of the update module is another thing) )
API error codes owned by this package (all listed in docs/API_CONVENTIONS.md 3.3).
const ( // CookieDevice is the name of the device cookie (core INV-9). CookieDevice = "__Secure-vedette_device" // DeviceLifetime is how long a device cookie stays valid after the sign-in that issued it. DeviceLifetime = 90 * 24 * time.Hour )
Device cookies, after OWASP "Slow Down Online Guessing Attacks with Device Cookies" (https://owasp.org/www-community/Slow_Down_Online_Guessing_Attacks_with_Device_Cookies).
The rate limit of sign-in is keyed by client address, and an IPv6 /64 is one key at a higher limit, so a person on the same /64 who guesses 100 times blocks everyone of that /64 for the account they aim at, the real owner included. After a successful sign-in the box therefore hands the browser a signed device cookie bound to the user. A sign-in that presents a valid cookie of that very account is counted per cookie (its own limit: loginMaxFailures in the usual window, with the same growing wait) and is exempt from the address and /64 counters, in both directions: it is not blocked by them and does not add to them. A missing, malformed, expired, forged or other-user cookie gets no exemption.
The cookie is signed with HMAC-SHA-256 under a key of the box (core_secret), carries the user id, the user's cred_version (a password change or reset kills every cookie of the account), a random nonce and an expiry. Every successful sign-in issues a new cookie with a new nonce. A stolen cookie lets a thief guess from anywhere, but only loginMaxFailures times per window per cookie, and the cookie is useless once the password changes. Only the box reads it: HttpOnly, Secure, SameSite=Strict, and a Path that only the sign-in endpoints match. It is a strictly necessary cookie for sign-in security, not tracking: the value never leaves the box.
const ( CodeTTL = 10 * time.Minute MaxCodeTries = 5 ResendAfter = 60 // seconds between two sends MaxSendsPerHour = 5 )
Email two-step codes (INV-8).
const ( MinPasswordLen = 12 MaxPasswordLen = 256 )
Password length limits, in characters. The maximum is a denial-of-service guard: argon2 work does not grow with length, but request bodies and hashing buffers do.
const ( CookieSession = "__Host-vedette_session" CookieCSRF = "__Host-vedette_csrf" HeaderCSRF = "X-CSRF-Token" )
Cookie and header names (API_CONVENTIONS 7.1, 7.2). These are the only cookies Vedette sets (INV-9).
const ( IdleTimeout = 4 * time.Hour AbsoluteTimeout = 7 * 24 * time.Hour )
Session lifetimes: a session ends after 4 hours without a request or 7 days after sign-in, whichever comes first. last_seen is refreshed at most once a minute, so a request storm does not write.
const ( CodeNoAccess = "no_access" CodeEmailInUse = "email_in_use" CodeEmailUnverified = "email_unverified" )
Codes of an SSO sign-in that core/auth decides; the protocol's own (sso_expired, sso_failed) are auth-oidc's.
const ( TOTPPeriod = 30 // seconds per step // NoStep is the lastStep to pass to VerifyTOTP when no code has been accepted yet. NoStep int64 = -1 )
TOTP parameters (RFC 6238 with the defaults every authenticator app uses).
const CodeRequired = "code_required"
CodeRequired is the 400 code of a step-up that still needs its code (API_CONVENTIONS 3.3).
const (
PruneEvery = time.Hour
)
Retention of the sign-in tables (core CONTRACT INV-30). A session is deleted a day after it ended (expired, revoked, or idle that long: nothing reads an ended session, and the audit log keeps its sign-in and sign-out); a key the user never proved and an email code an hour past their 10 minutes; a code send a day after it was sent, past the hour that MaxSendsPerHour counts.
const TempPasswordLifetime = 72 * time.Hour
TempPasswordLifetime is how long a password an administrator set can sign in. core/auth has no other one-time credential with a window of hours (email codes and the pending TOTP key last 10 minutes), so the window is the 72 hours of the decision.
Variables ¶
var DefaultParams = Params{Memory: 64 * 1024, Time: 3, Threads: 2}
DefaultParams is what new password hashes use: m=64 MiB, t=3, p=2 (OWASP-grade for a login that runs once per sign-in). Raising it later makes Params.Verify report needsRehash for older hashes. Callers outside this package get hashing through Service, which holds the argon2 concurrency cap.
var ErrBadHash = errors.New("auth: malformed password hash")
ErrBadHash is returned by Verify for a stored hash that is not a PHC argon2id string within limits.
Functions ¶
func ClearCookies ¶
ClearCookies returns the cookies that delete both cookies in the browser.
func DeviceCookie ¶
DeviceCookie returns the cookie that carries value (from LoginResult.Device).
func HasInvisible ¶
HasInvisible reports whether s has a control character (category Cc: C0, DEL, C1), an invisible format character (category Cf: bidirectional overrides and isolates, zero-width space and joiners, soft hyphen, byte order mark, tag characters), a Unicode Default_Ignorable_Code_Point (hangul fillers, combining grapheme joiner, variation selectors and others, many of them letters or marks, not Cf) or the braille blank U+2800. None belongs in a name or an email: they let a name read as another (an administrator-looking one) or make a name that cannot be typed back exactly. Used for the names of accounts and the organization. One exception: ZERO WIDTH NON-JOINER (U+200C) and ZERO WIDTH JOINER (U+200D) between two letters, which Persian, Indic and other scripts need to spell a name correctly.
func MaskEmail ¶
MaskEmail keeps the first character of the name and the whole domain: enough for a person to recognise their own mailbox, not enough to enumerate it.
func NewTOTPSecret ¶
NewTOTPSecret returns a fresh 160-bit key.
func NewTempPassword ¶
NewTempPassword returns a random 20-character password (20 x log2 55, about 115 bits) for an account an administrator created or reset. The caller shows it once; only its hash is stored.
func OTPAuthURI ¶
OTPAuthURI is the otpauth:// URI the SPA draws as a QR code.
func SecretBase32 ¶
SecretBase32 is the key as an authenticator app takes it (unpadded base32).
func TOTPCode ¶
TOTPCode returns the 6-digit code of secret for a time step (RFC 4226 dynamic truncation of HMAC-SHA1).
func ValidatePassword ¶
ValidatePassword applies the password policy to a new password: 12 to 256 characters, valid UTF-8, not equal to the account's email. It returns a 400 weak_password error, or nil.
func ValidateUserFields ¶
ValidateUserFields applies the rules of a new account's name, email and role and returns the email as it is stored (trimmed, lowercase). Handlers that must refuse in a fixed order call it before the work (hashing) that CreateUser would otherwise follow.
func VerifyTOTP ¶
VerifyTOTP checks code against the steps around now. A step at or before lastStep is refused, so a code cannot be used twice (replay protection); pass NoStep when nothing was accepted before. It returns the accepted step, which the caller must store as the new lastStep atomically with accepting the login (AdvanceTotpStep refuses a concurrent second use). Every candidate is compared in constant time.
Types ¶
type CodeMailer ¶
type CodeMailer interface {
// Available reports whether SendCode can work now: notify is on and its email channel is configured and enabled.
Available(ctx context.Context) bool
// SendCode mails the 6-digit code to the address. The implementation must not log the code.
SendCode(ctx context.Context, to, code string) error
}
CodeMailer sends two-step codes by email. The notify module implements it (core never imports notify, FORBID-2); main wires it in. A nil mailer means "unavailable".
type Config ¶
type Config struct {
DB *store.DB
Secrets *secrets.Store
Audit *audit.Log
Mailer CodeMailer // nil: email codes are unavailable
Clock func() time.Time
Log *slog.Logger
// Argon2 overrides DefaultParams. Tests lower it; production leaves it zero.
Argon2 Params
// MaxHashing caps the argon2 runs at once (each takes Argon2.Memory); 0 means half the CPUs this process
// may use (GOMAXPROCS, so a container quota counts), at least 1, and at most a quarter of the Go memory
// limit (GOMEMLIMIT) divided by Argon2.Memory.
MaxHashing int
// HashWait is how long a request waits for a free slot before 503 server_busy; 0 means 2 s.
HashWait time.Duration
}
Config wires a Service.
type EmailCodes ¶
type EmailCodes struct {
// contains filtered or unexported fields
}
EmailCodes issues and checks the one pending email code of a user (core_email_code).
func (*EmailCodes) Available ¶
func (c *EmailCodes) Available(ctx context.Context) bool
Available reports whether codes can be mailed now (a mailer exists and says so).
func (*EmailCodes) Choosable ¶
func (c *EmailCodes) Choosable(ctx context.Context) bool
Choosable reports whether a person may choose email codes now: Available, and the mailer has shown it sends (ProvenMailer).
func (*EmailCodes) Discard ¶
Discard deletes the pending code of a user inside tx (two-step turned off or reset).
func (*EmailCodes) Send ¶
Send mails a new code to the user. When mail cannot be sent it fails with 503 twofa_email_unavailable before changing anything. With reuseFresh (the sign-in page, which may be reloaded), a code sent less than 60 s ago is kept and nothing is sent. Otherwise a code asked for within 60 s of the last is 429 resend_too_soon (retry_after), and a sixth code within an hour is 429 too_many_codes. If the mailer fails after the code was stored, the code and the send record are removed again: a failed send does not use up one of the five.
func (*EmailCodes) Verify ¶
func (c *EmailCodes) Verify(ctx context.Context, userID, input string) error
Verify checks a code the user typed. The code is single use and dies after 5 wrong tries; every outcome is an *apierr.Error: no_code, code_expired (the code is deleted), invalid_code (not 6 digits; not counted), wrong_code (counted; the message says how many tries are left), too_many_tries (the code is deleted). A wrong try is saved even though the caller gets an error.
type Found ¶
type Found struct {
ID string
UserID string
Email string
Role routes.Role
StartedAt time.Time
LastSeen time.Time
ExpiresAt time.Time
// PasswordChangeRequired: the user's password was set by an administrator and not replaced yet.
PasswordChangeRequired bool
// contains filtered or unexported fields
}
Found is what Lookup knows about a valid session.
type Info ¶
type Info struct {
ID string
Device string
IP string
StartedAt time.Time
LastSeen time.Time
ExpiresAt time.Time
}
Info is a session as listed in My account.
type Issued ¶
Issued is a new session: the values the handler puts in the two cookies. The tokens exist only here; the database keeps their hashes.
type LoginRequest ¶
type LoginRequest struct {
Email string
Password string
Code string // the two-step code, empty on the first call
IP netip.Addr
UserAgent string
// DeviceCookie is the value of the __Secure-vedette_device cookie the browser sent, "" when it sent none.
DeviceCookie string
}
LoginRequest is POST /auth/login after the handler decoded it. IP is the client address (the handler parses r.RemoteAddr with netip.ParseAddrPort and refuses the request when that fails) and UserAgent the header; neither is trusted for anything but display and the rate limit. A zero IP is refused: there is no shared fallback key an attacker could fill to lock everyone out.
type LoginResult ¶
type LoginResult struct {
Session Issued
User User
// Device is the value of the device cookie to set with DeviceCookie; "" when none could be made.
Device string
}
LoginResult is a successful sign-in: the handler sets Session.Cookies() and answers 200.
type NewUser ¶
type NewUser struct {
Name string
Email string
Role routes.Role
PasswordHash string
// Temporary: an administrator chose the password: it works for TempPasswordLifetime and the user must replace it.
Temporary bool
}
NewUser is a account to create. PasswordHash comes from Service.HashPassword (which applies the policy), computed before the transaction starts.
type Params ¶
Params are the argon2id cost parameters. Memory is in KiB.
func (Params) Hash ¶
Hash returns the PHC string $argon2id$v=19$m=..,t=..,p=..$<salt>$<hash> for password (16-byte random salt, 32-byte key, unpadded standard base64).
func (Params) Verify ¶
Verify checks password against a PHC string in constant time. needsRehash is true when the hash is valid for this password but was made with parameters (or salt/key sizes) other than p's. The error is non-nil only when encoded is malformed (ErrBadHash); a wrong password is ok=false with a nil error.
type ProvenMailer ¶
ProvenMailer is the optional third interface of a CodeMailer: Proven reports whether the email channel has shown that it sends (its last test succeeded). A person may choose email two-step sign-in only then (EmailCodes.Choosable), so nobody waits for a code that cannot arrive. Sign-in and step-up codes use Available only: a failed test never locks out an account. A mailer without it is proven whenever it is available.
type Pruned ¶
type Pruned struct{ Sessions, PendingTOTP, EmailCodes, EmailCodeSends int64 }
Pruned is how many rows one Prune deleted.
type SSOIdentity ¶
type SSOIdentity struct {
Issuer, Subject string
Email string
EmailVerified *bool // nil: the ID token has no email_verified claim (Entra ID)
Name string
Role routes.Role // "" = no mapped group and no default role: no access
IP netip.Addr
UserAgent string
}
SSOIdentity is what the auth-oidc module proved about a person: it verified the ID token (signature, iss, aud, azp, exp, nonce) before calling SSOSignIn, and mapped the groups to Role. core/auth trusts these fields and nothing else from the IdP.
type Sent ¶
type Sent struct {
SentTo string // masked address, a•••@acme.example
ResendAfter int // seconds until another code may be asked for
}
Sent is the result of sending a code.
type Service ¶
type Service struct {
Sessions *Sessions
Codes *EmailCodes
// contains filtered or unexported fields
}
Service is the auth library. Create it once with New.
func (*Service) BeginBackupPasswordAttempt ¶
BeginBackupPasswordAttempt counts one guess of the password of an uploaded backup file before scrypt judges it, per client address with the limits of a sign-in, on its own counter: a mistyped file password never blocks a sign-in or the setup code of that address. Its 429 says "Too many wrong backup passwords". It returns a refund to call when the password was right (or not judged).
func (*Service) BeginSetupAttempt ¶
BeginSetupAttempt counts one guess of the first-run setup code before it is judged: per client address like a sign-in (the address, and for IPv6 its /64, with the same limits and growing wait). There is deliberately no counter for the whole box: any shared ceiling is a lever a stranger with a few dozen addresses (ten IPv6 /64s, a hundred IPv4 addresses) pulls to keep setup closed for the owner, and a 100-bit code needs none to resist guessing. It returns a refund to call when the guess was right (or never judged), or 429 rate_limited.
func (*Service) ChangeOwnPassword ¶
func (s *Service) ChangeOwnPassword(ctx context.Context, userID, currentSessionID, current, next string) (Issued, error)
ChangeOwnPassword is POST /core/account/password: the current password must be right (400 wrong_password, counted by the same rate limit as sign-in), the new one must pass the policy (weak_password) and differ (same_password). Every session of the user ends, the current one (currentSessionID) included, and a new session for the same browser is returned for the handler to set as cookies (Sessions.Replace): the user stays signed in, a copy of the old cookie does not. It also ends the limit of a temporary password: the statement that stores the hash clears core_user.temp_password_expires_at.
func (*Service) CheckAdmin ¶
CheckAdmin is adminRefusal inside the caller's transaction, for the operations that write through their own transaction (creating a user): it returns the refusal as an error, nil when the actor may go on.
func (*Service) ConfirmEmail2FA ¶
func (s *Service) ConfirmEmail2FA(ctx context.Context, userID, currentSessionID, code string) (Issued, error)
ConfirmEmail2FA turns on email-code sign-in once the mailed code is right (the code errors of EmailCodes.Verify; 409 already_on; 409 email_channel_not_ready). Like ConfirmTOTP it ends every session of the user and returns a new one for the current browser.
func (*Service) ConfirmTOTP ¶
func (s *Service) ConfirmTOTP(ctx context.Context, userID, currentSessionID, code string) (Issued, error)
ConfirmTOTP turns two-step sign-in on with the authenticator app once the user proves they hold the key: 409 no_pending (no key, or it is over 10 minutes old), 400 invalid_code (not 6 digits), 400 wrong_code, 409 already_on. The confirming code's step is recorded, so it cannot sign in a second time. Every code is a guess: it is counted on the account's two-step limiter before it is checked (429 rate_limited; given back when the code is right, like a sign-in code), and the pending key is dropped after 5 wrong codes (400 too_many_tries): without the limits a holder of any session of the account could try every code while the key is pending. Turning two-step on ends every session of the user and returns a new one for the current browser (Sessions.Replace, INV-7), empty when currentSessionID is.
func (*Service) ConsoleReset ¶
func (s *Service) ConsoleReset(ctx context.Context, email string) (temp string, sessionsEnded int, err error)
ConsoleReset is `vedette reset-admin <email>` on the box console: the way back in for an administrator who lost the two-step device or the password when no other administrator can help. Whoever runs it already holds the database and its key, so it asks for nothing else; the web has no such path. In one transaction it sets a temporary password (TempPasswordLifetime, replaced at the next sign-in), turns two-step sign-in off, ends every session of the account and writes the audit row user.console_reset. Only an active administrator who signs in with a password qualifies: others are reset by an administrator in Settings -> Users, and an SSO account signs in at its identity provider. The errors are sentences for the console.
func (*Service) CountSSOUsers ¶
CountSSOUsers is the number of accounts that sign in only through SSO (OidcConfig.sso_users).
func (*Service) CreateUser ¶
func (s *Service) CreateUser(ctx context.Context, tx *sql.Tx, actor string, in NewUser) (User, error)
CreateUser inserts an account inside the caller's transaction and writes user.create. Refusals are *apierr.Error: invalid_name (1 to 80 characters), invalid_email, invalid_role, 409 duplicate. The caller (the admin handler, or first-run setup) owns the transaction; the actor is "system" during setup.
func (*Service) DisableTwoFA ¶
func (s *Service) DisableTwoFA(ctx context.Context, userID, currentSessionID, password string) (Issued, error)
DisableTwoFA turns two-step sign-in off for the signed-in user (POST /core/account/2fa/disable): the password must be right (400 wrong_password); 409 not_on. The key or pending code is deleted and every session of the user ends, with a new one returned for the current browser: INV-7.
func (*Service) HashPassword ¶
HashPassword applies the password policy for email and hashes with the configured parameters, under the argon2 concurrency cap. A policy failure is a 400 weak_password *apierr.Error; a full queue is 503 server_busy.
func (*Service) Login ¶
func (s *Service) Login(ctx context.Context, req LoginRequest) (LoginResult, error)
Login runs the sign-in flow of core INV-8:
- the (IP, email) rate limit (IPv6 by /64): the attempt is counted up front, 429 rate_limited while blocked, before any password work. A valid device cookie of that account (device.go) swaps the address keys for its own counter;
- the password (always one argon2 run, under the concurrency cap: 503 server_busy when the box is swamped): 400 invalid_credentials, identical for an unknown email and a wrong password; a disabled account that gave the right password is 403 disabled;
- two-step sign-in, when the account has it: the account's own limiter of two-step guesses first (no IP, 429 rate_limited); without Code, 401 twofa_required with method app, or method email plus sent_to and resend_after (the code was just mailed); with a bad Code, no session: invalid_code (app) or the email-code errors of EmailCodes.Verify. An email-method account whose channel cannot send is 503 twofa_email_unavailable, never password-only. An app-method account whose key the box cannot open (a backup restored without its decryption key) is 403 twofa_reset_required, with or without Code, until an administrator resets its two-step sign-in: never password-only either; A password an administrator set that is past TempPasswordLifetime is refused here, once it is proven right: 400 temp_password_expired. One inside its window signs in, and its session is limited (server.Principal.PasswordChangeRequired);
- on success one transaction first re-reads the account and refuses when its password, disabled flag or two-step method changed since step 2 (a reset or disable that committed meanwhile wins), then creates the session, sets last_login, stores the TOTP step (a code is accepted once), upgrades an outdated password hash (only if it is still the one that was checked), and writes auth.login.
Failures write auth.login_failed (a reason, never the password or code); an unknown email is written too, as a hash, so both paths do the same work.
func (*Service) NewDevice ¶
NewDevice returns a fresh device cookie value for the user's current password, "" when none could be made (logged, never an error: the password change itself must not fail for it).
func (*Service) NewTempCredential ¶
NewTempCredential makes a random temporary password for an account an administrator creates, and its hash (computed under the argon2 concurrency cap, outside any transaction). The caller shows the password once and stores only the hash.
func (*Service) Prune ¶
Prune deletes the rows of the sign-in tables that can no longer be used, so they do not grow without end: sessions ended more than a day ago, authenticator keys never confirmed (with their sealed key in core_secret, like every other path that drops one), expired email codes and old code sends. None of them can sign anyone in, so no audit row is written (the session's own sign-in and sign-out rows stay in the audit log).
func (*Service) RefuseSSO ¶
RefuseSSO writes auth.login_failed "SSO: <why>" for a sign-in that failed before an identity was proved (state, binding, token, id_token): who is the issuer, since nobody is known yet.
func (*Service) ResendCode ¶
func (s *Service) ResendCode(ctx context.Context, email, password string, ip netip.Addr, deviceCookie string) (Sent, error)
ResendCode is POST /auth/login/resend-code: it needs the password again, so a stranger cannot make the box mail codes to someone else's mailbox. Errors: the rate limit, invalid_credentials, 403 disabled, 409 not_email_method, 503 twofa_email_unavailable, and the send limits of EmailCodes.Send.
func (*Service) ResetPassword ¶
func (s *Service) ResetPassword(ctx context.Context, actorID, actorEmail, actorSessionID, targetID string) (string, error)
ResetPassword is POST /core/users/{id}/reset-password (admin): it sets a new random temporary password (TempPasswordLifetime, replaced by the user at the next sign-in), ends every session of that user (INV-7) and returns the password. It is returned this once and never stored in the clear: the handler passes it on in the response and nowhere else.
func (*Service) ResetTwoFA ¶
func (s *Service) ResetTwoFA(ctx context.Context, actorID, actorEmail, actorSessionID, targetID string) error
ResetTwoFA is POST /core/users/{id}/2fa/reset (admin): it turns another user's two-step sign-in off, for someone who lost their phone. An administrator cannot reset their own (400 self_reset: use DisableTwoFA, which asks for the password); 404 not_found; 409 not_on. Every session of that user ends in the same transaction (INV-7): whoever held the lost phone, or the stolen password, is signed out with it.
func (*Service) SSOSignIn ¶
SSOSignIn finds or creates the account of an SSO identity and starts a session like a password sign-in, in one write transaction:
- the account is keyed by (iss, sub), never by email;
- Role "" → 403 no_access, and an existing account's sessions end (leaving the group at the IdP takes effect now);
- a new identity: no email or email_verified=false → 403 email_unverified; an email that belongs to a password account, or to an SSO account of the same issuer → 409 email_in_use (never linked); to an SSO account of another issuer (the IdP changed) → re-linked to the new (iss, sub) only when email_verified is true (user.sso_relink); else a new SSO account (user.create SSO);
- a disabled account → 403 disabled, whatever the IdP said;
- the role follows the groups at every sign-in; a change ends the account's other sessions (user.role "… (SSO groups)");
- email and name never change after creation.
Every refusal writes auth.login_failed "SSO: <reason>" in the same transaction as what it changed. No device cookie.
func (*Service) StartEmail2FA ¶
func (s *Service) StartEmail2FA(ctx context.Context, userID, keepSessionID, password string) (Sent, error)
StartEmail2FA mails a code to the user's address so they can prove the mailbox works before email-code sign-in turns on. It needs the current password (400 wrong_password, counted like a wrong sign-in password). 409 already_on; 409 email_channel_not_ready when the email channel is not set up, off, or has not passed a test (EmailCodes.Choosable); the send limits of EmailCodes.Send (resend_too_soon, too_many_codes). A caller whose account or session is gone (keepSessionID) gets nothing sent.
func (*Service) StartTOTP ¶
func (s *Service) StartTOTP(ctx context.Context, userID, keepSessionID, password string) (TOTPSetup, error)
StartTOTP creates a new unconfirmed key for the user (replacing an earlier unconfirmed one) and returns it. Turning two-step on needs the current password, like turning it off: 400 wrong_password, counted by the same account limiter as a wrong sign-in password. 409 already_on when two-step sign-in is already on. Nothing changes for sign-in until ConfirmTOTP. keepSessionID is the caller's session: when it has ended by the time the key is written, nothing is written (401).
func (*Service) UpdateOwnName ¶
UpdateOwnName changes the display name of the signed-in user (PATCH /core/account): 1 to 80 characters, no control characters (400 invalid_name). The account must not be disabled and the session (keepSessionID) must still be live when the name is written.
func (*Service) UpdateUser ¶
func (s *Service) UpdateUser(ctx context.Context, actorID, actorEmail, actorSessionID, targetID string, p UserPatch) (User, error)
UpdateUser changes a role and/or disables or enables an account (INV-7). actorID is the signed-in admin. An administrator cannot disable themselves (400 self_disable), and the change may not leave the box without an active administrator (400 last_admin) - checked on the state after the change, so demoting or disabling the last one is refused. Disabling ends all of the account's sessions. 404 not_found for an unknown id; 400 invalid_role.
func (*Service) ValidDevice ¶
ValidDevice reports whether cookie is, right now, a valid device cookie of the user userID: signed by this box, not expired, for the user's current password. A caller that is about to change the password asks before the change, then asks NewDevice for the cookie of the new password (the browser the owner already trusted keeps its exemption after a password change they just proved).
func (*Service) VerifyOwnPassword ¶
VerifyOwnPassword is the password step-up of a sensitive act of the signed-in user for callers outside this package, such as the factory reset: the same limiter and audit row as turning two-step on or off. A wrong password is 400 wrong_password with wrongMsg; too many wrong ones, 429 rate_limited.
func (*Service) VerifyTwoStep ¶
func (s *Service) VerifyTwoStep(ctx context.Context, userID, code, purpose, summary string) (StepUp, error)
VerifyTwoStep asks a signed-in user for a fresh two-step code before one sensitive act (core INV-22): purpose names the act and, for a code that must belong to one request, carries its id (for example "response.approve.req-7"); it is validated and goes into the audit, and an emailed code only passes for the purpose it was mailed for. summary is one line built by the server that says what is being approved ("Approve: Block 203.0.113.5 on Firewall A (high risk, AI request)"); the email shows it. It is 1 to 200 characters with no control or format character (a violation is a programming error: 400 invalid) and never goes into the audit. There is no sudo window: every call needs its own code and nothing is remembered.
- app method: the code must be one step after the last accepted one, so the code that just signed the user in, and a code already used here, are refused (RFC 6238 5.2). The step is stored in the same transaction as auth.stepup.
- email method: an empty code mails one (same generator, HMAC storage, lifetime and resend spacing as sign-in) and fails with 400 code_required plus the StepUp; the code is bound to purpose, so a sign-in code never passes here and a step-up code never signs in. Mail that cannot be sent is 503 twofa_email_unavailable, and so is a mailer that does not implement StepUpMailer. Step-up sends have their own budget of five an hour (the owner's sign-in codes are not used up) and write auth.stepup_code_sent.
- a user without two-step is 403 twofa_required; a disabled or unknown user gets 400 invalid_code (the userID comes from the caller's own session, so this reveals nothing the caller does not know).
- wrong codes count on the account's two-step limiter shared with sign-in: a blocked account is 429 rate_limited with retry_after.
The error is the only way to tell "passed" from "not passed": only nil means the user proved the code. auth.stepup and auth.stepup_failed carry the purpose and method, never the code.
type Sessions ¶
type Sessions struct {
// contains filtered or unexported fields
}
Sessions stores and checks sessions. It implements server.Authenticator.
func (*Sessions) Authenticate ¶
Authenticate implements server.Authenticator.
func (*Sessions) CheckCSRF ¶
CheckCSRF implements server.Authenticator: the X-CSRF-Token header must hash to the session's csrf_hash (constant-time compare). The session is looked up again because Authenticate returns only the principal.
func (*Sessions) Create ¶
func (s *Sessions) Create(ctx context.Context, tx *sql.Tx, userID, device string, ip netip.Addr) (Issued, error)
Create inserts a session for userID inside tx and returns its tokens. device is the User-Agent (cleaned and cut to 200 characters), ip the client address (the real one, not the rate-limit key).
func (*Sessions) CurrentID ¶
CurrentID returns the id of the session the request belongs to (for "this is your current session" and the 400 current_session rule), or server.ErrNoSession.
func (*Sessions) Logout ¶
Logout ends the session of a cookie value and writes auth.logout. A missing, unknown or already ended session is not an error (POST /auth/logout never fails because the session ran out).
func (*Sessions) Lookup ¶
Lookup resolves a session cookie value. An unknown, malformed, revoked, expired or idle session is server.ErrNoSession; a session of a disabled user is 403 disabled. The role is read from the database here, on every call (API_CONVENTIONS 7.4). last_seen is refreshed when it is a minute old.
func (*Sessions) Replace ¶
func (s *Sessions) Replace(ctx context.Context, tx *sql.Tx, userID, currentID string) (Issued, error)
Replace ends every live session of userID inside the caller's transaction and, when currentID is the session the caller acts from, starts a new one for the same browser (same device text and address) and returns its tokens; with an empty currentID nothing new is made and Issued is zero. It is how a password change or a change of two-step sign-in ends the user's other sessions (INV-7) while the user stays signed in: the current session's token is renewed too, so a copy of the old cookie (malware, an extension, a shared machine) does not survive the remediation (OWASP Session Management Cheat Sheet: renew the session ID after a change of privilege or re-authentication). The caller sets the new cookies.
func (*Sessions) Revoke ¶
Revoke ends one session of userID (DELETE /core/account/sessions/{id}) and writes auth.session_revoke. A session that does not exist, is already ended or belongs to someone else is apierr.NotFound. Refusing to end the caller's own session (400 current_session) is the handler's job: see CurrentID.
func (*Sessions) RevokeAllForUser ¶
RevokeAllForUser ends every live session of userID inside the caller's transaction (password reset, disabling an account, INV-7) and returns how many ended. The caller writes the audit row.
type StepUp ¶
StepUp describes the outcome of VerifyTwoStep. A nil error means the code was right and used up; then only Method is set. Without a code the call fails with 400 code_required and StepUp says where the code went: for the email method SentTo (masked address) and ResendAfter (seconds), as at sign-in.
type StepUpMailer ¶
StepUpMailer is the optional second interface of a CodeMailer: it mails a step-up code (VerifyTwoStep) with a summary of what is being approved, so the message cannot be mistaken for a sign-in code (OWASP Transaction Authorization). A mailer without it cannot serve email step-up: VerifyTwoStep answers 503 twofa_email_unavailable. summary is one line built by the server, never user text; the implementation must not log the code.
type TOTPSetup ¶
TOTPSetup is what the SPA shows when someone turns on the authenticator-app method: the key to type in and the otpauth:// URI it draws as a QR code. The key is shown once, here.
type User ¶
type User struct {
ID string
Name string
Email string
Role routes.Role
TwofaMethod string // "app", "email" or "" (two-step sign-in off)
Disabled bool
CreatedAt time.Time
LastLogin *time.Time // nil: never signed in
// PasswordChangeRequired: an administrator set the password and the user has not replaced it yet.
PasswordChangeRequired bool
// SSO: the account was made by an SSO sign-in and signs in only through the identity provider.
SSO bool
}
User is an account as the API shows it (never the password hash).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package authtest builds a ready auth.Service for tests: a migrated SQLite database, a fake clock, a fake code mailer and cheap argon2 parameters.
|
Package authtest builds a ready auth.Service for tests: a migrated SQLite database, a fake clock, a fake code mailer and cheap argon2 parameters. |