Documentation
¶
Overview ¶
Package localapi is the local control API of the porthole client daemon: HTTP/1.1 + JSON over a unix domain socket (see docs/adr/0002-client-daemon-and-tunnels-file.md). It contains the shared JSON types, the HTTP handler over a Backend, the Client used by the CLI, socket listen helpers, peer credentials and sd_notify.
The package is independent of internal/client: the daemon implements Backend on top of its tunnel manager.
Index ¶
- Constants
- Variables
- func ConnContext(ctx context.Context, c net.Conn) context.Context
- func CurrentSID() string
- func DefaultSocketPaths() []string
- func Dial(ctx context.Context, endpoint string) (net.Conn, error)
- func IsPermissionDenied(err error) bool
- func IsPipePath(endpoint string) bool
- func IsUnavailable(err error) bool
- func Listen(socketPath string, mode os.FileMode) (net.Listener, error)
- func ListenAllow(socketPath string, mode os.FileMode, allow []string) (net.Listener, error)
- func NewHandler(b Backend, log *slog.Logger) http.Handler
- func Notify(state string) (bool, error)
- func Serve(ctx context.Context, ln net.Listener, handler http.Handler, log *slog.Logger) error
- func UserSocketPath() string
- func WithPeerCred(ctx context.Context, cred Cred) context.Context
- type AddTunnelRequest
- type Backend
- type Client
- func (c *Client) AddTunnel(ctx context.Context, req AddTunnelRequest) (Tunnel, error)
- func (c *Client) Attach(ctx context.Context, req AddTunnelRequest, fn func(Event) error) error
- func (c *Client) Close()
- func (c *Client) Events(ctx context.Context, fn func(Event) error) error
- func (c *Client) Reload(ctx context.Context) (ReloadResult, error)
- func (c *Client) RemoveTunnel(ctx context.Context, name string) error
- func (c *Client) Status(ctx context.Context) (Status, error)
- func (c *Client) Tunnels(ctx context.Context) ([]Tunnel, error)
- type Cred
- type Error
- type Event
- type ReloadResult
- type Status
- type Tunnel
Constants ¶
const ( NotifyReady = "READY=1" NotifyStopping = "STOPPING=1" )
sd_notify states.
const ( // Host is the only Host header value the handler accepts (tailscale does the same with a fixed fake host). Host = "porthole" // MaxBodyBytes caps every request body. MaxBodyBytes = 64 << 10 )
const ( CodeInvalidRequest = proto.CodeInvalidRequest CodeForbidden = proto.CodeForbidden CodeNameTaken = proto.CodeNameTaken CodeInternal = proto.CodeInternal CodeNotFound = "not_found" CodeConflict = "conflict" )
Error codes. The proto codes are reused where they have the same meaning.
const ( StateConnecting = "connecting" StateConnected = "connected" StateBackoff = "backoff" )
Connection states reported in Status.State.
const ( TunnelPending = "pending" TunnelReady = "ready" TunnelFailed = "failed" )
Tunnel states reported in Tunnel.State.
const ( TypeHTTP = "http" TypeTCP = "tcp" TypeSSH = "ssh" // reachable through the SSH gateway (with public_port: a tcp tunnel to port 22) )
Tunnel types.
const ( SourceFile = "file" SourceRuntime = "runtime" )
Tunnel sources reported in Tunnel.Source.
const ( LifetimeFile = "file" LifetimeRuntime = "runtime" // lives until DELETE or a daemon restart LifetimeAttached = "attached" // removed when the request connection closes )
Tunnel lifetimes. LifetimeFile only appears in Tunnel.Lifetime; requests use attached or runtime.
const ( EventConnected = "connected" EventDisconnected = "disconnected" EventTunnelReady = "tunnel_ready" EventTunnelClosed = "tunnel_closed" // EventAttached is only ever the first line of an attached POST /v1/tunnels stream. It carries the accepted // tunnel in Event.Tunnel (the name may have been chosen by the daemon). EventAttached = "attached" )
Event types.
Variables ¶
var ErrAlreadyRunning = errors.New("localapi: another porthole daemon is already listening on the socket")
ErrAlreadyRunning is returned by Listen when another process answers on the socket path.
var ErrStopStream = errors.New("localapi: stop stream")
ErrStopStream can be returned by a stream callback of Client.Attach and Client.Events to end the stream cleanly; the method then returns nil.
var SystemSocketPath = systemSocketPath()
SystemSocketPath is the endpoint of the system daemon: /run/porthole/porthole.sock on Linux (systemd RuntimeDirectory=porthole), /var/run/porthole/porthole.sock on macOS and other Unix systems, and the named pipe \\.\pipe\ProtectedPrefix\Administrators\porthole on Windows (only administrators can create pipes under that prefix, so no other user can squat the name).
Functions ¶
func ConnContext ¶
ConnContext is an http.Server.ConnContext function that stores the peer credentials of the connection in the context. Serve installs it; handlers read the result with PeerCredFromContext.
func DefaultSocketPaths ¶
func DefaultSocketPaths() []string
DefaultSocketPaths lists where the CLI looks for a daemon: the user endpoint first, then the system one.
func Dial ¶
Dial connects to the daemon endpoint at endpoint: a named pipe (Windows only) or a unix socket. The connect is bounded by a timeout. A user pipe is verified before it is returned: it must be owned by the current user and grant access to nobody else, because a pipe name outside \\.\pipe\ProtectedPrefix\Administrators can be created by any user in advance (squatting).
func IsPermissionDenied ¶
IsPermissionDenied reports whether err means that the socket exists but the caller may not use it (EACCES, or access denied on Windows). The caller must not fall back to running standalone then: a second session with the same token would replace the daemon's.
func IsPipePath ¶
IsPipePath reports whether endpoint names a Windows named pipe (it starts with \\.\pipe\, case-insensitive). Any other value is a unix socket path.
func IsUnavailable ¶
IsUnavailable reports whether err means that no daemon is listening on the socket: the socket file does not exist or nobody accepts on it. The caller should then run standalone. API errors (*Error) never match.
func Listen ¶
Listen creates a listener at socketPath with the given permission bits: a unix socket, or on Windows a named pipe when socketPath is a pipe path (see IsPipePath); a pipe path on another OS is an error. It is ListenAllow without extra principals.
A named pipe under \\.\pipe\ProtectedPrefix\Administrators (the SystemSocketPath on Windows) gets the DACL SYSTEM + Administrators, any other pipe is owned by and open only to the current user; creating a system pipe needs an elevated process. mode is ignored for pipes, and "already running" means that a connection to the pipe succeeds.
For a unix socket:
The parent directory is created with mode 0700 if it does not exist; an existing directory is left untouched (the system unit's RuntimeDirectory decides its mode). If the path already exists and something answers on it, Listen returns ErrAlreadyRunning; a stale socket is removed. The socket is chmod-ed after listening (skipped on Windows, where the directory ACL is the access control). Two processes starting at the same moment can still race between the probe and the bind; the loser gets ErrAlreadyRunning when the bind reports "address in use".
func ListenAllow ¶
ListenAllow is Listen that also admits the principals in allow to a system named pipe: user or group names (for example "BUILTIN\\Users") or SIDs ("S-1-5-32-545"), each given read and write access without the right to create further pipe instances. It is an error to pass allow for a pipe outside ProtectedPrefix\Administrators (anybody could squat such a name, so the pipe stays private to its owner). allow is ignored for unix sockets: their access control is mode and the directory.
func NewHandler ¶
NewHandler returns the HTTP handler of the local API. It rejects requests whose Host is not "porthole" and any request carrying an Origin or Referer header (a browser can never be the caller), caps request bodies at MaxBodyBytes and logs the peer credentials (see ConnContext) of every mutating call. A nil log discards logs.
func Notify ¶
Notify sends state (for example NotifyReady) to the service manager over $NOTIFY_SOCKET (sd_notify(3)). It returns false without an error when $NOTIFY_SOCKET is not set or on Windows, so it is safe to call unconditionally. An address starting with '@' is an abstract socket.
func Serve ¶
Serve serves handler on ln until ctx is done, then shuts down gracefully: open event streams are ended (the request contexts are cancelled), and connections still busy after a short grace period are closed. It sets header and idle timeouts, puts the peer credentials of every connection into the request context (see ConnContext) and takes ownership of ln. It returns nil after a graceful shutdown.
func UserSocketPath ¶
func UserSocketPath() string
UserSocketPath returns the per-user socket path, or "" if the user's directories cannot be determined.
- Linux: $XDG_RUNTIME_DIR/porthole/porthole.sock. If XDG_RUNTIME_DIR is unset (no systemd user session) it falls back to <UserCacheDir>/porthole/porthole.sock (~/.cache/porthole/porthole.sock) rather than a /tmp/porthole-<uid> directory: a directory in the shared /tmp can be pre-created by another user (squatting), a directory under the user's home cannot.
- Windows: the named pipe \\.\pipe\porthole-<SID> of the current user (owner-only DACL, checked by the client).
- macOS: <UserCacheDir>/porthole/porthole.sock (~/Library/Caches/porthole/porthole.sock; short, unlike $TMPDIR).
func WithPeerCred ¶
WithPeerCred returns a context that carries cred as the peer credentials, as ConnContext would store them. It is meant for embedders and tests that call a Backend directly.
Types ¶
type AddTunnelRequest ¶
type AddTunnelRequest struct {
Type string `json:"type"` // http | tcp | ssh
Name string `json:"name,omitempty"`
Addr string `json:"addr,omitempty"`
RemotePort int `json:"remote_port,omitempty"`
Lifetime string `json:"lifetime,omitempty"` // attached (default) | runtime
// Private (ssh only) makes the SSH gateway require a porthole token.
Private bool `json:"private,omitempty"`
// Inspect (http only) asks the server to store request and response bodies and headers of the tunnel.
Inspect bool `json:"inspect,omitempty"`
// PublicPort (ssh only) selects the v0.1 mode: a public TCP port instead of the gateway. RemotePort is only
// valid together with it.
PublicPort bool `json:"public_port,omitempty"`
}
AddTunnelRequest is the body of POST /v1/tunnels.
type Backend ¶
type Backend interface {
// Status returns the current daemon state.
Status(ctx context.Context) Status
// Tunnels returns all tunnels (file and runtime), ordered by name.
Tunnels(ctx context.Context) []Tunnel
// AddTunnel adds a tunnel to the set and returns quickly, once the tunnel is accepted; its state may still
// be pending. Validation problems and name conflicts are returned as *Error (invalid_request, name_taken,
// conflict). req.Lifetime is "attached" or "runtime" (the handler has validated it); the tunnel's
// Lifetime field reports it back.
AddTunnel(ctx context.Context, req AddTunnelRequest) (Tunnel, error)
// RemoveTunnel removes a tunnel by name. It returns *Error with not_found, or conflict for tunnels that
// come from the tunnels file.
RemoveTunnel(ctx context.Context, name string) error
// Reload re-reads the tunnels file and applies the difference. A broken file keeps the old set and is
// reported as an *Error (invalid_request); per-tunnel failures go to ReloadResult.Errors.
Reload(ctx context.Context) (ReloadResult, error)
// Subscribe returns a stream of events. The channel is closed when ctx is done. Delivery is best effort: a
// consumer that does not keep up may miss events (the backend must never block on a slow consumer). A
// failed registration of a tunnel is reported as EventTunnelClosed with Error set.
Subscribe(ctx context.Context) <-chan Event
}
Backend is what the daemon implements and the handler serves. All methods must be safe for concurrent use.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to the local API of a daemon over its unix socket or (Windows) named pipe.
func NewClient ¶
NewClient returns a client for the daemon endpoint at socketPath: a unix socket path or, on Windows, a named pipe path (see Dial). Nothing is dialled until the first call. Call Client.Close to release idle connections.
func (*Client) AddTunnel ¶
AddTunnel adds a runtime tunnel (it stays until Client.RemoveTunnel or a daemon restart); req.Lifetime is ignored. It returns once the daemon has accepted the tunnel; the state may still be pending, watch Client.Events.
func (*Client) Attach ¶
Attach adds an attached tunnel and streams its events to fn, which runs in the calling goroutine. The daemon removes the tunnel when the stream ends, so Attach blocks for as long as the tunnel should live: until ctx is done (it then returns ctx.Err()), the daemon ends the stream (nil), or fn returns an error (ErrStopStream ends cleanly with nil, anything else is returned as is). req.Lifetime is ignored.
The first event has Type EventAttached and carries the accepted Tunnel; after it come the connected and disconnected events and the events of this tunnel (tunnel_ready, tunnel_closed). A failed registration arrives as tunnel_closed with Error set; the stream stays open, so fn should return an error to end it. When the daemon rejects the request, Attach returns the *Error without calling fn.
func (*Client) Close ¶
func (c *Client) Close()
Close closes idle connections. The client stays usable.
func (*Client) Events ¶
Events streams daemon events to fn until ctx is done (returns ctx.Err()), the daemon ends the stream (nil), or fn returns an error (see Client.Attach). Events may be missed if fn is slow.
func (*Client) Reload ¶
func (c *Client) Reload(ctx context.Context) (ReloadResult, error)
Reload asks the daemon to re-read its tunnels file.
func (*Client) RemoveTunnel ¶
RemoveTunnel removes a tunnel by name.
type Cred ¶
Cred is the identity of the process on the other end of a local API connection.
UID, GID and PID are -1 when the platform cannot provide them (on macOS the PID or the GID may be unavailable; on Windows there is no UID or GID). SID is the Windows user SID ("S-1-5-21-..."), empty elsewhere. User is the account name of the caller (the Windows account "DOMAIN\name", or the Unix user resolved from UID), empty when it cannot be resolved.
On Windows SID is empty when the token of the caller cannot be read. Admin is set on Windows when that token has the BUILTIN\Administrators group enabled: a member of the group running with a UAC-filtered token (the group is "deny only" there) is not an administrator for this purpose. It is always false elsewhere.
func PeerCred ¶
PeerCred returns the credentials of the peer of c: SO_PEERCRED on Linux, LOCAL_PEERCRED and LOCAL_PEERPID on macOS, the token of the pipe client (ImpersonateNamedPipeClient) on Windows. The second result is false when c is not a connection of the local API listener or the platform has no peer credentials.
func PeerCredFromContext ¶
PeerCredFromContext returns the credentials stored by ConnContext.
type Error ¶
Error is an API error. It is the JSON body {"error":{"code":...,"message":...}} on the wire and implements error.
type Event ¶
type Event struct {
Type string `json:"type"` // connected | disconnected | tunnel_ready | tunnel_closed | attached
Name string `json:"name,omitempty"`
PublicURL string `json:"public_url,omitempty"`
SSHJump string `json:"ssh_jump,omitempty"`
Reason string `json:"reason,omitempty"`
ClientName string `json:"client_name,omitempty"`
Error string `json:"error,omitempty"`
RetryInMS int64 `json:"retry_in_ms,omitempty"`
Time time.Time `json:"time"`
Tunnel *Tunnel `json:"tunnel,omitempty"` // only for EventAttached
}
Event is one line of the /v1/events stream and of an attached POST /v1/tunnels stream.
type ReloadResult ¶
type ReloadResult struct {
Added []string `json:"added"`
Removed []string `json:"removed"`
Changed []string `json:"changed"`
Unchanged []string `json:"unchanged"`
Errors map[string]string `json:"errors,omitempty"` // per-tunnel failures
}
ReloadResult is the outcome of POST /v1/reload: tunnel names by what the reload did to them.
type Status ¶
type Status struct {
Version string `json:"version"`
PID int `json:"pid"`
StartedAt time.Time `json:"started_at"`
Server string `json:"server"`
State string `json:"state"` // connecting | connected | backoff
ClientName string `json:"client_name"`
RetryAt *time.Time `json:"retry_at,omitempty"`
LastError string `json:"last_error,omitempty"`
TunnelsFile string `json:"tunnels_file,omitempty"`
Tunnels []Tunnel `json:"tunnels"`
}
Status is the daemon state returned by GET /v1/status.
type Tunnel ¶
type Tunnel struct {
Name string `json:"name"`
Type string `json:"type"` // http | tcp | ssh
LocalAddr string `json:"local_addr"`
RemotePort int `json:"remote_port,omitempty"`
PublicURL string `json:"public_url,omitempty"`
Private bool `json:"private,omitempty"` // ssh only
Inspect bool `json:"inspect,omitempty"` // http only: bodies are stored on the server
SSHJump string `json:"ssh_jump,omitempty"` // ssh only: host:port of the SSH gateway, once ready
State string `json:"state"` // pending | ready | failed
Error string `json:"error,omitempty"`
Source string `json:"source"` // file | runtime
Lifetime string `json:"lifetime"` // file | runtime | attached
}
Tunnel describes one tunnel of the daemon.