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
- Variables
- func ActorID(ctx context.Context) string
- func ActorLabel(ctx context.Context) string
- func AdminFrom(ctx context.Context) (store.Admin, bool)
- func ApprovedPlanTool(ctx context.Context) string
- func AuthCeremonyTOTPRecordID(id string) string
- func ClientIPFrom(ctx context.Context) netip.Addr
- func ContextWithPeerIP(ctx context.Context, r *http.Request) context.Context
- func DisableTurnstile(ctx context.Context, st *store.Store, now time.Time) error
- func HasApprovedUserChangePlan(ctx context.Context) bool
- func IssueSetupToken(ctx context.Context, st *store.Store, now time.Time) (string, error)
- func NeedsStepUp(path string) bool
- func NewTokenSecret() string
- func NodeInstallSecretAAD(planID string) string
- func ParseProxies(list []string) ([]netip.Prefix, error)
- func PeerIP(r *http.Request) netip.Addr
- func ProcedureRole(path string) string
- func SealNodeInstallSecret(v *vault.Vault, planID string, s NodeInstallSecret) []byte
- func SourceKey(a netip.Addr) string
- func TOTPSecretAAD(adminID string) string
- func TokenAccess(path string) (access int, ok bool)
- func TokenProcedureRole(path string) string
- func TokenProfileRole(profile string) string
- func WithAdmin(ctx context.Context, a store.Admin) context.Context
- func WithAssistant(ctx context.Context, tokenID, profile, adminID, adminName string) context.Context
- func WithAssistantFollowUp(ctx context.Context, tokenID, profile, adminID, adminName string) context.Context
- func WithChannel(ctx context.Context, c Channel) context.Context
- func WithPlanning(ctx context.Context) context.Context
- func WithScheduledTask(ctx context.Context, tokenID, adminID, adminName string) context.Context
- type Channel
- type Config
- type Event
- type NodeInstallSecret
- type Principal
- type ProxyTrust
- type ResetLoginInput
- type ResetLoginResult
- type ResetTargetError
- type Service
- func (s *Service) ApprovalHandler() (string, http.Handler)
- func (s *Service) ApproveAssistantMCPPlan(ctx context.Context, id string, admin store.Admin) (store.MCPPlan, error)
- func (s *Service) BeginAddPasskey(ctx context.Context, req *connect.Request[adminv1.BeginAddPasskeyRequest]) (*connect.Response[adminv1.BeginAddPasskeyResponse], error)
- func (s *Service) BeginLogin(ctx context.Context, req *connect.Request[adminv1.BeginLoginRequest]) (*connect.Response[adminv1.BeginLoginResponse], error)
- func (s *Service) BeginSetup(ctx context.Context, req *connect.Request[adminv1.BeginSetupRequest]) (*connect.Response[adminv1.BeginSetupResponse], error)
- func (s *Service) BeginStepUp(ctx context.Context, req *connect.Request[adminv1.BeginStepUpRequest]) (*connect.Response[adminv1.BeginStepUpResponse], error)
- func (s *Service) BeginTotpEnrollment(ctx context.Context, req *connect.Request[adminv1.BeginTotpEnrollmentRequest]) (*connect.Response[adminv1.BeginTotpEnrollmentResponse], error)
- func (s *Service) ChangePassword(ctx context.Context, req *connect.Request[adminv1.ChangePasswordRequest]) (*connect.Response[adminv1.ChangePasswordResponse], error)
- func (s *Service) ClientIP(r *http.Request) netip.Addr
- func (s *Service) ContextWithClientIP(ctx context.Context, r *http.Request) context.Context
- func (s *Service) EndOtherSessions(ctx context.Context, req *connect.Request[adminv1.EndOtherSessionsRequest]) (*connect.Response[adminv1.EndOtherSessionsResponse], error)
- func (s *Service) EndSession(ctx context.Context, req *connect.Request[adminv1.EndSessionRequest]) (*connect.Response[adminv1.EndSessionResponse], error)
- func (s *Service) FinishAddPasskey(ctx context.Context, req *connect.Request[adminv1.FinishAddPasskeyRequest]) (*connect.Response[adminv1.FinishAddPasskeyResponse], error)
- func (s *Service) FinishLogin(ctx context.Context, req *connect.Request[adminv1.FinishLoginRequest]) (*connect.Response[adminv1.FinishLoginResponse], error)
- func (s *Service) FinishSetup(ctx context.Context, req *connect.Request[adminv1.FinishSetupRequest]) (*connect.Response[adminv1.FinishSetupResponse], error)
- func (s *Service) FinishStepUp(ctx context.Context, req *connect.Request[adminv1.FinishStepUpRequest]) (*connect.Response[adminv1.FinishStepUpResponse], error)
- func (s *Service) FinishTotpEnrollment(ctx context.Context, req *connect.Request[adminv1.FinishTotpEnrollmentRequest]) (*connect.Response[adminv1.FinishTotpEnrollmentResponse], error)
- func (s *Service) GetLoginInfo(ctx context.Context, _ *connect.Request[adminv1.GetLoginInfoRequest]) (*connect.Response[adminv1.GetLoginInfoResponse], error)
- func (s *Service) GetPasswordLogin(ctx context.Context, _ *connect.Request[adminv1.GetPasswordLoginRequest]) (*connect.Response[adminv1.GetPasswordLoginResponse], error)
- func (s *Service) GetSecuritySettings(ctx context.Context, _ *connect.Request[adminv1.GetSecuritySettingsRequest]) (*connect.Response[adminv1.GetSecuritySettingsResponse], error)
- func (s *Service) Handler() (string, http.Handler)
- func (s *Service) ListAudit(ctx context.Context, req *connect.Request[adminv1.ListAuditRequest]) (*connect.Response[adminv1.ListAuditResponse], error)
- func (s *Service) ListPasskeys(ctx context.Context, _ *connect.Request[adminv1.ListPasskeysRequest]) (*connect.Response[adminv1.ListPasskeysResponse], error)
- func (s *Service) ListSessions(ctx context.Context, req *connect.Request[adminv1.ListSessionsRequest]) (*connect.Response[adminv1.ListSessionsResponse], error)
- func (s *Service) Logout(ctx context.Context, req *connect.Request[adminv1.LogoutRequest]) (*connect.Response[adminv1.LogoutResponse], error)
- func (s *Service) Me(ctx context.Context, _ *connect.Request[adminv1.MeRequest]) (*connect.Response[adminv1.MeResponse], error)
- func (s *Service) PasswordLogin(ctx context.Context, req *connect.Request[adminv1.PasswordLoginRequest]) (*connect.Response[adminv1.PasswordLoginResponse], error)
- func (s *Service) RecoveryEnabled() bool
- func (s *Service) RecoveryHandler() http.Handler
- func (s *Service) RemovePasskey(ctx context.Context, req *connect.Request[adminv1.RemovePasskeyRequest]) (*connect.Response[adminv1.RemovePasskeyResponse], error)
- func (s *Service) RequireBearer(next http.Handler, c Channel) http.Handler
- func (s *Service) RequireSession(next http.Handler) http.Handler
- func (s *Service) RequireStepUp(ctx context.Context) error
- func (s *Service) SetEdge(edge bool)
- func (s *Service) SetEventHook(fn func(Event))
- func (s *Service) SetEventRunner(run func(func()))
- func (s *Service) SetSourceStars(fn func() (int, bool))
- func (s *Service) SourceURL() string
- func (s *Service) TokenHandler() (string, http.Handler)
- func (s *Service) TurnstileEnabled(ctx context.Context) bool
- func (s *Service) UpdateSecuritySettings(ctx context.Context, ...) (*connect.Response[adminv1.UpdateSecuritySettingsResponse], error)
- func (s *Service) WithApprovedStepUp(ctx context.Context, planID string) context.Context
- func (s *Service) WithClientIP(r *http.Request) *http.Request
Constants ¶
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).
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" )
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.
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.
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.
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).
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.
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).
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 )
const BackupDownloadProcedure = "/backup/download"
BackupDownloadProcedure is the plain HTTP archive route mounted beside Connect services.
const BackupUploadProcedure = "/backup/upload"
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.
const NodeInstallTool = "node_install"
NodeInstallTool is the MCP tool whose approval carries the owner's SSH login choice.
const SiteverifyURL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
SiteverifyURL is Cloudflare's verification endpoint.
const StepUpWindow = 5 * time.Minute
StepUpWindow is how long a proof of a sign-in factor keeps step-up protected calls open.
const (
// TokenSecretPrefix starts every token secret. Neutral on purpose: no product name travels in a header.
TokenSecretPrefix = "tk1_"
)
Variables ¶
var ErrAdminExists = errors.New("auth: an admin already exists")
ErrAdminExists is returned by IssueSetupToken once the first admin has been created.
Functions ¶
func ActorLabel ¶
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 ApprovedPlanTool ¶
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 AuthCeremonyTOTPRecordID ¶ added in v0.1.80
AuthCeremonyTOTPRecordID is the vault AAD for a TOTP secret held by a pending auth ceremony.
func ClientIPFrom ¶
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
ContextWithPeerIP returns ctx carrying PeerIP(r) for ClientIPFrom.
func DisableTurnstile ¶
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 HasApprovedUserChangePlan ¶
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 ¶
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 ¶
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
NodeInstallSecretAAD is the vault AAD for the secret the owner supplied while approving an MCP install plan.
func ParseProxies ¶
ParseProxies parses --trusted-proxy values: CIDRs ("10.0.0.0/8") or single addresses.
func PeerIP ¶ added in v0.1.41
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 ¶
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 ¶
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
TOTPSecretAAD is the vault AAD for an admin's password-login authenticator secret.
func TokenAccess ¶
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
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 ¶
TokenProfileRole returns the role represented by a token profile.
func WithAdmin ¶ added in v0.1.22
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 ¶
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 ¶
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 ¶
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
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 ¶
PrincipalFrom returns the token principal RequireSession or RequireBearer put into ctx; the zero Principal for a cookie session or outside the middleware.
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 ¶
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 (*Service) ApprovalHandler ¶
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 ¶
func (s *Service) BeginAddPasskey(ctx context.Context, req *connect.Request[adminv1.BeginAddPasskeyRequest]) (*connect.Response[adminv1.BeginAddPasskeyResponse], error)
BeginAddPasskey starts registering another passkey; the admin's existing ones are excluded.
func (*Service) BeginLogin ¶
func (s *Service) BeginLogin(ctx context.Context, req *connect.Request[adminv1.BeginLoginRequest]) (*connect.Response[adminv1.BeginLoginResponse], error)
BeginLogin starts a discoverable-credential assertion. options_json is the bare PublicKeyCredentialRequestOptionsJSON (no "publicKey" wrapper).
func (*Service) BeginSetup ¶
func (s *Service) BeginSetup(ctx context.Context, req *connect.Request[adminv1.BeginSetupRequest]) (*connect.Response[adminv1.BeginSetupResponse], error)
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 ¶
func (s *Service) BeginStepUp(ctx context.Context, req *connect.Request[adminv1.BeginStepUpRequest]) (*connect.Response[adminv1.BeginStepUpResponse], error)
BeginStepUp starts a passkey assertion limited to the admin's own passkeys.
func (*Service) BeginTotpEnrollment ¶
func (s *Service) BeginTotpEnrollment(ctx context.Context, req *connect.Request[adminv1.BeginTotpEnrollmentRequest]) (*connect.Response[adminv1.BeginTotpEnrollmentResponse], error)
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 ¶
func (s *Service) ChangePassword(ctx context.Context, req *connect.Request[adminv1.ChangePasswordRequest]) (*connect.Response[adminv1.ChangePasswordResponse], error)
ChangePassword sets a new password for the signed-in admin's password login: step-up, then the current password.
func (*Service) ClientIP ¶
ClientIP is the client address for a request under the trusted-proxy rules.
func (*Service) ContextWithClientIP ¶ added in v0.1.33
ContextWithClientIP returns ctx carrying r's client address for ClientIPFrom.
func (*Service) EndOtherSessions ¶
func (s *Service) EndOtherSessions(ctx context.Context, req *connect.Request[adminv1.EndOtherSessionsRequest]) (*connect.Response[adminv1.EndOtherSessionsResponse], error)
EndOtherSessions ends every session of the signed-in admin except this one.
func (*Service) EndSession ¶
func (s *Service) EndSession(ctx context.Context, req *connect.Request[adminv1.EndSessionRequest]) (*connect.Response[adminv1.EndSessionResponse], error)
EndSession ends one of the signed-in admin's sessions (the current one too: it logs out).
func (*Service) FinishAddPasskey ¶
func (s *Service) FinishAddPasskey(ctx context.Context, req *connect.Request[adminv1.FinishAddPasskeyRequest]) (*connect.Response[adminv1.FinishAddPasskeyResponse], error)
FinishAddPasskey verifies the new credential and stores it.
func (*Service) FinishLogin ¶
func (s *Service) FinishLogin(ctx context.Context, req *connect.Request[adminv1.FinishLoginRequest]) (*connect.Response[adminv1.FinishLoginResponse], error)
FinishLogin verifies the assertion and opens a session.
func (*Service) FinishSetup ¶
func (s *Service) FinishSetup(ctx context.Context, req *connect.Request[adminv1.FinishSetupRequest]) (*connect.Response[adminv1.FinishSetupResponse], error)
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 ¶
func (s *Service) FinishStepUp(ctx context.Context, req *connect.Request[adminv1.FinishStepUpRequest]) (*connect.Response[adminv1.FinishStepUpResponse], error)
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 ¶
func (s *Service) FinishTotpEnrollment(ctx context.Context, req *connect.Request[adminv1.FinishTotpEnrollmentRequest]) (*connect.Response[adminv1.FinishTotpEnrollmentResponse], error)
FinishTotpEnrollment checks a code of the new secret and stores it: the re-bound app, or the new password login.
func (*Service) GetLoginInfo ¶
func (s *Service) GetLoginInfo(ctx context.Context, _ *connect.Request[adminv1.GetLoginInfoRequest]) (*connect.Response[adminv1.GetLoginInfoResponse], error)
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 ¶
func (s *Service) GetPasswordLogin(ctx context.Context, _ *connect.Request[adminv1.GetPasswordLoginRequest]) (*connect.Response[adminv1.GetPasswordLoginResponse], error)
GetPasswordLogin says whether the signed-in admin has a password login, and under which login.
func (*Service) GetSecuritySettings ¶
func (s *Service) GetSecuritySettings(ctx context.Context, _ *connect.Request[adminv1.GetSecuritySettingsRequest]) (*connect.Response[adminv1.GetSecuritySettingsResponse], error)
GetSecuritySettings returns the captcha settings; the secret key is reported only as set or not.
func (*Service) 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 ¶
func (s *Service) ListAudit(ctx context.Context, req *connect.Request[adminv1.ListAuditRequest]) (*connect.Response[adminv1.ListAuditResponse], error)
ListAudit pages through the audit log (owner only), optionally for one source.
func (*Service) ListPasskeys ¶
func (s *Service) ListPasskeys(ctx context.Context, _ *connect.Request[adminv1.ListPasskeysRequest]) (*connect.Response[adminv1.ListPasskeysResponse], error)
ListPasskeys lists the signed-in admin's passkeys.
func (*Service) ListSessions ¶
func (s *Service) ListSessions(ctx context.Context, req *connect.Request[adminv1.ListSessionsRequest]) (*connect.Response[adminv1.ListSessionsResponse], error)
ListSessions lists the signed-in admin's live sessions.
func (*Service) Logout ¶
func (s *Service) Logout(ctx context.Context, req *connect.Request[adminv1.LogoutRequest]) (*connect.Response[adminv1.LogoutResponse], error)
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 ¶
func (s *Service) Me(ctx context.Context, _ *connect.Request[adminv1.MeRequest]) (*connect.Response[adminv1.MeResponse], error)
Me returns the signed-in admin.
func (*Service) PasswordLogin ¶
func (s *Service) PasswordLogin(ctx context.Context, req *connect.Request[adminv1.PasswordLoginRequest]) (*connect.Response[adminv1.PasswordLoginResponse], error)
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
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
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 ¶
func (s *Service) RemovePasskey(ctx context.Context, req *connect.Request[adminv1.RemovePasskeyRequest]) (*connect.Response[adminv1.RemovePasskeyResponse], error)
RemovePasskey deletes one of the signed-in admin's passkeys, never the last way in.
func (*Service) RequireBearer ¶
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 ¶
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 ¶
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
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 ¶
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
SetSourceStars installs the source repository's cached star count for Me. nil removes it.
func (*Service) SourceURL ¶ added in v0.1.65
SourceURL returns the source code URL configured for this panel.
func (*Service) TokenHandler ¶
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 ¶
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 ¶
func (s *Service) UpdateSecuritySettings(ctx context.Context, req *connect.Request[adminv1.UpdateSecuritySettingsRequest]) (*connect.Response[adminv1.UpdateSecuritySettingsResponse], error)
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 ¶
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 ¶
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).