previewgw

package
v0.241.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 39 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 previewgw is the preview gateway (cmd/muster-preview): it accepts hosts' preview tunnels on two listeners, checks their host tokens, keeps one tunnel per (owner, host), reads each tunnel's offer stream into memory, and asks muster every minute whether each owner's plugin token still holds the viewer capability. See docs/design/previews.md ("The preview gateway").

The tunnel's protocol is internal/preview/wire and its transport internal/preview/tunnel; this package is what runs them. The session page at w.<zone> is session.go, the owner's entry onto p-<id>.<zone> auth.go and cookie.go, the reverse proxy behind that entry proxy.go (with wsrelay.go, sse.go and samesite.go), and the open limits and lifecycle lifecycle.go.

🔴 NO DATABASE. Host tokens live in a flock'd file in STATE_DIR (hosttokens.go), written by the CLI and re-read by the running gateway; previews live in memory, so a restart closes them (the hosts re-announce their open requests when they see a new gateway boot id).

Index

Constants

View Source
const (
	DefaultTTL  = 24 * time.Hour
	DefaultIdle = 2 * time.Hour
)

Lifecycle defaults (docs/design/previews.md, "Lifecycle").

View Source
const (
	// OwnerCookie is the owner cookie's name. The __Host- prefix makes the
	// browser require Secure, Path=/ and no Domain, so a cookie another preview
	// tosses at the zone cannot overwrite or shadow it.
	OwnerCookie = "__Host-mp"
	// OwnerCookieTTL is how long an owner cookie admits its owner.
	OwnerCookieTTL = 8 * time.Hour
	// TeamOwnerCookieTTL is how long it admits a TEAM owner (team sharing
	// 2b.3b; #696 round 1, 🟡3): the gateway knows nothing of membership, so
	// a member muster removes keeps a team preview they opened until their
	// cookie expires. A team's cookie is therefore short, and each renewal
	// goes back through muster's Preview button, where the member's role is
	// read fresh.
	TeamOwnerCookieTTL = 15 * time.Minute
	// PageTokenTTL is how long a session page's token works; a reload or an
	// expired token means clicking muster's chip again.
	PageTokenTTL = 15 * time.Minute
	// MinSigningKey is PREVIEW_SIGNING_KEY's minimum length, in bytes.
	MinSigningKey = 32
)
View Source
const (
	// RecheckEvery: every live tunnel's host token is checked against the
	// token file this often; a revoked one ends its tunnel at the next check.
	RecheckEvery = 30 * time.Second
	// SelfEvery: each plugin token's GET /plugin/v1/self, this often.
	SelfEvery = time.Minute

	// UnknownLimit consecutive /self checks without a verdict (muster
	// unreachable, a 5xx, a 404 because plugins are off) end a token's last
	// verdict: about ten minutes at one check a minute. An outage shorter
	// than that does not drop previews; a longer one stops serving an owner
	// muster can no longer vouch for. One later live verdict restores it.
	UnknownLimit = 10
)

Periods of the gateway's two checks.

View Source
const (
	// MaxOpenPerWindow previews per calling session (tmux window).
	MaxOpenPerWindow = 4
	// MaxOpenPerOwner previews per owner, across hosts.
	MaxOpenPerOwner = 16
	// DefaultHostMaxOpen is a host's limit before it has sent a config with
	// maxOpen (previews.json's own default). A host's maxOpen above
	// MaxOpenPerOwner never binds: one host has one owner.
	DefaultHostMaxOpen = 8
	// MaxConnsPerPreview is the most requests and WebSockets one preview may
	// have in flight at once (the design's 64 "concurrent client
	// connections" per preview). One more WAITS for a slot, for at most the
	// dial wait (Options.DialWait, the same bound the host's own upstream
	// slots use), and is then refused 429 too_many_connections — before
	// anything is dialled. It binds when the host's own upstream slots
	// (maxConns, at most 64) are full and requests queue for one: without it
	// a page could queue without bound.
	MaxConnsPerPreview = 64
)

The open limits. A repeat open of an existing (owner, host, window, port) returns its id and counts nothing.

View Source
const (
	// UpstreamHeaderTimeout bounds the wait for an app's response headers
	// (the design's "upstream headers" limit).
	UpstreamHeaderTimeout = 60 * time.Second
	// StreamKeepalive is the browser-leg WebSocket ping interval and the
	// quiet-SSE comment interval: well under the edge's ~125 s idle cut.
	StreamKeepalive = 30 * time.Second
)
View Source
const (

	// ProbeWait bounds Open-on-offer's CONNECT probe.
	ProbeWait = 5 * time.Second
	// PollEvery is how often the session page refreshes its list while it is
	// visible.
	PollEvery = 5 * time.Second
	// SlowPathLabel marks a host whose tunnel is on the public path.
	SlowPathLabel = "slow path (via Cloudflare)"
)
View Source
const (
	// FailLimit failed token checks per FailWindow per peer; the next is 429.
	FailLimit  = 10
	FailWindow = time.Minute
)

The failed-token throttle, as muster's mirror connect has it (docs/mirroring.md, "Tokens, revocation, rate limits"): only FAILURES count, a valid token is never refused by it, and a peer past the limit gets 429 instead of 401 for its failures. The token's 256 bits are the guessing defence; the throttle tells a misconfigured host it is hammering.

View Source
const CapabilityViewer = "viewer"

CapabilityViewer is the plugin capability a token must hold for the gateway to serve its owner.

View Source
const DefaultListen = ":8080"

DefaultListen is PREVIEW_LISTEN's default.

View Source
const (
	DefaultMaxBody = 32 << 20
)

DefaultMaxBody is PREVIEW_MAX_BODY's default (the design's 32 MiB), and minMaxBody its least value.

View Source
const DrainTimeout = 60 * time.Second

DrainTimeout bounds how long a replaced tunnel keeps its open streams.

View Source
const (
	// EntryCodeTTL is how long a gateway-minted entry code may be spent.
	EntryCodeTTL = 60 * time.Second
)
View Source
const ErrorCodeHeader = "X-Muster-Preview-Error"

ErrorCodeHeader names the code on every page the gateway answers for a p- request itself.

View Source
const LifecycleEvery = 30 * time.Second

LifecycleEvery is how often the idle, TTL and window-gone closes are checked; a preview closes at most this long after its limit passed.

View Source
const MaxCookieHeader = 8 << 10

MaxCookieHeader is the most Cookie header bytes a p- request may carry; past it, the reset page answers instead (cookieBomb).

View Source
const PurposeView = "view"

PurposeView is the only hand-off purpose the session page accepts in this phase (share links, purpose "share", are phase 3).

View Source
const ShareCookie = "__Host-mps"

ShareCookie is the phase-3 share-link cookie's name, reserved now so the proxy already keeps it from apps.

View Source
const TeamOwnerPrefix = "team:"

TeamOwnerPrefix names a team owner on `host-token create`: team:<id>.

View Source
const Version = "0.1.0"

Version is the gateway's version string.

View Source
const WindowGoneAfter = 10 * time.Minute

WindowGoneAfter closes a preview whose window has been absent from its host's window listing (wire.TypeWindows) this long.

Variables

View Source
var ErrHandoffRefused = errors.New("muster refused the hand-off code")

ErrHandoffRefused is Redeem's error when muster will not spend the code: unknown, used, expired or another plugin's (404), or the token cannot redeem at all (401, 403).

View Source
var ErrHostOffline = errors.New("previewgw: the host has no tunnel")

ErrHostOffline is Dial's error when the (owner, host) has no live tunnel.

View Source
var ErrNoHostToken = errors.New("no host token with that id")

ErrNoHostToken is Revoke's error for an id the file does not hold.

Functions

func BaseURL

func BaseURL(name, v string) (string, error)

BaseURL validates an absolute http(s) base URL with no query, user or fragment, and strips a trailing slash.

func CheckStateDir

func CheckStateDir(v string) (string, error)

CheckStateDir requires STATE_DIR to name an existing directory.

func HashToken

func HashToken(tok string) string

HashToken is a token's stored form.

func ReadPluginTokens

func ReadPluginTokens(path string) ([]string, error)

ReadPluginTokens reads PLUGIN_TOKENS_FILE: one mpl_ token per line; blank lines are skipped. At least one token is required. A token is never echoed in an error.

func TokenShapeOK

func TokenShapeOK(s string) bool

TokenShapeOK reports whether s is shaped like a host token: the prefix and exactly the base64url characters of 32 bytes. A string that is not is refused without reading the file.

Types

type Clock

type Clock interface {
	Now() time.Time
	// AfterFunc runs f once, d from now, and returns its cancel.
	AfterFunc(d time.Duration, f func()) (stop func() bool)
}

Clock is the gateway's time: its periodic checks and the drain timer run on it, so tests drive them without sleeping.

type Config

type Config struct {
	// MusterURL is muster's API base (MUSTER_URL), for GET /plugin/v1/self;
	// it may be an in-cluster address.
	MusterURL string
	// PublicURL is muster's public URL as browsers see it
	// (MUSTER_PUBLIC_URL). Required and validated now; the session page and
	// the preview origins put its origin in frame-ancestors.
	PublicURL string
	// PluginTokens are the owners' mpl_ tokens (PLUGIN_TOKENS_FILE), one per
	// line, in file order.
	PluginTokens []string
	// Domain is the preview zone (PREVIEW_DOMAIN), lowercase, no dot at
	// either end; the public listener serves the host tunnel on
	// tunnel.<Domain>.
	Domain string
	// Listen is the public listener's address (PREVIEW_LISTEN).
	Listen string
	// MeshListen is the mesh listener's address (PREVIEW_MESH_LISTEN); empty
	// means no mesh listener.
	MeshListen string
	// StateDir holds the host-token file and its lock (STATE_DIR).
	StateDir string
	// SigningKey signs owner cookies and page tokens (PREVIEW_SIGNING_KEY),
	// at least MinSigningKey bytes. Rotating it ends every owner cookie and
	// page token already given out.
	SigningKey []byte
	// TTL closes a preview this long after it opened (PREVIEW_TTL); reopening
	// mints a new id. Zero means DefaultTTL.
	TTL time.Duration
	// Idle closes a preview that has had no request for this long
	// (PREVIEW_IDLE); an open connection counts as a request in progress.
	// Zero means DefaultIdle.
	Idle time.Duration
	// MaxBody is the most request-body bytes one proxied request may send
	// (PREVIEW_MAX_BODY); past it the request is refused 413 body_too_large.
	// Zero means DefaultMaxBody.
	MaxBody int64
}

Config is the gateway's configuration.

func LoadConfig

func LoadConfig(getenv func(string) string) (Config, error)

LoadConfig reads the serve configuration from getenv.

type Gateway

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

Gateway is the running preview gateway.

func New

func New(cfg Config, o Options) (*Gateway, error)

New builds a gateway; Start begins its checks.

func (*Gateway) Boot

func (g *Gateway) Boot() string

Boot is this process's boot id (wire.GatewayBootHeader).

func (*Gateway) CheckOwners

func (g *Gateway) CheckOwners(ctx context.Context)

CheckOwners asks /self for every plugin token, and closes the tunnels and previews of every owner that was served and no longer is: one whose token answered 401, or 200 without the viewer capability, with no other live token of that owner. A token muster did not answer for keeps its last verdict for UnknownLimit-1 checks; at the UnknownLimit-th in a row it is no longer live (its owner closes as above) until muster answers again.

func (*Gateway) Close

func (g *Gateway) Close()

Close stops the checks and ends every tunnel.

func (*Gateway) Dial

func (g *Gateway) Dial(ctx context.Context, owner int64, host string, port int) (net.Conn, error)

Dial opens one upstream connection to port on the (owner, host)'s current tunnel. The connection holds the tunnel open while it is draining.

func (*Gateway) MeshHandler

func (g *Gateway) MeshHandler() http.Handler

MeshHandler serves the mesh listener (PREVIEW_MESH_LISTEN): the host tunnel, /metrics and /healthz, whatever the Host.

func (*Gateway) Previews

func (g *Gateway) Previews(owner int64) []Preview

Previews lists owner's open previews (any order).

func (*Gateway) PublicHandler

func (g *Gateway) PublicHandler() http.Handler

PublicHandler serves the public listener (PREVIEW_LISTEN), by Host: the host tunnel on tunnel.<domain>, the session page on w.<domain> (session.go), each open preview on p-<id>.<domain> (auth.go), and 404 for everything else. It serves no /metrics or /healthz: those are on the mesh listener, which the edge never reaches.

func (*Gateway) Recheck

func (g *Gateway) Recheck()

Recheck re-reads the host-token file and ends every tunnel whose token is gone, or no longer names the tunnel's owner and host. It also closes the previews of every (owner, host) no stored token names any more — whether or not that host has a tunnel now: a host revoked while offline must not keep previews a new token for the same name would re-attach.

func (*Gateway) Registry

func (g *Gateway) Registry() *prometheus.Registry

Registry is the gateway's own metrics registry.

func (*Gateway) Run

func (g *Gateway) Run(ctx context.Context) error

Run serves the public listener and, when configured, the mesh listener until ctx ends.

func (*Gateway) Start

func (g *Gateway) Start(ctx context.Context)

Start asks /self for every plugin token once, then starts the minute-by- minute /self check, the 30 s host-token recheck and the lifecycle sweep.

func (*Gateway) Tunnels

func (g *Gateway) Tunnels() []TunnelInfo

Tunnels lists every live tunnel, the draining ones included.

type Handoff

type Handoff struct {
	OwnerID int64 `json:"owner_id"`
	Target  struct {
		Mirror *struct {
			Host    string `json:"host"`
			Session string `json:"session"`
			Window  string `json:"window"`
		} `json:"mirror"`
	} `json:"target"`
	Purpose string `json:"purpose"`
}

Handoff is POST /plugin/v1/handoffs/redeem's answer (internal/api plugin_handoffs.go). 🔴 The owner is owner_id — an identifier, never the login label.

type HostState

type HostState struct {
	// Config is the host's latest config line; nil before the first.
	Config *wire.Config
	// MaxConns is the tunnel's upstream-connection limit, fixed by the first
	// config that carried one (0 before then). A later config never raises
	// it: the host's HTTP/2 server was started with its own value when it
	// dialed, and a gateway limit above that only turns waits into refusals.
	MaxConns int
	// Windows is the host's latest window listing; HaveWindows is whether it
	// has sent one (an empty listing is omitted on the wire, so a nil Windows
	// alone cannot tell "none" from "not yet").
	Windows     []string
	HaveWindows bool
	Listeners   []wire.Listener
}

HostState is what a tunnel's offer stream has said, as of now.

type HostToken

type HostToken struct {
	ID string `json:"id"` // "ht_" + 8 hex; what ls prints and revoke takes
	// OwnerID is muster's owner id, from GET /plugin/v1/self when the token
	// was created: what the gateway keys the host's tunnel and previews on.
	OwnerID int64 `json:"owner_id"`
	// OwnerLogin is that owner's login as /self named it: a LABEL for ls,
	// never compared with anything.
	OwnerLogin string `json:"owner_login"`
	Host       string `json:"host"`
	Hash       string `json:"sha256"` // hex sha256 of the whole token
	Created    string `json:"created"`
}

HostToken is one stored host token. The secret itself is never stored.

type HostTokens

type HostTokens struct{ Dir string }

HostTokens is the token file in one STATE_DIR.

func (HostTokens) Create

func (s HostTokens) Create(ownerID int64, ownerLogin, host string, now time.Time) (string, HostToken, error)

Create mints a token for (ownerID, host), stores its hash, and returns the token (shown once) and its record. ownerLogin is stored as a label.

func (HostTokens) List

func (s HostTokens) List() ([]HostToken, error)

List reads every stored token under a shared lock. A missing file is an empty list.

func (HostTokens) Revoke

func (s HostTokens) Revoke(id string) (HostToken, error)

Revoke deletes the token with id. A gateway ends its tunnel at its next recheck (at most 30 s).

func (HostTokens) SortedForList

func (s HostTokens) SortedForList() ([]HostToken, error)

SortedForList is List's answer in ls order.

type MusterAPI

type MusterAPI interface {
	Self(ctx context.Context, token string) (Self, SelfVerdict, error)
	Redeem(ctx context.Context, token, code string) (Handoff, error)
}

MusterAPI is the muster calls the gateway makes (MusterClient): /self per plugin token, and redeeming a hand-off code for the session page.

type MusterClient

type MusterClient struct {
	Base string // MUSTER_URL, no trailing slash
	HTTP *http.Client
	UA   string
}

MusterClient calls muster's plugin door.

func NewMusterClient

func NewMusterClient(base, ua string) *MusterClient

NewMusterClient is a client with a bounded timeout.

func (*MusterClient) Redeem

func (m *MusterClient) Redeem(ctx context.Context, token, code string) (Handoff, error)

Redeem spends a hand-off code with token (which must hold viewer).

func (*MusterClient) Self

func (m *MusterClient) Self(ctx context.Context, token string) (Self, SelfVerdict, error)

Self asks who token is. The Self is filled only on a 200. The verdict is SelfDead on a 401 or a 200 without viewer, SelfLive on a 200 with it, and SelfUnknown otherwise (with an error saying why, never quoting the token).

func (*MusterClient) SelfAll

func (m *MusterClient) SelfAll(ctx context.Context, tokens []string) []SelfAnswer

SelfAll asks /self for every token, in order.

type Options

type Options struct {
	Clock  Clock
	Log    *slog.Logger
	Muster MusterAPI // nil: NewMusterClient(cfg.MusterURL)
	// DialWait bounds both waits for capacity: a request waiting for one of
	// its preview's MaxConnsPerPreview slots (useBegin), and a dial waiting
	// for one of the host's maxConns upstream slots (the tunnel's Dial). Each
	// refuses 429 when it passes; 0 means tunnel.DefaultDialWait.
	DialWait time.Duration
	// Tests only: the per-preview in-flight cap; 0 means MaxConnsPerPreview.
	MaxConnsPerPreview int
	// Tests only: the ping interval each tunnel's client uses.
	PingInterval time.Duration
	// Tests only: the browser-leg WebSocket ping and the quiet-SSE comment
	// interval; 0 means StreamKeepalive.
	StreamKeepalive time.Duration
}

Options are the gateway's collaborators; zero values take real ones.

type Path

type Path string

Path is which listener a tunnel arrived on.

const (
	PathMesh   Path = "mesh"
	PathPublic Path = "public"
)

type Preview

type Preview struct {
	ID      string
	OwnerID int64
	Host    string
	Window  string
	Session string // display only
	Port    int
	Label   string
	Path    string
	Opened  time.Time
	// contains filtered or unexported fields
}

Preview is one open preview, in memory only.

type Self

type Self struct {
	PluginID   int64  `json:"plugin_id"`
	PluginName string `json:"plugin_name"`
	OwnerID    int64  `json:"owner_id"`
	OwnerLogin string `json:"owner_login"`
	// OwnerKind is "team" for a team viewer plugin's token (team sharing
	// 2b.3b; OwnerLogin is then the team's name), "person" or "" (an older
	// muster) for a person's.
	OwnerKind    string   `json:"owner_kind"`
	Capabilities []string `json:"capabilities"`
}

Self is GET /plugin/v1/self's answer.

func ResolveOwner

func ResolveOwner(login string, answers []SelfAnswer) (Self, error)

ResolveOwner picks the owner a `host-token create` names, from the /self answers of every token in PLUGIN_TOKENS_FILE.

🔴 owner_login IS A LABEL, NOT AN IDENTIFIER (muster's email-else-display- name): two accounts can share one. So the login is matched against every LIVE answer, and the result is refused unless exactly one owner_id carries it. With login empty and exactly one live owner, that owner is the answer. A token whose answer is not live (401, no viewer, unreachable) cannot be named, and the error says how many were skipped.

A TEAM is named team:<id> (team sharing 2b.3b), never by its name: it has no login, and its name is a label as a login is. team:<id> matches only a live answer whose owner IS that team (owner_kind "team"), and a login never matches a team's answer. As for a person, which owner a host is minted for is the gateway admin's assertion.

func (Self) HasViewer

func (s Self) HasViewer() bool

HasViewer reports whether the token holds the viewer capability.

func (Self) IsTeam added in v0.229.0

func (s Self) IsTeam() bool

IsTeam reports whether the token's owner is a team.

type SelfAnswer

type SelfAnswer struct {
	Self    Self
	Verdict SelfVerdict
	Err     error
}

SelfAnswer is one token's /self result.

type SelfVerdict

type SelfVerdict int

SelfVerdict is what one /self call says about a token.

const (
	// SelfUnknown: no verdict (muster unreachable, a 5xx, a 404 because
	// plugins are off, an answer that does not parse). Nothing changes.
	SelfUnknown SelfVerdict = iota
	// SelfLive: 200 with the viewer capability.
	SelfLive
	// SelfDead: 401 (revoked token, disabled owner), or 200 WITHOUT the
	// viewer capability — treated exactly like a 401 (the capability is
	// what lets the gateway serve the owner at all).
	SelfDead
)

func (SelfVerdict) String

func (v SelfVerdict) String() string

type Tunnel

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

Tunnel is one host's accepted tunnel.

func (*Tunnel) Close

func (t *Tunnel) Close()

Close ends the tunnel.

func (*Tunnel) Done

func (t *Tunnel) Done() <-chan struct{}

Done is closed when the tunnel has ended.

type TunnelInfo

type TunnelInfo struct {
	Owner    int64
	Host     string
	Path     Path
	Draining bool
	Streams  int
	State    HostState
}

TunnelInfo is a tunnel as Tunnels reports it.

Jump to

Keyboard shortcuts

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