auth

package
v0.2.0-dev.12 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: AGPL-3.0 Imports: 52 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 (
	PathProbeProcedure    = "/mistgate.probe.v1.ProbeService/PathProbe"
	NodeTraceProcedure    = "/mistgate.probe.v1.ProbeService/NodeTrace"
	NodeDnsCheckProcedure = "/mistgate.probe.v1.ProbeService/NodeDnsCheck"
	PathSpeedProcedure    = "/mistgate.probe.v1.ProbeService/PathSpeed"

	PathSpeedResultsProcedure = "/mistgate.probe.v1.ProbeService/PathSpeedResults"

	ChannelMeasurePlanProcedure   = "/mistgate.probe.v1.ProbeService/ChannelMeasurePlan"
	ChannelMeasureStartProcedure  = "/mistgate.probe.v1.ProbeService/ChannelMeasureStart"
	ChannelMeasureStatusProcedure = "/mistgate.probe.v1.ProbeService/ChannelMeasureStatus"
	ChannelMeasureCancelProcedure = "/mistgate.probe.v1.ProbeService/ChannelMeasureCancel"

	NodeSniScanProcedure = "/mistgate.probe.v1.ProbeService/NodeSniScan"
)

The ProbeService procedures (proto/mistgate/probe/v1) as strings: importing probev1connect here would put the generated messages into the Cloudflare Workers, which have no room for them and never serve the service. A test compares them with the generated names.

View Source
const (
	OpsGetLogSettingsProcedure     = "/mistgate.ops.v1.OpsService/GetLogSettings"
	OpsSetLogLevelProcedure        = "/mistgate.ops.v1.OpsService/SetLogLevel"
	OpsGetPanelLogsProcedure       = "/mistgate.ops.v1.OpsService/GetPanelLogs"
	OpsGetRetentionProcedure       = "/mistgate.ops.v1.OpsService/GetRetention"
	OpsSetRetentionProcedure       = "/mistgate.ops.v1.OpsService/SetRetention"
	OpsExportDataProcedure         = "/mistgate.ops.v1.OpsService/ExportData"
	OpsGetMetricsSettingsProcedure = "/mistgate.ops.v1.OpsService/GetMetricsSettings"
	OpsSetMetricsSettingsProcedure = "/mistgate.ops.v1.OpsService/SetMetricsSettings"
	// The on-demand debug capture of a node. Starting one raises a node's log level for at most 15 minutes and removes nothing, like
	// SetLogLevel: an admin-profile token may start one (the MCP tools node_debug_capture_plan / _apply put a plan in front of it)
	// and read the records back, which are scrubbed on the node, on intake and on the way out. Stopping one is the owner's in the
	// admin UI (a capture ends by itself), closed to tokens like the export.
	OpsStartDebugCaptureProcedure  = "/mistgate.ops.v1.OpsService/StartDebugCapture"
	OpsStopDebugCaptureProcedure   = "/mistgate.ops.v1.OpsService/StopDebugCapture"
	OpsListDebugCapturesProcedure  = "/mistgate.ops.v1.OpsService/ListDebugCaptures"
	OpsGetDebugCaptureProcedure    = "/mistgate.ops.v1.OpsService/GetDebugCapture"
	OpsGetPanelResourcesProcedure  = "/mistgate.ops.v1.OpsService/GetPanelResources"
	OpsGetFleetLoadProcedure       = "/mistgate.ops.v1.OpsService/GetFleetLoad"
	OpsGetNetworkSettingsProcedure = "/mistgate.ops.v1.OpsService/GetNetworkSettings"
	OpsSetNetworkSettingsProcedure = "/mistgate.ops.v1.OpsService/SetNetworkSettings"
	// The logs people send for support. A person's own logs, even cleaned, are the owner's to ask for and to read: all of these are the
	// owner's in the admin UI and closed to tokens (no tokenProcedures line), whatever the profile: that includes reading the records and
	// downloading them (the download also needs a fresh sign-in), so what a person's log says never reaches an AI provider. The MCP
	// list of requests, metadata only, is a later line here.
	OpsRequestClientDebugProcedure = "/mistgate.ops.v1.OpsService/RequestClientDebug"
	OpsCancelClientDebugProcedure  = "/mistgate.ops.v1.OpsService/CancelClientDebug"
	OpsListClientDebugProcedure    = "/mistgate.ops.v1.OpsService/ListClientDebug"
	OpsGetClientDebugProcedure     = "/mistgate.ops.v1.OpsService/GetClientDebug"
	OpsExportClientDebugProcedure  = "/mistgate.ops.v1.OpsService/ExportClientDebug"
	OpsDeleteClientDebugProcedure  = "/mistgate.ops.v1.OpsService/DeleteClientDebug"
)

The OpsService (proto/mistgate/ops/v1) is a package of its own so the Cloudflare edition does not link its messages; its procedures are named here by path. The diagnostics are owner-only: tokens (the admin profile) read the log level, the panel logs and the retention settings, may change the log level (it resets on restart and removes nothing), and change retention only through the owner's approved plan with a step-up, since a shorter retention deletes rows for good. The export and the metrics switch are the owner's in the admin UI and closed to tokens.

GetPanelResources and GetFleetLoad are reads like GetNodeHostHistory, whose rows the load is computed from: numbers, node names and recommendation codes, no address, path, key or person. Every signed-in admin and every token profile reads them.

View Source
const (
	OwnProbeGetProcedure            = "/mistgate.ownprobe.v1.OwnProbeService/Get"
	OwnProbeUpdateProcedure         = "/mistgate.ownprobe.v1.OwnProbeService/Update"
	OwnProbeCreateProcedure         = "/mistgate.ownprobe.v1.OwnProbeService/Create"
	OwnProbeUpdateCommandProcedure  = "/mistgate.ownprobe.v1.OwnProbeService/UpdateCommand"
	OwnProbeRevokeProcedure         = "/mistgate.ownprobe.v1.OwnProbeService/Revoke"
	OwnProbeConfirmNetworkProcedure = "/mistgate.ownprobe.v1.OwnProbeService/ConfirmNetwork"
	OwnProbeCheckNowProcedure       = "/mistgate.ownprobe.v1.OwnProbeService/CheckNow"
	OwnProbeDisconnectProcedure     = "/mistgate.ownprobe.v1.OwnProbeService/Disconnect"
)

The OwnProbeService (proto/mistgate/ownprobe/v1) is a package of its own so the Cloudflare edition does not link its messages; its procedures are named here by path, and a test compares them with the generated names. All of them are the owner's in the admin UI and closed to API tokens and the MCP (no tokenProcedures line): a probe's token and secret are credentials of a device in someone's home, and what the probes see is the owner's to read. Creating, revoking, switching and disconnecting probes also need a fresh sign-in; the update command (no token in it) does not.

View Source
const (
	TasksListTasksProcedure      = "/mistgate.tasks.v1.TasksService/ListTasks"
	TasksGetTaskProcedure        = "/mistgate.tasks.v1.TasksService/GetTask"
	TasksCreateTaskProcedure     = "/mistgate.tasks.v1.TasksService/CreateTask"
	TasksUpdateTaskProcedure     = "/mistgate.tasks.v1.TasksService/UpdateTask"
	TasksDeleteTaskProcedure     = "/mistgate.tasks.v1.TasksService/DeleteTask"
	TasksRunTaskNowProcedure     = "/mistgate.tasks.v1.TasksService/RunTaskNow"
	TasksListTaskRunsProcedure   = "/mistgate.tasks.v1.TasksService/ListTaskRuns"
	TasksListCheckToolsProcedure = "/mistgate.tasks.v1.TasksService/ListCheckTools"
)

The TasksService (proto/mistgate/tasks/v1) is a package of its own so the Cloudflare edition does not link its messages; its procedures are named here by path. Reading the tasks, their runs and the tools a check may run, and starting a run now, are day-to-day work of the owner and the helpers (operator-profile tokens through the MCP tools tasks_list, task_get, task_runs and task_run_now; a run is bounded: one at a time per task, a manual one at most once a minute or five). Creating, changing and deleting a task are the owner's: a task runs tools or the assistant again and again on its own, so a token reaches them only through the owner's approved plan (task_create_plan, task_update_plan, task_delete_plan and their _apply).

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
	// TokenAccessDraft: an in-process MCP call made while planning, with no approved plan (WithPlanning), or inside an approved plan of the
	// procedure's tool. The handler itself refuses a call that has no approved plan whatever changes what a node or the panel serves
	// (AddDecoySiteVersion: only a draft), so a token saves drafts freely and a live site only through the owner.
	TokenAccessDraft = 4
)

Token access kinds, the first result of TokenAccess.

View Source
const (
	TrustTunnelGetLinksProcedure  = "/mistgate.trusttunnel.v1.TrustTunnelService/GetTrustTunnelLinks"
	TrustTunnelIssueKeyProcedure  = "/mistgate.trusttunnel.v1.TrustTunnelService/IssueTrustTunnelKey"
	TrustTunnelRevokeKeyProcedure = "/mistgate.trusttunnel.v1.TrustTunnelService/RevokeTrustTunnelKey"
)

The TrustTunnelService (proto/mistgate/trusttunnel/v1) is a package of its own so the Cloudflare edition does not link its messages; its procedures are named here by path, and a test compares them with the generated names. A tt:// link carries the key's secret, so the key calls are the admin's write level like the AmneziaVPN and Telegram key calls, and closed to API tokens and the MCP (no tokenProcedures line).

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 BackupDownloadProcedure = "/backup/download"

BackupDownloadProcedure is the plain HTTP archive route mounted beside Connect services.

View Source
const BackupUploadProcedure = "/backup/upload"
View Source
const MihomoTemplateTool = "subscription_mihomo_template_set"

MihomoTemplateTool is the MCP tool whose owner-approved plan may change the Mihomo templates of the subscription settings through a token that is not the owner's (an operator token): the owner's approval of that plan is the owner's own decision.

View Source
const NodeInstallTool = "node_install"

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

View Source
const RoutingProfileTool = "subscription_routing_set"

RoutingProfileTool is the same for the routing profiles of Happ and INCY: the owner's approval of a plan of this tool is what lets an operator token change them.

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 ActorID

func ActorID(ctx context.Context) string

ActorID returns the stable identifier to store in an audit row.

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 ApprovedPlanTool

func ApprovedPlanTool(ctx context.Context) string

ApprovedPlanTool is the MCP tool whose plan this call is applying, when the plan is one the owner approved and its tool may call this procedure (the same test as the grant that let the call through); "" for any other call, a signed-in admin's included.

func AssistantAudienceAllows

func AssistantAudienceAllows(audience adminv1.AssistantAudience, role string) bool

AssistantAudienceAllows reports whether an admin of the role is in the audience the owner set for the assistant.

func AssistantProfile

func AssistantProfile(role string) string

AssistantProfile is the token profile the assistant of an admin of the role acts with; "" for a role the assistant is not for.

func AuthCeremonyTOTPRecordID added in v0.1.80

func AuthCeremonyTOTPRecordID(id string) string

AuthCeremonyTOTPRecordID is the vault AAD for a TOTP secret held by a pending auth ceremony.

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 GrantAllows

func GrantAllows(tool, procedure string) bool

GrantAllows reports whether the approved plan of the MCP tool (its name without the _plan / _apply suffix) may call the procedure: the one lookup of the grants table, for the middleware and for the tests that hold the tool registry against it.

func GrantedProcedures

func GrantedProcedures(tool string) []string

GrantedProcedures lists the procedures the approved plan of the MCP tool may call, for the tests that hold the tool registry against the grants table.

func HasApprovedUserChangePlan

func HasApprovedUserChangePlan(ctx context.Context) bool

HasApprovedUserChangePlan reports whether this exact MCP procedure is running inside an owner-approved user-change plan. The access service uses it to exempt the approved apply from the token's unattended hourly budget.

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 or a plain HTTP backup transfer 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 NodeInstallSecretAAD added in v0.1.80

func NodeInstallSecretAAD(planID string) string

NodeInstallSecretAAD is the vault AAD for the secret the owner supplied while approving an MCP install plan.

func OwnerSession

func OwnerSession(ctx context.Context) (store.Admin, error)

OwnerSession is the owner signed in with a cookie session: a helper, a readonly admin and every token are refused.

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 PlanningDryRun

func PlanningDryRun(r *http.Request) bool

PlanningDryRun reports whether r is a request whose procedure-specific flag guarantees no change, and puts the body back for the handler. Anything it cannot read as such (compressed, another content type, too large) is not a dry run. It is the one test of a plan's check call: the middleware applies it, and the MCP tests' stand-in for the middleware too.

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 SignedInSession

func SignedInSession(ctx context.Context) (store.Admin, error)

SignedInSession is the admin signed in with a cookie session. An API or MCP token is refused here whatever its profile and whatever the procedure table says: the second lock of the RPCs that no token may reach.

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 TOTPSecretAAD added in v0.1.80

func TOTPSecretAAD(adminID string) string

TOTPSecretAAD is the vault AAD for an admin's password-login authenticator secret.

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 TokenProfileRole

func TokenProfileRole(profile string) string

TokenProfileRole returns the role represented by a token profile.

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 WithAssistant

func WithAssistant(ctx context.Context, tokenID, profile, adminID, adminName string) context.Context

WithAssistant marks a server-created MCP call made for an authenticated assistant turn. This context value cannot be supplied over HTTP. RequireSession verifies its hidden token row and still applies the token profile, allow-list, planning and approved-plan checks before a panel procedure runs.

func WithAssistantFollowUp

func WithAssistantFollowUp(ctx context.Context, tokenID, profile, adminID, adminName string) context.Context

WithAssistantFollowUp marks an unattended assistant turn with a separate hidden token at the admin's current profile. The MCP session independently limits its change tools to the operator profile.

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.

func WithScheduledTask

func WithScheduledTask(ctx context.Context, tokenID, adminID, adminName string) context.Context

WithScheduledTask marks a server-created MCP call made by a scheduled task of an admin (internal/panel/tasks): the hidden identity store.ScheduledTokenID with the operator profile, whatever the admin's role. Like WithAssistant it cannot come over HTTP; RequireSession verifies the row and applies the operator profile, the allow-list and the planning and approval checks. It does not need the assistant to be on: a check task runs no model.

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"
	// ChannelAssistant is the in-process MCP call made for a signed-in assistant turn.
	ChannelAssistant Channel = "assistant"
)

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 header is
	// 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
	Assistant            bool      // a hidden per-admin identity; never accepted from bearer auth
	AllowBulkUserChanges bool      // owner-authorized exemption from the hourly user-change cap
}

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. A configured proxy must set or overwrite X-Forwarded-For; a proxy that only writes Forwarded is not supported. The zero value trusts nobody: the client address is the TCP peer, whatever the headers say. Overwriting that chain prevents a client-supplied address from changing per-client limits.

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. The configured proxy must set or overwrite X-Forwarded-For. Other forwarding headers are ignored. An unparseable X-Forwarded-For chain falls back to the peer.

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) ApproveAssistantMCPPlan

func (s *Service) ApproveAssistantMCPPlan(ctx context.Context, id string, admin store.Admin) (store.MCPPlan, error)

ApproveAssistantMCPPlan is the same awaiting -> approved operation used by ApprovalService.Approve, for the AssistantService's human-click path. Its caller must have checked the signed-in owner and RequireStepUp first.

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 audit log (pruned only after its retention, 400 days by default) 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