auth

package
v2.4.1 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: MIT Imports: 18 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 resolves who is making a request — a local process on this box, a tailnet user identified through tailscaled, or a bearer token — and decides what mode of gating the control plane runs under.

The owner's stated requirement is the whole design: "use tailscale identity so I never have to log in on my own devices, and for people using lectern on a single machine, don't require auth." Mode resolution (auto/none/token/ tailscale) picks the right default without configuration; principal resolution answers "who is this" for the one request in hand.

Index

Constants

View Source
const (
	KindLocal     = "local"     // an unauthenticated process on this machine (CLI, MCP, an agent)
	KindTailscale = "tailscale" // identified via tailscaled's LocalAPI whois, or the Tailscale-User-Login header
	KindToken     = "token"     // LECTERN_AUTH_TOKEN, presented by a script or an off-tailnet client
	// KindDevice is a phone or browser that exchanged a one-time pairing code
	// (internal/pairing) for a device token. It carries the identity of
	// whichever owner minted the code — Login/Node/Human are copied from that
	// owner's own Principal at mint time — because the whole point of pairing
	// is that the paired device IS the owner, reachable without Tailscale.
	KindDevice = "device"
	// KindRelayDevice is a phone paired over the end-to-end encrypted relay
	// (internal/relay/host, docs/relay.md). Like KindDevice it carries the
	// minting owner's identity. It only ever comes from a tunnel connection
	// that completed a Noise handshake with a paired device key; see
	// WithTunnel.
	KindRelayDevice = "relay-device"
)

Kind values a Principal can carry.

View Source
const DefaultSocket = "/var/run/tailscale/tailscaled.sock"

DefaultSocket is tailscaled's LocalAPI socket on a standard Linux install. LECTERN_TAILSCALE_SOCKET overrides it (e.g. for a userspace/tsnet daemon).

Variables

This section is empty.

Functions

func ClassifyRemote

func ClassifyRemote(remoteAddr string) (loopback, tailscale bool)

ClassifyRemote reports whether an http.Request.RemoteAddr is loopback or a tailnet address — the two "this is basically local" cases every mode already trusts to some degree. Exported for callers outside this package that want to warn about the third case (docs/remote-access.md's "Add a Settings hint when the request arrives over a non-tailnet, non-loopback origin"), without duplicating the address classification this package already owns.

func WithPrincipal

func WithPrincipal(ctx context.Context, p Principal) context.Context

WithPrincipal attaches the resolved principal to a request context.

func WithTunnel

func WithTunnel(ctx context.Context, resolve TunnelResolver) context.Context

WithTunnel marks a connection as coming through the end-to-end encrypted relay. Only the relay host's in-process listener calls this, after a Noise handshake with a paired key: it is a Go context value, so no header, address or other request content can produce it. Authenticate trusts nothing else about such a request.

Types

type CertCache

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

CertCache serves TLS certificates for one DNS name from tailscaled's own cert store, fetching lazily and refreshing them ahead of expiry. Its GetCertificate method plugs directly into tls.Config.

func NewCertCache

func NewCertCache(la LocalAPI, dnsName string, log *slog.Logger) *CertCache

NewCertCache builds a cache for dnsName (tailscaled's LocalAPI cert endpoint, not a general ACME client — it only ever asks tailscaled for a cert it already manages for this node).

func (*CertCache) GetCertificate

func (c *CertCache) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error)

GetCertificate is a tls.Config.GetCertificate callback.

type DeviceLookup

type DeviceLookup interface {
	LookupDevice(ctx context.Context, rawToken string) (Principal, bool)
}

DeviceLookup resolves a paired device's raw token to the principal it authenticates as. Implemented by internal/pairing and wired in via SetDeviceLookup — this package stays decoupled from storage, the same pattern LocalAPI uses for tailscaled.

type LocalAPI

type LocalAPI interface {
	WhoIs(ctx context.Context, addr string) (*WhoIsResponse, error)
	Status(ctx context.Context) (*StatusResponse, error)
	// Cert fetches a TLS certificate/key pair for dnsName from tailscaled's
	// own cert store (issuing or renewing it via Let's Encrypt as needed).
	// Both return values are PEM-encoded.
	Cert(ctx context.Context, dnsName string) (certPEM, keyPEM []byte, err error)
}

LocalAPI is tailscaled's local control socket, narrowed to what identity resolution needs. An interface so tests use a fake instead of a real daemon.

func NewLocalAPIClient

func NewLocalAPIClient(socket string) LocalAPI

NewLocalAPIClient dials tailscaled's LocalAPI over its unix socket. Every request targets the fixed host "local-tailscaled.sock" regardless of the socket's real filesystem path — that is the name tailscaled's LocalAPI itself expects over the socket.

type Mode

type Mode string

Mode is the resolved (never "auto") auth mode a request is gated under.

const (
	ModeAuto      Mode = "auto"
	ModeNone      Mode = "none"
	ModeToken     Mode = "token"
	ModeTailscale Mode = "tailscale"
)

func ResolveMode

func ResolveMode(setting, host string, tokenSet bool, tailscaleUp func() bool) Mode

ResolveMode turns the configured LECTERN_AUTH setting into a concrete mode.

setting: "", "auto" (default), "none", "token", or "tailscale" — an explicit non-auto value always wins outright, so a forced mode never probes anything. host: the configured listen host (LECTERN_HOST). tokenSet: is LECTERN_AUTH_TOKEN non-empty. tailscaleUp: probes tailscaled's LocalAPI; nil or false skips straight to the token/none fallback. It is a func, not a bool, so an explicit mode never pays for a probe it doesn't need.

type Principal

type Principal struct {
	Kind  string
	Login string
	Node  string
	Human bool
}

Principal is the resolved identity of one request.

Human is true only for a person: a token holder, a tailnet login that matched the allowlist, or a paired device (which inherits its minting owner's Human bit). It is false for KindLocal and for a tagged (service) node — those may use the ordinary API but may not decide approvals, which the contract requires a human for.

func FromContext

func FromContext(ctx context.Context) (Principal, bool)

FromContext reads back a principal attached by WithPrincipal. ok is false for a context that never went through the auth middleware (e.g. a hook request, which is exempt and authenticates its own way).

type Resolver

type Resolver struct {
	Mode Mode
	// contains filtered or unexported fields
}

Resolver identifies the caller of one request and decides whether the request may proceed, given the mode it was constructed with.

func New

func New(s Settings, log *slog.Logger) *Resolver

New resolves the mode once at startup (probing tailscaled if the mode is auto and the listener isn't loopback-only), logs it loudly, and returns a Resolver ready to gate requests.

func (*Resolver) Authenticate

func (a *Resolver) Authenticate(r *http.Request) (Principal, bool)

Authenticate resolves the caller's principal for one request and reports whether the request may proceed under the resolver's mode. The two travel together because the token and tailnet-allowlist checks answer both questions at once.

func (*Resolver) CanDecide

func (a *Resolver) CanDecide(p Principal) bool

CanDecide reports whether a principal may decide a pending approval. Approval decisions need a human unless the whole control plane is running with no auth at all.

func (*Resolver) SetDeviceLookup

func (a *Resolver) SetDeviceLookup(d DeviceLookup)

SetDeviceLookup wires device-pairing authentication into the resolver. Called once at startup, after internal/pairing.Store exists, from internal/app — a setter rather than a Settings field because the resolver is otherwise built from plain config values, and the device store is a live object with its own database handle. Safe to call with nil (device pairing off, or not yet configured): Authenticate simply never finds a paired device.

func (*Resolver) TLSListenerConfig

func (a *Resolver) TLSListenerConfig(ctx context.Context, port int) (*TLSListenerConfig, error)

TLSListenerConfig resolves this node's tailnet addresses and DNS name from tailscaled's status and builds a config for a TLS listener on port, certificate served via CertCache. It only makes sense — and only succeeds — when the resolver's LocalAPI actually answers, i.e. effectively tailscale mode; callers gate on that themselves so a failure here can be logged as a specific, actionable warning rather than a generic startup error.

type Settings

type Settings struct {
	Mode            string // LECTERN_AUTH: "", "auto", "none", "token", "tailscale"
	Host            string // LECTERN_HOST, to detect a loopback-only listener
	Token           string // LECTERN_AUTH_TOKEN
	Socket          string // LECTERN_TAILSCALE_SOCKET override
	AllowedUsersCSV string // LECTERN_TAILSCALE_USERS
	AllowedTagsCSV  string // LECTERN_TAILSCALE_TAGS

	// TrustServeHeaders is LECTERN_TRUST_SERVE_HEADERS=1. Unsafe wherever an
	// agent can run a process on this host: X-Forwarded-For and
	// Tailscale-User-Login are ordinary headers, and loopback cannot tell
	// `tailscale serve` proxying a real tailnet client from `curl -H
	// 'Tailscale-User-Login: owner@example.com' 127.0.0.1:PORT/...` run by
	// anything on the box, including a dispatched agent. Off by default, so a
	// loopback request is always KindLocal/non-human regardless of what
	// headers it carries. Opt in only when Lectern's HTTP listener is
	// unreachable except through `tailscale serve` on the same host and no
	// untrusted process shares that host.
	TrustServeHeaders bool
}

Settings configures a Resolver. Individual fields rather than *config.Config so this package stays decoupled from internal/config, matching how the rest of the codebase's constructors take explicit values.

type StatusResponse

type StatusResponse struct {
	Self *StatusSelf           `json:"Self"`
	User map[string]StatusUser `json:"User"`
}

StatusResponse is the subset of GET /localapi/v0/status this package reads: enough to learn who owns this node, and (for the tailscale TLS listener) this node's own tailnet addresses and DNS name.

func (*StatusResponse) OwnerLogin

func (s *StatusResponse) OwnerLogin() string

OwnerLogin is the login of the account this tailscaled node belongs to (Self.UserID looked up in User) — the default allowed identity when LECTERN_TAILSCALE_USERS is unset.

type StatusSelf

type StatusSelf struct {
	UserID       int64    `json:"UserID"`
	TailscaleIPs []string `json:"TailscaleIPs"`
	DNSName      string   `json:"DNSName"`
}

StatusSelf is the subset of ipnstate.PeerStatus for this node that StatusResponse.Self carries.

type StatusUser

type StatusUser struct {
	LoginName string `json:"LoginName"`
}

StatusUser is the subset of tailcfg.UserProfile this package reads.

type TLSListenerConfig

type TLSListenerConfig struct {
	// Addrs are host:port strings, one per tailnet address (v4 and v6, when
	// this node has both) on the requested port.
	Addrs []string
	TLS   *tls.Config
	// DNSName is the certificate's name — what a phone on the tailnet types
	// (with the port) to reach this listener.
	DNSName string
}

TLSListenerConfig is what's needed to run a second listener bound to this node's own tailnet addresses: real tailnet peer addresses arrive on it, so whois there is trustworthy without `tailscale serve` fronting it.

type TunnelResolver

type TunnelResolver func() (Principal, bool)

TunnelResolver answers, for one request, which paired relay device sent it and whether that device is still allowed in. It is consulted per request, so a revocation takes effect on the very next request of a live connection.

type WhoIsNode

type WhoIsNode struct {
	Name string   `json:"Name"`
	Tags []string `json:"Tags"`
}

WhoIsNode and WhoIsUser mirror the subset of tailscaled's whois JSON this package needs. Hand-rolled rather than importing tailscale.com/client/local (and the tsnet dependency tree behind it) for two read-only HTTP calls.

type WhoIsResponse

type WhoIsResponse struct {
	Node        *WhoIsNode `json:"Node"`
	UserProfile *WhoIsUser `json:"UserProfile"`
}

WhoIsResponse is GET /localapi/v0/whois?addr=IP:PORT.

type WhoIsUser

type WhoIsUser struct {
	LoginName string `json:"LoginName"`
}

Jump to

Keyboard shortcuts

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