auth

package
v0.1.74 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: AGPL-3.0 Imports: 46 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package auth signs panel admins in — with passkeys (WebAuthn) or, as the fallback chosen at setup, with password + authenticator code — and manages their sessions. It implements the admin AuthService over Connect-RPC and provides the HTTP middleware that protects everything else under the admin API.

Index

Constants

View Source
const (
	EventSetup          = "setup"           // the first admin was created
	EventSignIn         = "sign_in"         // a session was opened (Method says how)
	EventSignInFailed   = "sign_in_failed"  // a wrong password or code
	EventLockout        = "lockout"         // a login was locked after too many failures
	EventPasskeyAdded   = "passkey_added"   // Settings -> Security
	EventPasskeyRemoved = "passkey_removed" // Settings -> Security
	// Settings -> Security -> "Password and code": a new password, a re-bound authenticator app, a new password login.
	EventPasswordChanged = "password_changed"
	EventTOTPRebound     = "totp_rebound"
	EventPasswordAdded   = "password_added"
)

Event kinds passed to the hook installed with SetEventHook. The panel installs one (internal/panel/telegram) that tells the owner of a lockout, a sign-in from a new address and a change to a sign-in method; the audit log stays the record (a lockout is its "lockout" row).

View Source
const (
	// TokenAccessDirect: a token of a sufficient profile may call the procedure.
	TokenAccessDirect = 1
	// TokenAccessApproved: only with a grant in the context (WithPlanning for a call that changes nothing,
	// WithApprovedStepUp for the owner's approved plan), which only the MCP layer can create. Never over /api.
	TokenAccessApproved = 2
	// TokenAccessPlanning: only for an in-process MCP call carrying WithPlanning on the MCP channel. It changes nothing
	// that matters (CheckRelay stores its own result), but the raw response is not a free tool for a script (for example,
	// GetSSHFingerprint probes a host and GetWarp contains node network details). Never over /api.
	TokenAccessPlanning = 3
)

Token access kinds, the first result of TokenAccess.

View Source
const (
	// CookieName is the session cookie. The __Host- prefix forces Secure, Path=/ and no Domain.
	CookieName = "__Host-sid"

	SetupTokenTTL    = 30 * time.Minute
	RecoveryTokenTTL = 30 * time.Minute
	CeremonyTTL      = 5 * time.Minute
	SessionIdleTTL   = 12 * time.Hour
	SessionMaxAge    = 30 * 24 * time.Hour

	// MaxSignInFailures wrong password sign-ins within FailureWindow lock the login for LockDuration.
	MaxSignInFailures = 5
	FailureWindow     = time.Hour
	LockDuration      = 15 * time.Minute
	// MaxSourceFailures failed password sign-ins from one address (IPv4, or an IPv6 /64) within FailureWindow, for
	// any logins, lock that address for LockDuration. Higher than the per-login limit: one address can be a whole
	// office behind a NAT. The lock row is keyed "ip:<SourceKey>"; a login cannot contain a colon, so the two never meet.
	MaxSourceFailures = 10
)
View Source
const NodeInstallTool = "node_install"

NodeInstallTool is the MCP tool whose approval carries the owner's SSH login choice.

View Source
const SiteverifyURL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"

SiteverifyURL is Cloudflare's verification endpoint.

View Source
const StepUpWindow = 5 * time.Minute

StepUpWindow is how long a proof of a sign-in factor keeps step-up protected calls open.

View Source
const (
	// TokenSecretPrefix starts every token secret. Neutral on purpose: no product name travels in a header.
	TokenSecretPrefix = "tk1_"
)

Variables

View Source
var ErrAdminExists = errors.New("auth: an admin already exists")

ErrAdminExists is returned by IssueSetupToken once the first admin has been created.

Functions

func ActorLabel

func ActorLabel(ctx context.Context) string

ActorLabel names the caller of an admin RPC for an event the admin reads ("who pressed it"): the admin's display name, else the id (an API token is "token:<id>"), "" when the call has no admin.

func AdminFrom

func AdminFrom(ctx context.Context) (store.Admin, bool)

AdminFrom returns the signed-in admin placed in ctx by RequireSession.

func ClientIPFrom

func ClientIPFrom(ctx context.Context) netip.Addr

ClientIPFrom returns the client address RequireSession resolved for the request (the TCP peer, or what a trusted proxy reported): the one to put in audit rows. Invalid outside RequireSession.

func ContextWithPeerIP added in v0.1.41

func ContextWithPeerIP(ctx context.Context, r *http.Request) context.Context

ContextWithPeerIP returns ctx carrying PeerIP(r) for ClientIPFrom.

func DisableTurnstile

func DisableTurnstile(ctx context.Context, st *store.Store, now time.Time) error

DisableTurnstile switches the captcha off in the database (the CLI kill switch). It keeps the keys. It works with the panel stopped or running: the panel reads the setting on every request.

func IssueSetupToken

func IssueSetupToken(ctx context.Context, st *store.Store, now time.Time) (string, error)

IssueSetupToken creates a one-time setup token (32 random bytes, stored as SHA-256, valid SetupTokenTTL from now) and invalidates earlier unused ones. It returns the plaintext token exactly once. It fails if an admin already exists.

func NeedsStepUp

func NeedsStepUp(path string) bool

NeedsStepUp reports whether the procedure's handler asks for a step-up.

func NewTokenSecret

func NewTokenSecret() string

NewTokenSecret returns a fresh token secret: the prefix and 256 random bits, URL-safe.

func ParseProxies

func ParseProxies(list []string) ([]netip.Prefix, error)

ParseProxies parses --trusted-proxy values: CIDRs ("10.0.0.0/8") or single addresses.

func PeerIP added in v0.1.41

func PeerIP(r *http.Request) netip.Addr

PeerIP is the address of the TCP peer of r, with no proxy trusted: the client address of a server that has no auth service. (The edge sets RemoteAddr from CF-Connecting-IP.)

func ProcedureRole

func ProcedureRole(path string) string

ProcedureRole is the lowest role that may call a procedure: "readonly", "helper" or "owner". Unknown procedures need the owner.

func SealNodeInstallSecret added in v0.1.15

func SealNodeInstallSecret(v *vault.Vault, planID string, s NodeInstallSecret) []byte

SealNodeInstallSecret seals what the owner entered to plan planID (the approval does it; tests too).

func SourceKey

func SourceKey(a netip.Addr) string

SourceKey is the rate-limit and ceremony-cap key for a client: the address for IPv4, the /64 for IPv6 (a single subscriber is handed a whole /64, so per-address limits are free to evade).

func TokenAccess

func TokenAccess(path string) (access int, ok bool)

TokenAccess says how a token may reach a procedure: TokenAccessDirect, TokenAccessApproved or TokenAccessPlanning; ok is false when the procedure is closed to tokens.

func TokenProcedureRole added in v0.1.24

func TokenProcedureRole(path string) string

TokenProcedureRole is the minimum profile role for a token to call a procedure. It may be narrower than ProcedureRole when the MCP layer safely projects a response before returning it.

func WithAdmin added in v0.1.22

func WithAdmin(ctx context.Context, a store.Admin) context.Context

WithAdmin returns ctx carrying a as RequireSession would put it, for tests of modules that read AdminFrom. A request cannot reach it: only the middleware sets the admin of a real call.

func WithChannel

func WithChannel(ctx context.Context, c Channel) context.Context

WithChannel marks ctx as belonging to a call the MCP layer makes in process: RequireSession then counts the call as "mcp:<id>", audits it with source mcp and does not charge the token's rate limit again (the /mcp request already paid it). The token is still verified against the database on every call. Only ChannelMCP has an effect, and only code that holds the context can set it: a network request cannot.

func WithPlanning

func WithPlanning(ctx context.Context) context.Context

WithPlanning lets a TokenAccessApproved procedure through only when its request flag guarantees no change: ApplyFix and UpdateProfile dry runs, CreateInbound validation, and UpdateGroup dry runs. The MCP layer uses it while making plans. It does not open step-up, and it counts only on the MCP channel.

Types

type Channel

type Channel string

Channel is how a token call arrived.

const (
	// ChannelAPI is a Connect-RPC call with a Bearer header (a script).
	ChannelAPI Channel = "api"
	// ChannelMCP is a call the MCP layer makes in process on behalf of an agent.
	ChannelMCP Channel = "mcp"
)

type Config

type Config struct {
	RPID    string   // e.g. "localhost" or "example.com"
	RPName  string   // shown by the authenticator; defaults to "Mistgate"
	Origins []string // allowed browser origins, e.g. "https://k7q2x9.example.com"
	// Vault seals the TOTP secrets at rest. Without it password sign-in is unavailable.
	Vault *vault.Vault
	// TrustedProxies are the reverse proxies whose X-Forwarded-For / Forwarded headers are
	// believed when working out the client address (rate limit, audit log, sessions).
	TrustedProxies []netip.Prefix
	// TurnstileURL is the Cloudflare siteverify endpoint; empty means SiteverifyURL. Tests point it at a fake.
	TurnstileURL string
	// HTTPClient makes the siteverify call; nil means a client with a 5 s timeout.
	HTTPClient *http.Client
	// Limiter is the shared backend for security-sensitive limits. Nil uses bounded in-memory state.
	Limiter securitylimit.Limiter
	// SourceURL is where the panel's source code is published; Me hands it to the admin, which links it next to the
	// version. Empty = no link.
	SourceURL string
}

Config is the relying-party configuration and what the service needs from its host.

type Event

type Event struct {
	Kind    string
	Time    time.Time
	AdminID string    // "" when the login matched no admin
	Login   string    // password sign-ins: the login, only when it names a real admin
	Method  string    // "passkey" or "password" where it applies
	IP      string    // client address, "" if unknown
	Until   time.Time // EventLockout: when the lock ends
}

Event is what a hook gets to react to. It carries no secrets.

type NodeInstallSecret added in v0.1.15

type NodeInstallSecret struct {
	Password    string `json:"password"`
	Fingerprint string `json:"fingerprint"`
	PanelKey    bool   `json:"panel_key,omitempty"`
}

NodeInstallSecret is what the owner chooses when approving a node_install plan. The approval seals it to the plan; ProvisioningService.StartNodeProvision opens it once, for that plan's apply, and uses that login only with this fingerprint. The agent never sees a password or private key.

func OpenNodeInstallSecret added in v0.1.15

func OpenNodeInstallSecret(v *vault.Vault, planID string, sealed []byte) (NodeInstallSecret, error)

OpenNodeInstallSecret opens what ApproveMCPPlanWithSecret stored for plan planID.

type Principal

type Principal struct {
	Token     bool   // false: an admin signed in with a cookie session
	TokenID   string // "tok_..." when Token
	Profile   string // store.ProfileReadonly | ProfileOperator | ProfileAdmin
	Channel   Channel
	Name      string    // the token's name
	ExpiresAt time.Time // when the token stops working
}

Principal describes the token behind a request. The zero value is a signed-in admin (a cookie session).

func PrincipalFrom

func PrincipalFrom(ctx context.Context) Principal

PrincipalFrom returns the token principal RequireSession or RequireBearer put into ctx; the zero Principal for a cookie session or outside the middleware.

func (Principal) ActorID

func (p Principal) ActorID() string

ActorID is the id the audit log shows for the principal: "token:<id>" for the API channel, "mcp:<id>" for MCP.

type ProxyTrust

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

ProxyTrust says which peers are reverse proxies whose X-Forwarded-For / Forwarded headers may be believed. The zero value trusts nobody: the client address is the TCP peer, whatever the headers say.

func NewProxyTrust

func NewProxyTrust(p []netip.Prefix) ProxyTrust

NewProxyTrust trusts the given networks.

func (ProxyTrust) ClientIP

func (t ProxyTrust) ClientIP(remoteAddr string, h http.Header) netip.Addr

ClientIP returns the address of the client behind remoteAddr ("host:port" as in http.Request.RemoteAddr). Headers are read only when the peer itself is a trusted proxy. Then the chain is walked from the right (the proxy nearest to us appended last) and the first address that is not itself a trusted proxy is the client, so values the client put at the left of the header are never believed. X-Forwarded-For and Forwarded are both understood; if a request carries both and they name different clients, neither is believed and the proxy's own address is returned (one shared bucket for that request, instead of letting a spoofed header pick one). An unparseable chain falls back to the peer as well.

type ResetLoginInput

type ResetLoginInput struct {
	// Login is the password login to reset, or (when no admin has it yet) the login to give a passkey-only admin.
	Login string
	// AdminID picks that passkey-only admin; empty is fine when the panel has exactly one admin.
	AdminID string
	// Actor is the audit actor. Empty retains the CLI actor used by the VPS command.
	Actor string
	// IP is the client address for an HTTP-triggered reset, or invalid for the local CLI.
	IP netip.Addr
}

ResetLoginInput says whose login `mistgate auth reset-login` resets.

type ResetLoginResult

type ResetLoginResult struct {
	Admin         store.Admin
	Login         string
	Password      string
	TOTPURI       string
	TOTPSecret    string // base32, for typing into the app
	Created       bool   // the admin had no password login before
	SessionsEnded int
}

ResetLoginResult is what the operator is shown once: the new password and the new authenticator secret.

func ResetLogin

func ResetLogin(ctx context.Context, st *store.Store, v *vault.Vault, in ResetLoginInput, now time.Time) (ResetLoginResult, error)

ResetLogin is the way back in for an admin who lost the phone: run on the panel's own server (the database and the master key are files only root, or the panel's own user, can read, so whoever can run it owns the panel already). It gives the admin a fresh random password and a fresh authenticator secret, under the existing login or a new one for a passkey-only admin, lifts the lockouts of the login and of the admin's step-up, and ends every session of the admin (a lost phone may still hold one). Passkeys stay: the admin removes a lost one in Settings -> Security. One audit row, actor "cli", without the secrets.

type ResetTargetError

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

ResetTargetError is a reset-login that does not name one admin clearly; the message says what to do.

func (*ResetTargetError) Error

func (e *ResetTargetError) Error() string

type Service

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

Service implements the admin AuthService.

func New

func New(st *store.Store, cfg Config, log *slog.Logger) (*Service, error)

New builds the service. log may be nil.

func (*Service) ApprovalHandler

func (s *Service) ApprovalHandler() (string, http.Handler)

ApprovalHandler returns the Connect path prefix and the handler of ApprovalService. Mount it behind RequireSession.

func (*Service) BeginAddPasskey

BeginAddPasskey starts registering another passkey; the admin's existing ones are excluded.

func (*Service) BeginLogin

BeginLogin starts a discoverable-credential assertion. options_json is the bare PublicKeyCredentialRequestOptionsJSON (no "publicKey" wrapper).

func (*Service) BeginSetup

BeginSetup starts creating the first admin: a passkey registration, or (method PASSWORD) a password + TOTP enrolment. options_json is the bare PublicKeyCredentialCreationOptionsJSON (no "publicKey" wrapper).

func (*Service) BeginStepUp

BeginStepUp starts a passkey assertion limited to the admin's own passkeys.

func (*Service) BeginTotpEnrollment

BeginTotpEnrollment makes a new authenticator secret for the signed-in admin: a re-bind of the app for an admin with a password login, or (login + password given) a new password login for a passkey admin. Nothing is stored until FinishTotpEnrollment gets a code of the new secret.

func (*Service) ChangePassword

ChangePassword sets a new password for the signed-in admin's password login: step-up, then the current password.

func (*Service) ClientIP

func (s *Service) ClientIP(r *http.Request) netip.Addr

ClientIP is the client address for a request under the trusted-proxy rules.

func (*Service) ContextWithClientIP added in v0.1.33

func (s *Service) ContextWithClientIP(ctx context.Context, r *http.Request) context.Context

ContextWithClientIP returns ctx carrying r's client address for ClientIPFrom.

func (*Service) EndOtherSessions

EndOtherSessions ends every session of the signed-in admin except this one.

func (*Service) EndSession

EndSession ends one of the signed-in admin's sessions (the current one too: it logs out).

func (*Service) FinishAddPasskey

FinishAddPasskey verifies the new credential and stores it.

func (*Service) FinishLogin

FinishLogin verifies the assertion and opens a session.

func (*Service) FinishSetup

FinishSetup verifies the new credential (passkey, or the TOTP code for a password admin), consumes the setup token, creates the owner and signs them in.

func (*Service) FinishStepUp

FinishStepUp verifies a passkey assertion (ceremony_id + credential_json) or a fresh authenticator code (totp_code) and opens the step-up window on this session. Wrong proofs are counted per admin: five lock step-up for LockDuration.

func (*Service) FinishTotpEnrollment

FinishTotpEnrollment checks a code of the new secret and stores it: the re-bound app, or the new password login.

func (*Service) GetLoginInfo

GetLoginInfo is public: the brand, accent and language for the sign-in page and whether setup or the password form should be offered.

func (*Service) GetPasswordLogin

GetPasswordLogin says whether the signed-in admin has a password login, and under which login.

func (*Service) GetSecuritySettings

GetSecuritySettings returns the captcha settings; the secret key is reported only as set or not.

func (*Service) Handler

func (s *Service) Handler() (string, http.Handler)

Handler returns the Connect path prefix (e.g. "/mistgate.admin.v1.AuthService/") and the handler. It does not check sessions itself: mount it behind RequireSession, which also covers every other service.

func (*Service) ListAudit

ListAudit pages through the audit log (owner only), optionally for one source.

func (*Service) ListPasskeys

ListPasskeys lists the signed-in admin's passkeys.

func (*Service) ListSessions

ListSessions lists the signed-in admin's live sessions.

func (*Service) Logout

Logout deletes the session (if any) and clears the cookie. Only the end of a real session is audited: the procedure is public, and an audit row per anonymous call would let anyone who reaches the admin grow the (never pruned) audit log and the database at the admin request rate.

func (*Service) Me

Me returns the signed-in admin.

func (*Service) PasswordLogin

PasswordLogin signs an admin in with login + password + authenticator code. Every failure looks the same whatever was wrong and whether the login exists; five failures lock the login for LockDuration, and a locked login is refused without looking at the credentials. A code is single-use.

func (*Service) RecoveryEnabled added in v0.1.49

func (s *Service) RecoveryEnabled() bool

RecoveryEnabled is true on the Cloudflare edition, where the one-time recovery token is offered by the Worker.

func (*Service) RecoveryHandler added in v0.1.49

func (s *Service) RecoveryHandler() http.Handler

RecoveryHandler is the public, edge-only endpoint used by the recover screen. The regular Connect auth service stays unchanged for the VPS edition.

func (*Service) RemovePasskey

RemovePasskey deletes one of the signed-in admin's passkeys, never the last way in.

func (*Service) RequireBearer

func (s *Service) RequireBearer(next http.Handler, c Channel) http.Handler

RequireBearer wraps an endpoint that is not an admin procedure (the MCP endpoint) with token authentication: the same checks as the API (a well-formed secret, a live token, the token's rate limit), no cookie. It puts the Principal into the context (PrincipalFrom) and records the use; it writes no "call" row itself, the procedures the endpoint then calls do. The channel names how the token is used and what last_used_via shows.

func (*Service) RequireSession

func (s *Service) RequireSession(next http.Handler) http.Handler

RequireSession wraps the admin API handler. It sees request paths with the "/api" prefix already stripped ("/mistgate.admin.v1.XService/Method"). Every request whose path is not exactly a public procedure needs a valid session cookie, whatever the service, the RPC kind (unary or streaming) or whether the path even exists; the signed-in admin is put into the request context for AdminFrom. A request with an "Authorization: Bearer" header is an API token call instead (bearer.go): the token is checked, the procedure must be on the token allow-list and within the profile's role, and AdminFrom then returns a synthetic admin "token:<id>" (PrincipalFrom says so).

func (*Service) RequireStepUp

func (s *Service) RequireStepUp(ctx context.Context) error

RequireStepUp returns nil when the session behind ctx (set by RequireSession) proved a sign-in factor within StepUpWindow; else PERMISSION_DENIED with a StepUpRequired detail that tells the UI what to ask for. It is the one helper every step-up protected call goes through, in this package and in the modules that follow. For an API token it is always PERMISSION_DENIED, except inside an approved plan (WithApprovedStepUp).

func (*Service) SetEdge added in v0.1.35

func (s *Service) SetEdge(edge bool)

SetEdge tells the service it serves the edge edition: Me reports it with the features the edge lacks, and CreateApiToken refuses (MCP is not served there). The app sets it once while building.

func (*Service) SetEventHook

func (s *Service) SetEventHook(fn func(Event))

SetEventHook installs fn, called once per event on its own goroutine, so it may block without slowing a sign-in down (and must be safe for concurrent use). nil removes it. Events are fire-and-forget: the audit log is the record.

func (*Service) SetEventRunner added in v0.1.50

func (s *Service) SetEventRunner(run func(func()))

SetEventRunner makes emit run the hook through run instead of a bare goroutine (on the edge, an after-response task the Worker waits for). nil, the VPS, keeps the goroutine. Set it once while building.

func (*Service) SetSourceStars added in v0.1.65

func (s *Service) SetSourceStars(fn func() (int, bool))

SetSourceStars installs the source repository's cached star count for Me. nil removes it.

func (*Service) SourceURL added in v0.1.65

func (s *Service) SourceURL() string

SourceURL returns the source code URL configured for this panel.

func (*Service) TokenHandler

func (s *Service) TokenHandler() (string, http.Handler)

TokenHandler returns the Connect path prefix and the handler of ApiTokenService. Like Handler it does not check sessions itself: mount it behind RequireSession.

func (*Service) TurnstileEnabled

func (s *Service) TurnstileEnabled(ctx context.Context) bool

TurnstileEnabled tells the admin HTTP layer whether the captcha is on, so that the admin pages allow Cloudflare's script and frame in their CSP only then. An unreadable setting counts as off: the CSP stays strict, and the RPCs themselves fail closed.

func (*Service) UpdateSecuritySettings

UpdateSecuritySettings changes the captcha settings (absent fields stay). Turning the captcha on needs a site key and a secret key; removing the secret key switches it off. A call that leaves the captcha on with keys it was not proven with (switching it on, new keys while it is on) needs turnstile_test_token: see proveTurnstile.

func (*Service) WithApprovedStepUp

func (s *Service) WithApprovedStepUp(ctx context.Context, planID string) context.Context

WithApprovedStepUp returns ctx holding the grant of plan planID. The grant lets a TokenAccessApproved procedure through and makes RequireStepUp return nil, but only while the plan, read from the database on every use, is applying, belongs to the calling token, needs approval and carries a recorded human decision, and only for the procedures its tool is allowed to call (grantProcedures). It therefore dies the moment the apply finishes. The MCP layer derives it only while that apply is running.

func (*Service) WithClientIP

func (s *Service) WithClientIP(r *http.Request) *http.Request

WithClientIP returns r with its ClientIP in the context, for ClientIPFrom. RequireSession does this for the admin API; the public listener does it for everything it dispatches (subscription mounts, the agent endpoint).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL