expose

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 20 Imported by: ? 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 expose is the client side of `iap expose`: it publishes a local HTTP server (127.0.0.1:<port>) at https://<name>.<domain> through a tunnel service behind an iap-authz proxy (the iap-tunnel server, which is not part of this module and imports this package's wire protocol).

The client dials the tunnel endpoint with an ordinary agent token for that host (iapclient.TokenSource), as a WebSocket carrying a yamux session; the service opens one stream per visitor connection and the client pipes it to the local port. Every visitor request still passes the proxy's ForwardAuth. The wire protocol is in proto.go.

Unlike iapclient, this package has dependencies outside the standard library (github.com/coder/websocket, github.com/hashicorp/yamux).

Index

Constants

View Source
const (
	ConnectPath    = "/v1/connect"
	QueryName      = "name"
	QueryReserve   = "reserve"
	QueryTake      = "take"
	QueryPublic    = "public"
	InstanceHeader = "X-IAP-Tunnel-Instance"

	// MaxReserve is the longest reservation: 30 days after the last
	// disconnect, renewed by every connect. Independent of the
	// registration's own expiry.
	MaxReserve = 30 * 24 * 60 * 60 // seconds
)

The wire protocol between `iap expose` and the tunnel service (the iap-tunnel server), which imports these definitions so the two never drift. Changing anything here is a protocol change: see CLAUDE.md.

  1. The client sends GET https://tunnel.<domain>/v1/connect as a WebSocket upgrade, with Proxy-Authorization: Bearer <agent token for tunnel.<domain>> (the IAP's ForwardAuth checks it and hands the service X-IAP-Identity) and InstanceHeader. Query: QueryName, optional QueryReserve (whole seconds), QueryTake=1 and QueryPublic=1 (claim <name>.<public domain>, served without the IAP, instead of <name>.<domain>).
  2. A refusal is a plain HTTP response with a JSON Refusal body. Anything else non-101 (the IAP's 401/403, a 5xx) is not the service speaking.
  3. After the upgrade, binary WebSocket messages carry a yamux session: the service is the yamux client and opens streams, the CLI the yamux server. The first stream is the control stream: the service writes one JSON Control message per line (Ready, then possibly Closing).
  4. Every later stream is one connection to the CLI's local port: the service writes an HTTP/1.1 request on it (keep-alive and Upgrade included) and the CLI pipes the bytes both ways to 127.0.0.1:<port>.
View Source
const (
	CodeInvalidName     = "invalid_name"          // syntax or IDN
	CodeReservedName    = "reserved_name"         // a name the service keeps for itself
	CodeNameTaken       = "name_taken"            // another owner holds it, or it is live/reserved without --take
	CodeQuota           = "quota_exceeded"        // the owner holds the maximum number of names
	CodeBadRequest      = "bad_request"           // a malformed parameter
	CodeNotAgent        = "principal_not_allowed" // a principal kind that may not open tunnels
	CodeUnauthenticated = "unauthenticated"       // no or invalid X-IAP-Identity
	CodeUnavailable     = "unavailable"           // the service could not persist the reservation; retry
	CodeRateLimited     = "rate_limited"          // too many connects or open connections for this owner, or the service is full; retry
	CodePublicDenied    = "public_not_allowed"    // --public: no public-page entry allows this name for this principal, or public pages are off
)

Refusal codes. All are final for the CLI except CodeUnavailable and CodeRateLimited.

View Source
const (
	TypeReady   = "ready"
	TypeClosing = "closing"
	// TypeRefused: the claim was refused after the upgrade (another
	// connect won the name in between); Error/Message/Holder as in Refusal.
	TypeRefused = "refused"
)

Control message types.

View Source
const (
	ReasonTaken    = "taken"    // another registration of the same owner used --take; final
	ReasonReplaced = "replaced" // this process connected again; the old connection drains
	// ReasonSuperseded: another process of the same registration connected
	// (the box restarted before the service noticed); final for this one.
	ReasonSuperseded = "superseded"
	ReasonMaxAge     = "max_age"  // the connection outlived its token's longest lifetime; reconnect
	ReasonShutdown   = "shutdown" // the service is stopping; reconnect
	ReasonInternal   = "internal" // the service failed to record the claim; reconnect
)

Closing reasons.

Variables

View Source
var InstanceRE = regexp.MustCompile(`^[0-9a-f]{16,64}$`)

InstanceRE is an instance id: random hex the CLI picks once per process, so the service tells a reconnect of the same process from another one.

Functions

func Run

func Run(ctx context.Context, o Options) error

Run publishes the backend until ctx ends (nil) or the name is lost for good (a *Refusal, *TakenError, *ProxyRefusedError or a credential error). Network failures and service restarts are retried with backoff.

Types

type Control

type Control struct {
	Type string `json:"type"`
	// Ready.
	URL            string `json:"url,omitempty"`
	MaxAgeSeconds  int    `json:"max_age_seconds,omitzero"`
	ReserveSeconds int    `json:"reserve_seconds,omitzero"`
	TookFrom       string `json:"took_from,omitempty"` // the registration --take moved the name from
	// Closing.
	Reason string `json:"reason,omitempty"`
	By     string `json:"by,omitempty"` // ReasonTaken: the registration that took it
	// Refused.
	Error   string `json:"error,omitempty"`
	Message string `json:"message,omitempty"`
	Holder  string `json:"holder,omitempty"`
}

Control is one line on the control stream.

func (Control) MarshalLine

func (c Control) MarshalLine() []byte

MarshalLine renders c as one JSON line.

type Options

type Options struct {
	// Name is the host label: the page is https://<Name>.<Domain>.
	Name string
	// Domain is the tunnel service's domain (e.g. iap.example.com); the
	// endpoint is https://tunnel.<Domain> unless Endpoint is set.
	Domain   string
	Endpoint string
	// Backend is the local address requests go to (127.0.0.1:<port>).
	Backend string
	// Reserve keeps the name this long after the last disconnect (0: about a
	// minute). Take moves a name from another of the owner's registrations
	// or processes, on the first connect only.
	Reserve time.Duration
	Take    bool
	// Public claims <Name>.<the service's public domain> instead: served
	// without the IAP, and only where the service's public-page list allows
	// this name for this principal. The connection still goes to the
	// endpoint, through the IAP.
	Public bool
	Tokens Tokens
	// HTTPClient performs the WebSocket handshake. Its Timeout must be 0.
	// Redirects are never followed (a copy is used). Default:
	// http.DefaultClient.
	HTTPClient *http.Client
	// Log receives status lines (the URL once live, reconnects). Default:
	// io.Discard.
	Log io.Writer
	// OnReady is called once, when the page is first live.
	OnReady func(url string)
	// Backoff bounds between failed connects. Defaults 1s and 30s.
	MinBackoff, MaxBackoff time.Duration
	// Now is the clock; default time.Now.
	Now func() time.Time
}

Options configures Run.

type ProxyRefusedError

type ProxyRefusedError struct {
	Status    int
	Code      string
	Principal string
	Host      string
}

ProxyRefusedError: the IAP in front of the tunnel endpoint refused the connect (no grant for this agent on the endpoint host). Final.

func (*ProxyRefusedError) Error

func (e *ProxyRefusedError) Error() string

type RedirectError

type RedirectError struct {
	Status   int
	Location string
}

RedirectError: the tunnel endpoint answered the handshake with a redirect. Behind the IAP that is its sign-in page: the request was not authenticated as an agent (the token was not sent or not accepted, or the route is not behind the bearer-aware ForwardAuth). Final.

func (*RedirectError) Error

func (e *RedirectError) Error() string

type Refusal

type Refusal struct {
	Code    string `json:"error"`
	Message string `json:"message"`
	// Holder is the registration holding a taken name, when it has the
	// caller's owner (so the caller can decide on --take). Never set for
	// another owner's name.
	Holder string `json:"holder,omitempty"`
}

Refusal is the JSON body of a refused connect.

func (*Refusal) Error

func (r *Refusal) Error() string

type SupersededError

type SupersededError struct{ Name string }

SupersededError: another process of the same registration connected for the name (the box restarted, or a second `iap expose` of it ran). Final.

func (*SupersededError) Error

func (e *SupersededError) Error() string

type TakenError

type TakenError struct{ Name, By string }

TakenError: another registration or process of the same owner moved the name with --take. Final.

func (*TakenError) Error

func (e *TakenError) Error() string

type Tokens

type Tokens interface {
	Token(ctx context.Context, host string) (iapclient.Token, error)
}

Tokens mints access tokens for one exact host; *iapclient.TokenSource is one.

Jump to

Keyboard shortcuts

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