Documentation
¶
Overview ¶
Package web serves the browser interface of an application with its protection built in. The application supplies routes and handlers; the server applies the same checks to every request.
Listen binds the server and Serve runs it. By default it binds 127.0.0.1 and ::1.
Events serves a text/event-stream from a Source of the application and resumes it after the Last-Event-ID the browser sends back.
WebSocket serves a WebSocket endpoint of the application on a GET route; without it the server speaks no WebSocket.
CookieSessions is the Sessions implementation: a random ID that only the server issues, in a cookie, with the state in a SessionStore, in memory by default, and a tool may supply its own. Issue starts a session after a sign-in, End ends it on the server and deletes the cookie.
Authenticator turns a LoginMethod into a session, throttles failed attempts and reports sign-ins, sign-outs, failures and throttled attempts to a LoginAudit, for example for auditlog. OnceCode is the first method: the application calls Generate and shows the code in its terminal.
Pages serves the sign-in page and the sign-out for these. Sign-out takes POST only, so a tool adds a form that posts to LogoutPath.
CSRFToken returns the CSRF token of the session of a request for a form, in the field CSRFField; a script may send it in CSRFHeader instead. RequireRecent marks a route that is not public as one for sensitive steps, which runs only after a recent sign-in or a confirmation on the page at ReauthPath.
Unlocker offers the unlocking of a vault in the browser and exists only if the application makes one with NewUnlocker; without it there is no route and no way to unlock. The application passes the function that takes the passphrase and unlocks, for example through vault.Unlock or vaultproc, and the function that locks; the package imports neither. The Unlocker has no lock time of its own: when the vault locks otherwise is decided by the application, for example by the idle time of vaultproc. It locks only on Lock and Close, at once; if the function fails, the vault stays reported as unlocked, the error is returned and nothing is retried. Call Close after Serve returns so the vault does not outlive the server.
Approvals lets a person approve in the browser: its PersonChannel is a function with the signature of approval.AuthorizeOptions.PersonChannel, and web does not import approval. A call shows its prompt on a page at the configured path and waits for the form, and ends with the passphrase, ErrApprovalDeclined, ErrApprovalTimeout, ErrApprovalBusy (one request is shown at a time) or the error of the context the tool passes, which it ties to the shutdown of its server. Approvals asks for no recent sign-in; a tool that wants one wraps the routes with RequireRecent.
Static serves the files of an fs.FS such as an embed.FS for GET and HEAD, mounted as a route like "GET /". It reads the files once and answers only for a path that names one of them.
Error answers with a page that names only the status; Redirect sends a browser to another path on this server.
Always enforced ¶
Before a route runs, the server sets a strict Content Security Policy with a fresh nonce per response (read with Nonce), nosniff, a same-origin referrer policy and a same-origin resource policy, and grants no CORS access. Handlers keep the fixed headers they receive. Static files cannot carry the CSP nonce.
The server refuses a Host header other than localhost, 127.0.0.1 or [::1] with any port, or on the network the hosts of the allowed origins, which stops DNS rebinding. An unsafe request from another origin is refused through Sec-Fetch-Site and Origin; Origin: null never passes, and a request without either header comes from a client that is not a browser and passes. X-Forwarded-* and Forwarded headers are removed unless a declared proxy sent them, and a server on the network without TLS serves only a declared proxy.
Headers and bodies are bounded in size and time. A long-lived response other than an event stream clears its own deadlines with http.ResponseController. Serve waits a short time for running requests when it ends and then closes the remaining connections.
Every route pattern names its method, so a handler that changes state is not reached by GET; a pattern without a known method, a route without a handler and an invalid or conflicting pattern are refused when the server is made. A route that is not Public needs a session: without Sessions such a route is refused, unless LoginOff is chosen, which is accepted only on loopback.
An event stream refuses a handshake that comes from another site, and its Origin, if present, must be the allowed origin; Origin: null never passes. The route decides about the session as for any route. The Last-Event-ID the browser sends back is bounded in length and passed on unchanged. A stream gets a heartbeat, a deadline per write, a bounded event size and lifetime, and a bounded number of open streams per handler; it ends when the server shuts down. An event ID or type with a line break or NUL ends the stream.
A WebSocket handshake must carry exactly one Origin that is the allowed origin; Origin: null, a missing Origin and a Sec-Fetch-Site other than same-origin or none never pass, and the Origin check of the WebSocket library stays on besides. The route decides about the session as for any route. A received message is bounded in size and the wait for the next one in time, a write has a fixed deadline, the connection ends when the server shuts down, and messages are not compressed.
A session ID is 256 random bits that only the server issues, and the store keeps it under a hash of the ID. An unknown or expired ID is refused and never creates a session. Issue gives a new ID after a sign-in and ends one the request brought along. The cookie is always HttpOnly, SameSite=Strict, Path=/ and without Domain. It has the __Host- prefix and Secure, except on a Server that binds to loopback alone, which speaks plain HTTP: Safari does not store Secure cookies there and Chrome before version 138 refuses __Host-. That choice follows the Server and never a request header, and anything but such a Server, including a network server behind a proxy that terminates TLS, gets the strict form. Other local programs can read cookies of a loopback server whatever their form, which only IDs the server issued, the refusal of unknown IDs and the new ID after sign-in answer.
A one-time code is eight symbols without look-alikes, valid once, compared in constant time, replaced only by Generate and never by a request; a wrong guess does not use it up. Failed attempts, wrong or throttled, count against a limit per peer address and one for all addresses, using ratelimit; a refusal looks the same either way. On loopback every client shares one address, so the limit for all addresses is the one that holds, and a local program can lock the sign-in for one window by failing on purpose. A LoginAudit entry holds the kind, the time and the peer host, never a code or an ID.
The pages are plain, accessible markup with the CSP nonce, one-time-code autocomplete that never blocks pasting, and an error that names the field. A sign-in ends in a redirect to a fixed path of the application, never one from the request. With Pages, a GET or HEAD request without a session for a route that is not Public goes to the sign-in page, and any other method gets 401.
The CSRF token adds to the origin check and never replaces it. CookieSessions refuses an unsafe request of a session whose token is missing, wrong or from another or ended session, with 403. The token is 256 bits derived from the session ID, so it differs per session and changes with every sign-in, it is compared in constant time and read from the header or the form body, never from the URL. Reading the body consumes a multipart form, so a handler of one should use a header. A request sent by an HTML form needs the field; the sign-out of Pages takes it too when a session exists. The sign-in page has no session to bind to: it sets a cookie with the attributes of the session cookie, and its form carries a token derived from that cookie's secret, which POST to the sign-in path must return before the code is looked at. A refusal does not use up the throttle and shows the page again with a new token. Every refused token goes to LoginAudit as csrf-refused, with the peer host only, if SessionOptions.Audit (for sessions) or the Authenticator (for the sign-in page) has one. A public route other than those of Pages carries no token check of its own.
A route marked with RequireRecent runs only if the session was signed in or confirmed within PagesOptions.ReauthWithin, and the session store keeps that time as SignedIn. An older sign-in sends a GET or HEAD request to the confirmation page, which asks for the same code as the sign-in with the same throttle and the CSRF token of the session, and returns afterwards to the path the request came from; other methods get 403 and the handler does not run. The return target is a local path that starts with exactly one slash, without scheme, host, backslash or control character, else the fixed home. Confirming keeps the session ID and renews only the time. LoginAudit receives reauth and reauth-failed. Without a session a marked route is refused.
The page and the POST of an Unlocker run only with a sign-in at most two minutes old, or ReauthWithin if that is shorter. The field is type=password with autocomplete=new-password, so a browser has no saved passphrase to fill, and carries no value; the form carries the CSRF token of the session. The passphrase is read from the form body only, handed to the function once and never logged, echoed in a response, put in a URL or in an entry of LoginAudit, which receives vault-unlock, vault-unlock-failed, vault-unlock-throttled and vault-lock. Any error of the function counts as a refusal. Failed attempts are throttled by their own counter using ratelimit, apart from the sign-in throttle; a throttled attempt looks like a wrong one and does not call the function. Its page is served with Cache-Control: no-store. The browser cannot be forced not to offer to save a field, and an extension can read what is typed, which is why there is no Unlocker unless the application makes one.
The routes of Approvals are not public: the form is accepted only with a valid session, the CSRF token of that session and the origin check of the server, and a refusal leaves the request waiting. On a server with LoginOff, which has no sessions, they refuse every request. The prompt is escaped. The page has no script and no prefilled value and asks the browser not to save or fill the field, and neither it, the answer, a log nor a protocol entry holds the passphrase. Audit receives approval-submitted, approval-declined, approval-expired and approval-cancelled with the peer host only. Submitted means the form delivered a passphrase: whether Authorize accepts it is for approval to decide, and a tool that wants that verdict in its protocol records it itself.
Static answers no directory listing, no redirect, no path outside the file system and no file or directory whose name starts with a dot. The Content-Type is fixed by extension, application/octet-stream for an unknown one, next to the fixed nosniff header. Each file has an ETag of its content with Cache-Control: no-cache, so a browser revalidates and receives 304 until the content changes.
Error answers also for unknown paths and methods and for every refusal, and a status outside 400 to 599 becomes 500. Redirect sends a browser only to a path on this server, with code 301, 302, 303, 307 or 308, and refuses any other target with ErrRedirectTarget. Refusals and server errors go to the log with request values quoted.
Options ¶
- Options.Port: the loopback port. Default: 0, a free port.
- Options.Network: binds the server to another address instead of loopback. It starts only with TLS or declared proxies, with the origins browsers use and with Sessions, and Options.Port must stay 0. Default: loopback only, with the host and origin of the loopback address.
- Network.Addr: the host:port to bind. It is required with Network.
- Network.TLS: serves HTTPS directly. It must hold a certificate or a way to get one; TLS below 1.2 is never used. Default: no TLS, so a network server serves only declared proxies.
- Network.Proxies: the addresses of reverse proxies that terminate TLS. Only requests from them may carry X-Forwarded-* and Forwarded headers. Default: no proxy, and those headers are removed.
- Network.Origins: the origins browsers use, in the form https://host[:port]. They are required with Network.
- Options.Sessions: decides about every route that is not Public. Default: such routes are refused.
- Options.Login: LoginOff serves every route without a session and excludes Sessions. Default: LoginRequired, so routes that are not Public need a session.
- Route.Public: serves the route without a session. Default: the route needs a session.
- WebSocketOptions.MaxMessageBytes: the largest received message; a larger one closes the connection. Default: 64 KiB.
- WebSocketOptions.IdleTimeout: the wait for the next message before the connection closes. Default: 60 seconds.
- SessionOptions.Store: keeps the sessions. Default: in memory.
- SessionOptions.Idle: ends a session that was not used for this long. Default: 30 minutes.
- SessionOptions.Absolute: ends a session this long after it began, however active. Default: 8 hours.
- SessionOptions.Audit: receives the requests refused for a missing or wrong CSRF token. Default: no protocol.
- OnceCodeOptions.Lifetime: how long a code stays valid. Default: 5 minutes.
- OnceCodeOptions.Redactor: learns every code, so a code that reaches a log is removed. Default: none.
- AuthOptions.Audit: receives the sign-in events. Default: no protocol.
- AuthOptions.Window: how long a failed attempt counts. Default: 10 minutes.
- AuthOptions.PerAddress: the failed attempts one peer address may make per Window. Default: 5.
- AuthOptions.Global: the failed attempts from all addresses together per Window. Default: 20.
- PagesOptions.Prefix: a path put before the paths of the pages, such as "/auth" for "/auth/login". Default: none, so the pages are /login and /logout.
- PagesOptions.Home: the fixed path a browser goes to after signing in. Default: "/".
- PagesOptions.ReauthWithin: how recent the sign-in or its confirmation must be for a route marked with RequireRecent. Default: 5 minutes.
- NewUnlocker: offers the unlocking of a vault in the browser. Default: no Unlocker, so a vault cannot be unlocked in the browser.
- UnlockOptions.Window: how long a failed unlock attempt counts. Default: 10 minutes.
- UnlockOptions.Attempts: the failed unlock attempts from all addresses together per Window. Default: 5.
- UnlockOptions.Audit: receives the unlock and lock events. Default: no protocol.
- ApprovalOptions.Timeout: how long a request waits for an answer. Default: 2 minutes.
- ApprovalOptions.Audit: receives the outcomes of approvals. Default: no protocol.
- Options.Log: receives refusals and the errors of the HTTP server. Default: they are discarded.
- Options.Redactor: removes known secrets from every log line. Default: the text is logged as it is.
Index ¶
- Constants
- Variables
- func CSRFToken(r *http.Request) string
- func Error(w http.ResponseWriter, status int)
- func Events(src Source) http.Handler
- func Nonce(r *http.Request) string
- func Redirect(w http.ResponseWriter, r *http.Request, target string, code int) error
- func Static(fsys fs.FS) (http.Handler, error)
- func WebSocket(opt WebSocketOptions) http.Handler
- type ApprovalOptions
- type Approvals
- type AuthOptions
- type Authenticator
- type CookieSessions
- type Event
- type Login
- type LoginAudit
- type LoginEvent
- type LoginEventKind
- type LoginMethod
- type MemorySessionStore
- func (m *MemorySessionStore) Delete(key string) error
- func (m *MemorySessionStore) Get(key string) (SessionRecord, bool, error)
- func (m *MemorySessionStore) MarkSignIn(key string, at time.Time) (bool, error)
- func (m *MemorySessionStore) Put(key string, rec SessionRecord) error
- func (m *MemorySessionStore) Touch(key string, expires time.Time) (bool, error)
- type Network
- type OnceCode
- type OnceCodeOptions
- type Options
- type Pages
- type PagesOptions
- type Route
- type Server
- type Session
- type SessionOptions
- type SessionRecord
- type SessionStore
- type Sessions
- type Source
- type UnlockOptions
- type Unlocker
- type WebSocketConn
- type WebSocketOptions
Constants ¶
const ( // CSRFField is the name of the form field that carries the CSRF token. CSRFField = "csrf_token" // CSRFHeader is the request header that may carry the token instead, for requests a script sends. CSRFHeader = "X-CSRF-Token" )
const (
// CodeField is the form field OnceCode reads the submitted code from.
CodeField = "code"
)
const (
// PassphraseField is the name of the form field that carries the passphrase.
PassphraseField = "passphrase"
)
Variables ¶
var ( // ErrApprovalDeclined means the person refused the request in the form. ErrApprovalDeclined = errors.New("web: approval declined") // ErrApprovalTimeout means nobody answered in time. ErrApprovalTimeout = errors.New("web: approval timed out") // ErrApprovalBusy means another request still waits; only one is shown at a time. ErrApprovalBusy = errors.New("web: another approval request is waiting") )
var ErrRedirectTarget = errors.New("web: redirect target is not a path on this server")
ErrRedirectTarget reports a redirect to anything but a path on this server.
var ErrSignInRefused = errors.New("web: sign-in refused")
ErrSignInRefused is the only answer to a failed sign-in, whether the credentials were wrong or the attempt was throttled, so the answer never tells whether a code existed.
Functions ¶
func CSRFToken ¶ added in v0.25.0
CSRFToken returns the CSRF token of the session of r, for a form of a route that is not public: <input type="hidden" name="{{csrf field}}" value="...">. It is empty without a session. The token is bound to the session and changes with every sign-in. Never put it in a URL.
func Error ¶
func Error(w http.ResponseWriter, status int)
Error answers with an error page that names only the status. A status outside 400 to 599 becomes 500.
func Events ¶
Events returns the handler of an event stream fed by src, for a GET route of a Server. It panics if src is nil.
func Nonce ¶
Nonce returns the CSP nonce of the response to r. A script or style element carries it in its nonce attribute to run inline; it is empty for a request the server did not handle.
func Redirect ¶
Redirect sends a redirect with code 301, 302, 303, 307 or 308 to target, which must be an absolute path on this server such as "/items?page=2". Any other target is refused with ErrRedirectTarget and nothing is written, so a parameter can never send a browser elsewhere.
func Static ¶
Static returns a handler that serves the files of fsys, such as an embed.FS, for GET and HEAD. It reads every file once, so the answer is a snapshot and the handler never touches fsys again. A request path is looked up as a whole among those files: there is no directory listing, no redirect and no way out of fsys, and only "/" maps to index.html. Files and directories whose name starts with a dot are not served. Every file gets a fixed Content-Type by extension (application/octet-stream for an unknown one, which a browser downloads and never interprets) and an ETag of its content, with Cache-Control: no-cache so a browser revalidates and gets 304 until the content changes. Anything else answers through Error.
Files cannot carry the CSP nonce, so a served page runs only scripts and styles from its own origin.
func WebSocket ¶ added in v0.24.0
func WebSocket(opt WebSocketOptions) http.Handler
WebSocket returns the handler of a WebSocket endpoint, for a GET route of a Server. Without it the server speaks no WebSocket. It panics if opt.Handler is nil.
Types ¶
type ApprovalOptions ¶ added in v0.25.0
type ApprovalOptions struct {
// Path is where the approval page lives, an absolute path on this server without trailing slash,
// query or wildcard, such as "/approve". Required.
Path string
// Timeout is how long a request waits for an answer; 0 means 2 minutes, negative is an error.
Timeout time.Duration
// Audit receives the outcomes; nil keeps no protocol.
Audit LoginAudit
}
ApprovalOptions configure Approvals.
type Approvals ¶ added in v0.25.0
type Approvals struct {
// contains filtered or unexported fields
}
Approvals shows a request for a passphrase to the person at a browser session and hands the answer to the waiting caller. Its PersonChannel is the function approval.AuthorizeOptions expects.
func NewApprovals ¶ added in v0.25.0
func NewApprovals(opts ApprovalOptions) (*Approvals, error)
NewApprovals checks opts.
func (*Approvals) PersonChannel ¶ added in v0.25.0
PersonChannel returns a function for approval.AuthorizeOptions.PersonChannel (this package does not import approval). It makes the prompt visible on the approval page and waits for the form: it returns the passphrase the person sent, ErrApprovalDeclined if they declined, ErrApprovalTimeout after the timeout, ErrApprovalBusy if another request waits, or the error of ctx, which a tool ties to its server's shutdown. The prompt is escaped when shown.
func (*Approvals) Routes ¶ added in v0.25.0
Routes returns the page (GET) and its form (POST). Neither is public: they run behind the session, the CSRF token and the origin check of the server, none of which Approvals replaces; without a session, as on a server with LoginOff, they refuse the request. A tool may wrap the handlers with Pages.RequireRecent to ask for a recent sign-in first; Approvals asks for none itself.
type AuthOptions ¶ added in v0.24.0
type AuthOptions struct {
// Sessions issues and ends the sessions. Required.
Sessions *CookieSessions
// Method checks the credentials. Required.
Method LoginMethod
// Audit receives the events; nil keeps no protocol.
Audit LoginAudit
// Window is how long a failed attempt counts; 0 means 10 minutes.
Window time.Duration
// PerAddress is the failed attempts one peer address may make per Window; 0 means 5.
PerAddress int
// Global is the failed attempts from all addresses together per Window; 0 means 20. On loopback every
// client has the same address, and behind a proxy all clients share the proxy's, so this limit is the
// one that holds there. It also bounds the counters kept per address: only an attempt that passes it
// creates one.
Global int
}
AuthOptions configure an Authenticator.
type Authenticator ¶ added in v0.24.0
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator turns a successful LoginMethod check into a session, throttles failed attempts and reports to the protocol. It is the core that the sign-in and sign-out handlers call.
func NewAuthenticator ¶ added in v0.24.0
func NewAuthenticator(opts AuthOptions) (*Authenticator, error)
NewAuthenticator returns an Authenticator or an error for a missing Sessions or Method.
func (*Authenticator) Reauth ¶ added in v0.25.0
func (a *Authenticator) Reauth(r *http.Request) error
Reauth checks the credentials in r like SignIn, with the same throttle, and on success records the sign-in time of the session of r, which must carry one. The session ID stays. It returns ErrSignInRefused for wrong and for throttled attempts alike.
func (*Authenticator) SignIn ¶ added in v0.24.0
func (a *Authenticator) SignIn(w http.ResponseWriter, r *http.Request) error
SignIn checks the credentials in r and, if they are valid, issues a new session and sets its cookie. It returns ErrSignInRefused for wrong and for throttled attempts alike; any other error is a failure of the method or the store. Every failed attempt, including wrong ones, uses up budget until the window passes, a successful one costs nothing.
func (*Authenticator) SignOut ¶ added in v0.24.0
func (a *Authenticator) SignOut(w http.ResponseWriter, r *http.Request) error
SignOut ends the session of r on the server, deletes its cookie and reports the sign-out. It is safe without a session, which is not reported.
type CookieSessions ¶ added in v0.24.0
type CookieSessions struct {
// contains filtered or unexported fields
}
CookieSessions implements Sessions with a random ID in a cookie and the session state on the server. It also refuses an unsafe request without the CSRF token of its session.
The cookie is always HttpOnly, SameSite=Strict, Path=/ and without Domain. It carries the __Host- prefix and Secure except when the Server binds to loopback only, which it serves over plain HTTP: browsers differ on both there. Which form applies is decided by the Server that handles the request, never by a request header, and a request that reaches CookieSessions outside a Server gets the strict form.
func NewCookieSessions ¶ added in v0.24.0
func NewCookieSessions(opts SessionOptions) *CookieSessions
NewCookieSessions returns CookieSessions for Options.Sessions. Call Issue after a successful sign-in and End on sign-out.
func (*CookieSessions) End ¶ added in v0.24.0
func (c *CookieSessions) End(w http.ResponseWriter, r *http.Request) error
End ends the session of the request on the server and deletes its cookie. It is safe without a session.
func (*CookieSessions) Issue ¶ added in v0.24.0
func (c *CookieSessions) Issue(w http.ResponseWriter, r *http.Request) error
Issue starts a new session with a new ID and sets its cookie. Call it after a successful sign-in. A session the request brought along ends, so an ID known before the sign-in is worthless afterwards.
func (*CookieSessions) Session ¶ added in v0.24.0
func (c *CookieSessions) Session(w http.ResponseWriter, r *http.Request) (*http.Request, bool)
Session implements Sessions. It never creates a session: an unknown, expired or missing ID is refused and a stale cookie is cleared. Each use renews the idle period, up to the absolute limit.
type Event ¶
type Event struct {
// ID is what the browser sends back as Last-Event-ID when it reconnects; empty keeps the previous one.
// It must not contain a line break or NUL.
ID string
// Type is the event type the browser listens for; empty means "message". It must not contain a line
// break or NUL.
Type string
// Data is the payload. Each of its lines goes out as a data line of its own.
Data string
}
Event is one message of an event stream.
type LoginAudit ¶ added in v0.24.0
type LoginAudit interface {
Record(LoginEvent)
}
LoginAudit receives sign-ins, sign-outs and failed attempts, for example to write them to auditlog. Record must not block for long and must be safe for concurrent use.
type LoginEvent ¶ added in v0.24.0
type LoginEvent struct {
Kind LoginEventKind
Time time.Time
// Remote is the host of the peer address. Behind a proxy it is the proxy.
Remote string
}
LoginEvent is one entry for the protocol. It holds no credential and no session ID.
type LoginEventKind ¶ added in v0.24.0
type LoginEventKind string
LoginEventKind names what a LoginEvent reports.
const ( // ApprovalSubmitted reports a passphrase that a person sent through the form. Whether the vault accepts // it is for the application to say: this entry holds neither the passphrase nor the verdict. ApprovalSubmitted LoginEventKind = "approval-submitted" // ApprovalDeclined is a request the person refused with the button of the form. ApprovalDeclined LoginEventKind = "approval-declined" // ApprovalExpired is a request that nobody answered within the time allowed. ApprovalExpired LoginEventKind = "approval-expired" // ApprovalCancelled is a request that its context ended, for example at shutdown. ApprovalCancelled LoginEventKind = "approval-cancelled" )
const ( LoginSucceeded LoginEventKind = "login" LoginFailed LoginEventKind = "login-failed" // LoginThrottled is an attempt refused by the throttle without checking the credentials. LoginThrottled LoginEventKind = "login-throttled" LogoutDone LoginEventKind = "logout" // CSRFRefused is a request refused for a missing or wrong CSRF token, on the sign-in page or in a session. CSRFRefused LoginEventKind = "csrf-refused" // ReauthSucceeded and ReauthFailed report the confirmation of a sign-in for a sensitive route. ReauthSucceeded LoginEventKind = "reauth" ReauthFailed LoginEventKind = "reauth-failed" )
const ( // VaultUnlocked, VaultUnlockFailed and VaultUnlockThrottled report an attempt to unlock; a throttled // attempt is refused without calling the application. VaultLocked reports the lock by Lock or // Close; its Remote is empty then. VaultUnlocked LoginEventKind = "vault-unlock" VaultUnlockFailed LoginEventKind = "vault-unlock-failed" VaultUnlockThrottled LoginEventKind = "vault-unlock-throttled" VaultLocked LoginEventKind = "vault-lock" )
type LoginMethod ¶ added in v0.24.0
type LoginMethod interface {
// Verify reports whether r carries valid credentials. A false answer is an ordinary wrong attempt; an
// error means the method itself failed.
Verify(r *http.Request) (ok bool, err error)
}
LoginMethod is how a person proves who they are. Authenticator calls it once per attempt. The method reads what it needs from the request, such as a form field, and must not log or echo it. A method for a later procedure with more than one round trip keeps its own state and routes.
type MemorySessionStore ¶ added in v0.24.0
type MemorySessionStore struct {
// contains filtered or unexported fields
}
MemorySessionStore is a SessionStore in process memory. Sessions end with the process.
func NewMemorySessionStore ¶ added in v0.24.0
func NewMemorySessionStore() *MemorySessionStore
NewMemorySessionStore returns an empty MemorySessionStore.
func (*MemorySessionStore) Delete ¶ added in v0.24.0
func (m *MemorySessionStore) Delete(key string) error
func (*MemorySessionStore) Get ¶ added in v0.24.0
func (m *MemorySessionStore) Get(key string) (SessionRecord, bool, error)
func (*MemorySessionStore) MarkSignIn ¶ added in v0.25.0
func (*MemorySessionStore) Put ¶ added in v0.24.0
func (m *MemorySessionStore) Put(key string, rec SessionRecord) error
type Network ¶
type Network struct {
// Addr is the host:port to bind.
Addr string
// TLS serves HTTPS directly. It must hold a certificate or a way to get one.
TLS *tls.Config
// Proxies are the addresses of reverse proxies that terminate TLS. Only requests from them may carry
// X-Forwarded-* and Forwarded headers; without TLS no other client is served.
Proxies []netip.Prefix
// Origins are the origins browsers use, in the form https://host[:port].
Origins []string
}
Network binds the server to an address other than loopback. It starts only with TLS or with declared proxies, and only for the origins it names.
type OnceCode ¶ added in v0.24.0
type OnceCode struct {
// contains filtered or unexported fields
}
OnceCode is a LoginMethod with a code the application shows the person in the terminal. One code is valid at a time, once and for a short time. A wrong guess does not consume it, so a stranger cannot burn the code of the person; Authenticator limits the guesses instead.
func NewOnceCode ¶ added in v0.24.0
func NewOnceCode(opts OnceCodeOptions) *OnceCode
NewOnceCode returns a OnceCode that has no valid code yet.
type OnceCodeOptions ¶ added in v0.24.0
type OnceCodeOptions struct {
// Lifetime is how long a code stays valid; 0 means 5 minutes.
Lifetime time.Duration
// Redactor, if set, learns every code, so a code that reaches a log is removed.
Redactor *redact.Redactor
}
OnceCodeOptions configure OnceCode.
type Options ¶
type Options struct {
// Port is the loopback port; 0 picks a free one. It must stay 0 with Network.
Port int
// Network binds the server to another address instead of loopback.
Network *Network
// Routes are the handlers of the application.
Routes []Route
// Sessions decides about every route that is not public. Without it such routes are refused unless
// Login is LoginOff.
Sessions Sessions
// Login selects whether routes that are not public need a session.
Login Login
// Log receives refusals and the errors of the HTTP server; nil discards them.
Log io.Writer
// Redactor removes known secrets from every log line; nil leaves the text as it is.
Redactor *redact.Redactor
}
Options configure a Server. The zero value serves nothing on a free loopback port and refuses every route that is not public.
type Pages ¶ added in v0.24.0
type Pages struct {
// contains filtered or unexported fields
}
Pages serves the sign-in page and the sign-out of a Server, plain and accessible, with the CSP nonce of the server. Its routes are public; mount Routes next to the routes of the application.
func NewPages ¶ added in v0.24.0
func NewPages(opts PagesOptions) (*Pages, error)
NewPages checks opts. It also makes the sessions of opts.Auth send an unsigned-in GET or HEAD request for a route that is not public to the sign-in page instead of answering 401, because a browser has nothing else to do there. Other methods stay at 401. Call it before the server starts.
func (*Pages) LogoutPath ¶ added in v0.24.0
LogoutPath is the path that ends the session. It takes POST only, so a tool offers a form <form method="post" action="..."> with a button.
func (*Pages) ReauthPath ¶ added in v0.25.0
ReauthPath is the path of the page that asks the person to confirm the sign-in again.
func (*Pages) RequireRecent ¶ added in v0.25.0
RequireRecent wraps the handler of a route that is not public, such as one that unlocks the vault. The handler runs only if the session was signed in or confirmed within ReauthWithin. Otherwise a GET or HEAD request goes to the confirmation page and back afterwards, and any other method gets 403 without the handler running. Without a session the route is refused, also on a server without sign-in. The check is no protection for a route that is Public, which has no session.
type PagesOptions ¶ added in v0.24.0
type PagesOptions struct {
// Auth checks the codes and ends the sessions. Required.
Auth *Authenticator
// Prefix is put before the paths of the pages, such as "/auth" for "/auth/login". It is empty or
// an absolute path without a trailing slash, query or wildcard.
Prefix string
// ReauthWithin is how recent the sign-in of a session must be for a route marked with RequireRecent;
// 0 means 5 minutes.
ReauthWithin time.Duration
// Home is where a browser goes after signing in; it is fixed, never taken from the request. Empty
// means "/". It must be an absolute path on this server.
Home string
}
PagesOptions configure Pages.
type Route ¶
type Route struct {
// Pattern is a net/http ServeMux pattern that starts with its method, such as "POST /items", so a
// handler that changes state is never reached by GET.
Pattern string
Handler http.Handler
// Public routes are served without a session.
Public bool
}
Route is one handler of the application.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a bound HTTP server for browsers. Listen creates it and Serve runs it.
func (*Server) Serve ¶
Serve answers requests until ctx ends, then stops accepting, waits a short time for running requests and closes the remaining connections. It returns nil after such a shutdown.
func (*Server) URL ¶
URL is the address a browser opens: http://127.0.0.1:<port> on loopback, the first origin on the network.
type Session ¶ added in v0.24.0
type Session struct {
// Created is when the session was issued.
Created time.Time
// SignedIn is when the person last signed in or confirmed the sign-in again.
SignedIn time.Time
// contains filtered or unexported fields
}
Session is the session of a request as the route handler sees it. It carries no ID.
type SessionOptions ¶ added in v0.24.0
type SessionOptions struct {
// Store keeps the sessions; nil keeps them in memory.
Store SessionStore
// Idle ends a session that was not used for this long; 0 means 30 minutes.
Idle time.Duration
// Absolute ends a session this long after it was issued, however active; 0 means 8 hours.
Absolute time.Duration
// Audit receives the requests refused for a missing or wrong CSRF token; nil keeps no protocol.
Audit LoginAudit
}
SessionOptions configure CookieSessions. The zero value is a safe default.
type SessionRecord ¶ added in v0.24.0
type SessionRecord struct {
// Created is when the session was issued.
Created time.Time
// SignedIn is when the person last proved who they are: the sign-in, or a later confirmation. A record
// without it counts as long ago.
SignedIn time.Time
// Expires is the instant after which the session is no longer valid. A store may drop the record then.
Expires time.Time
}
SessionRecord is what a SessionStore keeps per session.
type SessionStore ¶ added in v0.24.0
type SessionStore interface {
// Put creates or replaces the record under key. It is for issuing a session, never for renewing one.
Put(key string, rec SessionRecord) error
// Touch sets Expires of the record under key and reports whether there was one. It must be atomic
// and never create a record, so a session ended meanwhile stays ended.
Touch(key string, expires time.Time) (ok bool, err error)
// MarkSignIn sets SignedIn of the record under key and reports whether there was one. Like Touch it
// must be atomic and never create a record.
MarkSignIn(key string, at time.Time) (ok bool, err error)
// Get returns the record under key; ok is false if there is none.
Get(key string) (rec SessionRecord, ok bool, err error)
// Delete removes the record under key; a missing key is not an error.
Delete(key string) error
}
SessionStore keeps sessions on the server. The key is derived from the session ID with a hash, so a store never holds an ID a browser could present; implementations must be safe for concurrent use.
type Sessions ¶
type Sessions interface {
// Session reports whether r belongs to a valid session and returns the request the route handler
// receives, for example with the session in its context; nil keeps r. On false the route handler does
// not run: Session may answer itself, such as with a redirect to a sign-in page, and otherwise the
// server answers 401.
Session(w http.ResponseWriter, r *http.Request) (*http.Request, bool)
}
Sessions decides whether a request to a route that is not public may proceed. The server consults it after the host and origin checks and before the route handler.
type Source ¶
type Source interface {
// Subscribe starts the stream for r. lastID is the Last-Event-ID of a reconnecting browser, empty on a
// first connection, so the stream can resume after it; it comes from the client and is checked only
// for its length and characters. The events of the returned channel go to the browser in order, and
// closing the channel ends the stream. Once ctx ends, the stream is gone and nothing more may be sent.
// An error refuses the stream.
Subscribe(ctx context.Context, r *http.Request, lastID string) (<-chan Event, error)
}
Source supplies the events of a stream.
type UnlockOptions ¶ added in v0.25.0
type UnlockOptions struct {
// Unlock receives the passphrase and unlocks the vault, for example through vault.Unlock or a
// vaultproc process. Any error means the passphrase was not accepted. It must not log the
// passphrase, put it in an error, or keep it. Required.
Unlock func(passphrase string) error
// Lock locks the vault again. It runs only on Lock and on Close, never by itself: when the vault locks
// otherwise is up to the application. If it fails, the Unlocker keeps the vault as unlocked, returns
// the error and does not retry. Required.
Lock func() error
// Window is how long a failed attempt counts; 0 means 10 minutes.
Window time.Duration
// Attempts is the failed attempts from all addresses together per Window; 0 means 5. It is separate
// from the throttle of the sign-in, so a wrong guess here never costs a sign-in and the reverse.
Attempts int
// Audit receives the events; nil keeps no protocol.
Audit LoginAudit
}
UnlockOptions configure an Unlocker. Without an Unlocker a server has no way to unlock a vault.
type Unlocker ¶ added in v0.25.0
type Unlocker struct {
// contains filtered or unexported fields
}
Unlocker offers the unlocking of a vault in the browser. It has no lock time of its own and locks only when told to. Make one with NewUnlocker, mount Routes next to those of the pages, and call Close when the server ends.
func NewUnlocker ¶ added in v0.25.0
func NewUnlocker(pages *Pages, opts UnlockOptions) (*Unlocker, error)
NewUnlocker checks opts. It needs the Pages of the server, which ask for a fresh sign-in.
func (*Unlocker) Close ¶ added in v0.25.0
Close locks the vault if it is unlocked. Call it after Serve returns, so the vault does not outlive the server. The Unlocker is not meant for use afterwards.
func (*Unlocker) Lock ¶ added in v0.25.0
Lock locks the vault now, if it is unlocked, and reports the lock.
func (*Unlocker) Routes ¶ added in v0.25.0
Routes returns GET and POST on UnlockPath. Both need a session whose sign-in is at most two minutes old (or ReauthWithin, if that is shorter): an older one is sent to the confirmation page, or gets 403 for the POST.
func (*Unlocker) UnlockPath ¶ added in v0.25.0
UnlockPath is the path of the page with the passphrase field.
type WebSocketConn ¶ added in v0.24.0
type WebSocketConn struct {
// contains filtered or unexported fields
}
WebSocketConn is an accepted connection. Read and Write may be used from one goroutine each.
func (*WebSocketConn) Read ¶ added in v0.24.0
func (c *WebSocketConn) Read(ctx context.Context) ([]byte, error)
Read returns the next message, text or binary. It fails once IdleTimeout passes without one, when a message exceeds MaxMessageBytes, when the peer closes, and when ctx ends or the server shuts down.
type WebSocketOptions ¶ added in v0.24.0
type WebSocketOptions struct {
// Handler runs once per accepted connection and owns the conversation. The connection closes when it
// returns. Required.
Handler func(ctx context.Context, c *WebSocketConn)
// MaxMessageBytes bounds the size of a received message; a larger one closes the connection.
// Default 64 KiB.
MaxMessageBytes int64
// IdleTimeout bounds the wait for the next message; when it passes, the connection closes.
// Default 60 seconds.
IdleTimeout time.Duration
}
WebSocketOptions configures the handler returned by WebSocket. Zero values select the safe defaults.