adminapi

package
v0.4.0-alpha.10 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: Apache-2.0 Imports: 23 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 adminapi is the server's management API (ADR 0005): HTTP+JSON over a local unix socket (access is the file permission, full admin) and over the public listener under Prefix (bearer token with admin:* scopes). It is the only management path; the CLI and the MCP surfaces are thin clients of it.

The package knows nothing about the server's internals: it talks to a Backend (live state) and a Store (persistent state), both supplied by the caller.

Index

Constants

View Source
const (
	// Prefix is the path prefix of every endpoint, on the socket and on the public listener alike.
	Prefix = "/_porthole/admin/v1"
	// ActorSocket is the audit actor of calls that arrive on the unix socket.
	ActorSocket = "socket"
)
View Source
const (

	// ActionRemoteOpen is the audit action of a remote tunnel request.
	ActionRemoteOpen = "tunnel.remote_open"

	// CodeRemoteDisabled is the error code when the client's token does not allow remote control.
	CodeRemoteDisabled = "remote_control_disabled"
)
View Source
const SocketSupported = true

SocketSupported reports whether this platform serves the admin unix socket.

Variables

View Source
var (
	// ErrNotFound reports an unknown client, tunnel or token (HTTP 404).
	ErrNotFound = errors.New("adminapi: not found")
	// ErrUnauthorized reports a missing, malformed, unknown, revoked or expired token (HTTP 401).
	ErrUnauthorized = errors.New("adminapi: unauthorized")
)

Errors that Backend and Options.Authenticate implementations return.

Functions

func JoinLink(serverURL, code string) string

JoinLink returns the link for a join code string under serverURL: <server_url>/j/<code>.

func ListenUnix

func ListenUnix(ctx context.Context, path string) (net.Listener, error)

ListenUnix creates the admin socket at path with mode 0600, replacing a stale socket file left by a crashed process. It refuses to replace a live socket or a file that is not a socket.

The socket is bound inside a private staging directory (mode 0700, created next to path), chmod-ed to 0600 and only then renamed to path. So it is unreachable for other users until its mode is final, and the process-wide umask is never touched: a umask change would race with every file or directory that another goroutine (the SSH gateway, the ACME cache, the log) creates meanwhile. Docker's go-connections tightens the umask instead; that is safe only before any other goroutine runs (idea only, no code copied).

func RevokeToken

func RevokeToken(ctx context.Context, st Store, be Backend, id string, now time.Time) error

RevokeToken revokes the token with this id (not a name) and closes its live sessions at once through be, if be can. The admin API and the MCP server share it.

Types

type API

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

API serves the admin endpoints.

func New

func New(opts Options) (*API, error)

New builds the API. Backend, Store and Authenticate are required.

func (*API) BearerHandler

func (a *API) BearerHandler() http.Handler

BearerHandler serves the API for the public listener: every request needs a valid token. Mount it for paths under Prefix.

func (*API) SocketHandler

func (a *API) SocketHandler() http.Handler

SocketHandler serves the API for the unix socket: no token, full access, actor "socket". Only hand it to a listener whose access is limited by file permissions.

type AuditEntry

type AuditEntry struct {
	ID     int64     `json:"id"`
	At     time.Time `json:"at"`
	Actor  string    `json:"actor"`
	Action string    `json:"action"`
	Target string    `json:"target,omitempty"`
	Args   string    `json:"args,omitempty"`
	Result string    `json:"result"`
}

AuditEntry is one audit log record.

type Backend

type Backend interface {
	// Status returns the server version, uptime and counters.
	Status(ctx context.Context) (Status, error)
	// Clients lists the connected clients (one session per client name), ordered by name.
	Clients(ctx context.Context) ([]Client, error)
	// Disconnect drops the connection of the named client; the client may reconnect. ErrNotFound if it is offline.
	Disconnect(ctx context.Context, name string) error
	// Tunnels lists the registered tunnels, ordered by client and name.
	Tunnels(ctx context.Context) ([]Tunnel, error)
	// CloseTunnel closes the tunnel with the given id and tells its client. ErrNotFound if there is none.
	CloseTunnel(ctx context.Context, id string) error

	// Requests returns the logged HTTP requests matching f, newest first, without details.
	Requests(ctx context.Context, f traffic.RequestFilter) ([]traffic.Request, error)
	// RequestAggregates summarises the requests matching f; top lists hold at most topN entries.
	RequestAggregates(ctx context.Context, f traffic.RequestFilter, topN int) (traffic.Aggregates, error)
	// Request returns one logged request with its Detail (nil unless the request was inspected). ErrNotFound if
	// it is no longer in the log. The API drops Detail for callers without the admin:traffic scope.
	Request(ctx context.Context, id uint64) (traffic.Request, error)
	// ReplayRequest sends the recorded request again into its tunnel and returns the new log entry. It returns
	// ErrNotFound for an unknown id and a *ConflictError when the request cannot be replayed (not inspected,
	// body truncated, tunnel offline).
	ReplayRequest(ctx context.Context, id uint64) (traffic.Request, error)
	// Connections returns the logged TCP and SSH connections matching f, newest first.
	Connections(ctx context.Context, f traffic.ConnFilter) ([]traffic.Conn, error)
	// AuthFailures returns the SSH gateway authentication failures since the given time (zero for all), newest
	// first, at most limit of them (0 is the default).
	AuthFailures(ctx context.Context, since time.Time, limit int) ([]traffic.Conn, error)
	// RequestTunnel asks the named client to open a tunnel on its machine and waits for the outcome (at most 15 s).
	// ErrNotFound if the client is offline; *RemoteError if the request cannot be carried out.
	RequestTunnel(ctx context.Context, client string, req RemoteOpen) (RemoteTunnel, error)
}

Backend is the live state the API reads and acts on. The server implements it over its registry. Implementations must be safe for concurrent use.

type Client

type Client struct {
	Name          string    `json:"name"`
	SessionID     string    `json:"session_id"`
	TokenID       string    `json:"token_id"`
	Remote        string    `json:"remote"`
	ConnectedAt   time.Time `json:"connected_at"`
	ClientVersion string    `json:"client_version,omitempty"`
	OS            string    `json:"os,omitempty"`
	Tunnels       int       `json:"tunnels"`
}

Client is a connected client.

type ConflictError

type ConflictError struct{ Message string }

ConflictError reports a request that is valid but cannot be carried out in the current state (HTTP 409); its message is shown to the caller.

func (*ConflictError) Error

func (e *ConflictError) Error() string

type Error

type Error struct {
	HTTPStatus int
	Code       string
	Message    string
}

Error is an error response of the API.

func (*Error) Error

func (e *Error) Error() string

type ErrorBody

type ErrorBody struct {
	Error struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"error"`
}

ErrorBody is the JSON shape of every error response: {"error":{"code":"...","message":"..."}}.

type Grantor

type Grantor struct {
	// Actor is recorded as the creator of the link.
	Actor string
	// Trusted callers (the admin socket, an unauthenticated stdio server) may grant any scope.
	Trusted bool
	// Scopes are the scopes the caller holds; ignored when Trusted.
	Scopes []string
	// Name is the client name of the caller's token (it may be granted connect:<Name>); ignored when Trusted.
	Name string
	// ExpiresAt is the expiry of the caller's token, nil for none; links and minted tokens are capped by it.
	ExpiresAt *time.Time
	// MaxTunnels is the server's per-client limit (0 = none), the cap for MaxTunnels of the link.
	MaxTunnels int
}

Grantor is who creates a join link outside the HTTP API (the operator MCP server). It limits the scopes the link may hand out exactly as the API does for its callers.

type JoinCode

type JoinCode struct {
	ID             string     `json:"id"`
	ClientName     string     `json:"client_name"`
	Scopes         []string   `json:"scopes"`
	MaxTunnels     int        `json:"max_tunnels"`
	TokenExpiresAt *time.Time `json:"token_expires_at"`
	RemoteControl  bool       `json:"remote_control"`
	Status         string     `json:"status"` // active, used, revoked or expired
	CreatedAt      time.Time  `json:"created_at"`
	ExpiresAt      time.Time  `json:"expires_at"`
	UsedAt         *time.Time `json:"used_at"`
	RevokedAt      *time.Time `json:"revoked_at"`
	CreatedBy      string     `json:"created_by"`
}

JoinCode describes one join code in the list. It never holds the code or its hash.

type JoinCreated

type JoinCreated struct {
	ID         string    `json:"id"`
	Link       string    `json:"link"`
	Command    string    `json:"command"` // "porthole join <link>"
	ClientName string    `json:"client_name"`
	ExpiresAt  time.Time `json:"expires_at"`
	// TokenExpiresAt is when the token the link creates expires; nil = never. A bearer token's request is capped at
	// the creator's own expiry, so it may be earlier than asked.
	TokenExpiresAt *time.Time `json:"token_expires_at,omitempty"`
}

JoinCreated is the response of POST join. The link is shown once: the server keeps only a hash of the code.

func CreateJoin

func CreateJoin(ctx context.Context, st Store, serverURL string, now time.Time, g Grantor, req JoinRequest) (JoinCreated, error)

CreateJoin validates req and stores a one-time join code under the same rules as POST join, and returns the link. serverURL is the public URL the link is built on. Failures are *Error with the codes the API uses (invalid_request, forbidden, conflict).

type JoinRequest

type JoinRequest struct {
	ClientName     string   `json:"client_name"`
	Scopes         []string `json:"scopes,omitempty"`           // default: the tunnel scopes
	TTL            string   `json:"ttl,omitempty"`              // life of the link; default 15m
	MaxTunnels     int      `json:"max_tunnels,omitempty"`      // 0 = server default
	TokenExpiresIn string   `json:"token_expires_in,omitempty"` // life of the token created by the link; default: never
	RemoteControl  *bool    `json:"remote_control,omitempty"`   // accept tunnels opened remotely; default true
}

JoinRequest is the body of POST join. Durations are strings such as "15m", "2h" or "30d".

type Options

type Options struct {
	Backend Backend
	Store   Store
	// Authenticate resolves a bearer secret ("ph_<id>_<secret>") to an active token. It returns ErrUnauthorized,
	// *RateLimitedError or any other error (HTTP 500). ip is the caller's address, for rate limiting.
	Authenticate func(ctx context.Context, ip, raw string) (*store.Token, error)
	// ClientIP extracts the caller's address from a request (it may honour proxy headers). Default: RemoteAddr.
	ClientIP func(r *http.Request) string
	Now      func() time.Time
	Logger   *slog.Logger
	// ServerURL is the address clients connect to, the base of join links ("https://tun.example.com").
	ServerURL string
	// MaxTunnelsPerClient is the server's per-client tunnel limit. A join link made with a bearer token cannot grant
	// more; 0 means no limit.
	MaxTunnelsPerClient int
}

Options configures New.

type RateLimitedError

type RateLimitedError struct{ RetryAfter time.Duration }

RateLimitedError is returned by Options.Authenticate when the caller has failed too often (HTTP 429).

func (*RateLimitedError) Error

func (e *RateLimitedError) Error() string

type RemoteError

type RemoteError struct{ Code, Message string }

RemoteError is returned by Backend.RequestTunnel when the request was understood but could not be carried out. Codes: proto.CodeClientUnsupported, proto.CodeTimeout, proto.CodeNotAllowed, proto.CodeNameTaken, proto.CodeInvalidRequest, proto.CodePortUnavailable, proto.CodeLimitExceeded, CodeRemoteDisabled. A client that is not connected is ErrNotFound.

func (*RemoteError) Error

func (e *RemoteError) Error() string

type RemoteOpen

type RemoteOpen struct {
	// Kind is http, tcp or ssh.
	Kind string `json:"kind"`
	// LocalAddr is the target on the client's machine: a port, host:port, or "ssh" (127.0.0.1:22). Empty is allowed
	// for ssh only.
	LocalAddr  string `json:"local_addr,omitempty"`
	Name       string `json:"name,omitempty"`
	Private    bool   `json:"private,omitempty"`
	RemotePort int    `json:"remote_port,omitempty"`
	// RequestedBy is the acting token or "socket"; the API sets it, it is not read from the request body.
	RequestedBy string `json:"-"`
}

RemoteOpen asks a connected client to open a tunnel (POST .../clients/{name}/tunnels).

type RemoteTunnel

type RemoteTunnel struct {
	Name string `json:"name"`
	Kind string `json:"kind"`
	// URL is the public address (https URL for http, tcp://host:port for tcp, ssh target for ssh).
	URL string `json:"public_url"`
	// SSHJump is the host:port of the SSH gateway (kind ssh only).
	SSHJump string `json:"ssh_jump,omitempty"`
}

RemoteTunnel is the tunnel a client opened on request.

type SessionCloser

type SessionCloser interface {
	// TokenRevoked closes every session that authenticated with the token id and tells its client why.
	TokenRevoked(ctx context.Context, tokenID string)
}

SessionCloser is implemented by a Backend that can end the live sessions of a token. The API calls it after a token is revoked, so that revoking takes effect at once and not at the next revalidation of the session.

type SocketClient

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

SocketClient calls the admin API over the unix socket (no token needed).

func NewSocketClient

func NewSocketClient(path string) *SocketClient

NewSocketClient returns a SocketClient that talks to the admin socket at path.

func (*SocketClient) Audit

func (c *SocketClient) Audit(ctx context.Context, limit int) ([]AuditEntry, error)

Audit calls GET audit; limit 0 is the server's default.

func (*SocketClient) AuthFailures

func (c *SocketClient) AuthFailures(ctx context.Context, since time.Time, limit int) ([]traffic.Conn, error)

AuthFailures calls GET auth-failures: SSH gateway authentication failures since the given time, newest first.

func (*SocketClient) Clients

func (c *SocketClient) Clients(ctx context.Context) ([]Client, error)

Clients calls GET clients.

func (*SocketClient) CloseTunnel

func (c *SocketClient) CloseTunnel(ctx context.Context, id string) error

CloseTunnel calls DELETE tunnels/{id}.

func (*SocketClient) Connections

func (c *SocketClient) Connections(ctx context.Context, f traffic.ConnFilter) ([]traffic.Conn, error)

Connections calls GET connections: the logged TCP and SSH connections matching f, newest first.

func (*SocketClient) CreateJoin

func (c *SocketClient) CreateJoin(ctx context.Context, req JoinRequest) (JoinCreated, error)

CreateJoin calls POST join: it stores a one-time join code and returns its link.

func (*SocketClient) Disconnect

func (c *SocketClient) Disconnect(ctx context.Context, name string) error

Disconnect calls POST clients/{name}/disconnect.

func (*SocketClient) ListJoin

func (c *SocketClient) ListJoin(ctx context.Context) ([]JoinCode, error)

ListJoin calls GET join.

func (*SocketClient) ReleaseLabel

func (c *SocketClient) ReleaseLabel(ctx context.Context, label string) error

ReleaseLabel calls POST labels/{label}/release.

func (*SocketClient) ReplayRequest

func (c *SocketClient) ReplayRequest(ctx context.Context, id uint64) (traffic.Request, error)

ReplayRequest calls POST requests/{id}/replay and returns the new log entry.

func (*SocketClient) Request

func (c *SocketClient) Request(ctx context.Context, id uint64) (traffic.Request, error)

Request calls GET requests/{id}. The socket is fully trusted, so the result carries its Detail.

func (*SocketClient) RequestAggregates

func (c *SocketClient) RequestAggregates(ctx context.Context, f traffic.RequestFilter, topN int) (traffic.Aggregates, error)

RequestAggregates calls GET requests?aggregate=1: a summary of the requests matching f.

func (*SocketClient) RequestTunnel

func (c *SocketClient) RequestTunnel(ctx context.Context, client string, req RemoteOpen) (RemoteTunnel, error)

RequestTunnel calls POST clients/{name}/tunnels: the named client opens a tunnel and the call returns its address. Failures are *Error with the codes of RemoteError (and "not_found" for an offline client).

func (*SocketClient) Requests

Requests calls GET requests: the logged HTTP requests matching f, newest first, without details.

func (*SocketClient) RevokeJoin

func (c *SocketClient) RevokeJoin(ctx context.Context, id string) error

RevokeJoin calls POST join/{id}/revoke.

func (*SocketClient) RevokeToken

func (c *SocketClient) RevokeToken(ctx context.Context, id string) error

RevokeToken calls POST tokens/{id}/revoke.

func (*SocketClient) Status

func (c *SocketClient) Status(ctx context.Context) (Status, error)

Status calls GET status.

func (*SocketClient) Tokens

func (c *SocketClient) Tokens(ctx context.Context) ([]Token, error)

Tokens calls GET tokens.

func (*SocketClient) Tunnels

func (c *SocketClient) Tunnels(ctx context.Context) ([]Tunnel, error)

Tunnels calls GET tunnels.

type Status

type Status struct {
	Version       string    `json:"version"`
	StartedAt     time.Time `json:"started_at"`
	UptimeSeconds int64     `json:"uptime_seconds"`
	Clients       int       `json:"clients"`
	Tunnels       int       `json:"tunnels"`
}

Status is the GET status response.

type Store

type Store interface {
	GetToken(ctx context.Context, id string) (*store.Token, error)
	ListTokens(ctx context.Context) ([]*store.Token, error)
	RevokeToken(ctx context.Context, idOrName string, at time.Time) error
	AppendAudit(ctx context.Context, e *store.AuditEntry) error
	ListAudit(ctx context.Context, limit int) ([]store.AuditEntry, error)
	CreateJoinCode(ctx context.Context, jc *store.JoinCode) error
	ListJoinCodes(ctx context.Context) ([]*store.JoinCode, error)
	RevokeJoinCode(ctx context.Context, id string, at time.Time) error
	ReleaseLabel(ctx context.Context, label string) error
}

Store is the persistent state the API needs; store.Store satisfies it.

type Token

type Token struct {
	ID         string     `json:"id"`
	Name       string     `json:"name"`
	Last4      string     `json:"last4"`
	Scopes     []string   `json:"scopes"`
	MaxTunnels int        `json:"max_tunnels"`
	CreatedAt  time.Time  `json:"created_at"`
	ExpiresAt  *time.Time `json:"expires_at,omitempty"`
	RevokedAt  *time.Time `json:"revoked_at,omitempty"`
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`
	// RemoteControl: operators may open tunnels on this token's client remotely.
	// CreatedBy is the id of the token whose join link made this one, "socket", or empty.
	CreatedBy     string `json:"created_by,omitempty"`
	RemoteControl bool   `json:"remote_control"`
}

Token is a token as the API shows it: never the secret or its hash.

type Tunnel

type Tunnel struct {
	ID      string `json:"id"`
	Client  string `json:"client"`
	Name    string `json:"name"`
	Kind    string `json:"kind"`
	URL     string `json:"url,omitempty"`
	Port    int    `json:"port,omitempty"`
	Private bool   `json:"private,omitempty"`
	Inspect bool   `json:"inspect,omitempty"` // HTTP: request and response bodies are stored for the inspector
}

Tunnel is a registered tunnel.

Jump to

Keyboard shortcuts

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