httpapi

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 40 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 httpapi is the HTTPS front end: router, middleware (request id, panic recovery, LAN guard, security headers), the JSON error model, the REST handlers and the embedded single-page app.

Index

Constants

View Source
const (
	CodeBadRequest          = protocol.CodeBadRequest
	CodeUnauthorized        = protocol.CodeUnauthorized
	CodeForbidden           = protocol.CodeForbidden
	CodeNotFound            = protocol.CodeNotFound
	CodeConflict            = protocol.CodeConflict
	CodeTooLarge            = protocol.CodeTooLarge
	CodeUnsupportedMedia    = protocol.CodeUnsupportedMedia
	CodeRateLimited         = protocol.CodeRateLimited
	CodeInsufficientStorage = protocol.CodeInsufficientStorage
	CodeUnavailable         = protocol.CodeUnavailable
	CodeInternal            = protocol.CodeInternal
)

Error codes of the REST error model (see docs/openapi.yaml).

View Source
const ContentSecurityPolicy = "default-src 'self'; script-src 'self'; style-src 'self'; " +
	"img-src 'self' blob: data:; media-src 'self' blob:; connect-src 'self'; worker-src 'self'; " +
	"frame-ancestors 'none'; base-uri 'none'; form-action 'self'"

ContentSecurityPolicy is sent on every HTTPS response (Locked Decision 2).

View Source
const MaxJSONBody = 1 << 20

MaxJSONBody is the largest request body a JSON endpoint accepts.

View Source
const PermissionsPolicy = "camera=(), microphone=(), geolocation=(), payment=(), usb=()"

PermissionsPolicy turns off powerful features the app never uses.

View Source
const RequestIDHeader = "X-Request-Id"

RequestIDHeader carries the per-request id back to the client.

View Source
const ResetAttemptsPerHour = 3

ResetAttemptsPerHour is how many reset attempts (right or wrong) one admin gets per hour.

Variables

This section is empty.

Functions

func New

func New(d Deps) http.Handler

New returns the HTTPS handler: request id -> recover -> LAN guard -> security headers -> router. API routes add authentication, the Origin check and the rate limits per route (see registerAuthRoutes).

func NewServer

func NewServer(h http.Handler, getCert func(*tls.ClientHelloInfo) (*tls.Certificate, error), logger *slog.Logger) *http.Server

NewServer returns the HTTPS server for h. Certificates come from getCert on every handshake, so a re-issued leaf is served without a restart. Serve it with srv.ServeTLS(ln, "", "").

func RequestID

func RequestID(ctx context.Context) string

RequestID returns the id the requestID middleware assigned, or "".

func SameOrigin

func SameOrigin(r *http.Request) bool

SameOrigin reports whether r carries an Origin (or Referer) that matches its Host. The WebSocket upgrade uses it too.

func WriteError

func WriteError(w http.ResponseWriter, status int, code, message string)

WriteError writes the error model as JSON with the given status. Error responses are never cached.

func WriteErrorDetails

func WriteErrorDetails(w http.ResponseWriter, status int, code, message string, details map[string]any)

WriteErrorDetails is WriteError with a details object.

func WriteFieldErrors

func WriteFieldErrors(w http.ResponseWriter, status int, code, message string, fields map[string]string)

WriteFieldErrors answers a rejected request with details.fields mapping each offending field to the reason (status 400 bad_request, or the given status/code for conflicts).

func WriteRateLimited

func WriteRateLimited(w http.ResponseWriter, retryAfter time.Duration)

WriteRateLimited answers 429 rate_limited with a Retry-After header.

Types

type AdminHost

type AdminHost interface {
	// Host reports the start time, open connections, URLs and certificate.
	Host() HostStatus
	// ReissueTLS re-issues the leaf certificate from the local CA
	// (tlsca.ErrBYO when the server uses its own certificate files).
	ReissueTLS() error
}

AdminHost gives the admin endpoints the process-level state and actions.

type Deps

type Deps struct {
	// Version is reported by /healthz.
	Version string
	// Logger receives panics and server errors; nil discards them.
	Logger *slog.Logger
	// AllowedCIDRs returns the extra source ranges admitted besides private
	// and loopback addresses (admin setting allowed_cidrs); nil means none.
	AllowedCIDRs func() []netip.Prefix
	// SPA serves the single-page app files; nil means webui.Handler().
	SPA http.Handler
	// Auth serves the status, login, invite, register, password-reset and
	// /me endpoints; nil leaves those routes out.
	Auth *auth.Service
	// Chat serves the users, channels, DMs, messages, reactions, pins and
	// bootstrap endpoints; nil leaves them out. It needs Auth.
	Chat *chat.Service
	// Files serves POST /files and GET /files/{id}/{name}; nil leaves them
	// out. It needs Auth.
	Files *files.Service
	// Search serves GET /search; nil leaves it out. It needs Auth.
	Search *search.Service
	// Push serves the /push endpoints (VAPID key, subscriptions); nil leaves
	// them out. It needs Auth.
	Push *push.Service
	// Apps serves the app endpoints (GET /apps/self, pairing, /admin/apps,
	// /admin/pairing-requests) and authenticates app bearer tokens on the
	// routes an app may call; nil leaves them out and bearer tokens are not
	// recognised. It needs Auth.
	Apps *apps.Service
	// Alerts serves the /alerts endpoints; nil leaves them out. It needs
	// Auth and Apps.
	Alerts *alerts.Service
	// Hooks serves POST /hooks/{token} and the /admin/webhooks endpoints; nil
	// leaves them out. It needs Auth.
	Hooks *hooks.Service
	// Endpoint says how clients reach this server (host, HTTPS port, CA
	// fingerprint); it fills the connection string of new app tokens and the
	// CA fingerprint of pairing requests. nil means the request host and no
	// fingerprint.
	Endpoint func() apps.Endpoint
	// Now is the clock of the message-post rate limit; nil means time.Now.
	Now func() time.Time
	// WS serves the realtime WebSocket endpoint GET /api/v1/ws
	// (internal/wsgateway). It is mounted behind the cookie authentication
	// middleware and checks the Origin itself; nil (or nil Auth) leaves the
	// route out.
	WS http.Handler
	// Reset serves the Danger-zone endpoints (reset preview, reset, backup
	// download); nil leaves them out.
	Reset Resetter
	// Admin supplies the process state and actions of the admin overview and
	// TLS endpoints; nil leaves /admin/tls out and the overview without them.
	Admin AdminHost
	// DB serves the audit log and the client-isolation hint of the admin API;
	// nil leaves /admin/audit and /admin/tls out.
	DB *store.DB
}

Deps are the collaborators of the HTTPS handler.

type ErrorBody

type ErrorBody = protocol.ErrorBody

ErrorBody is the JSON error envelope: {"error":{"code","message","details"}}.

type ErrorDetail

type ErrorDetail = protocol.Error

ErrorDetail is the inner object of ErrorBody.

type HostStatus

type HostStatus struct {
	StartedAt      time.Time
	Connections    int
	HTTPSURLs      []string
	OnboardingURLs []string
	TLS            tlsca.Status
}

HostStatus is the live state of the server process that only the composition root knows.

type ResetInput

type ResetInput struct {
	Actor        audit.Actor
	Confirm      string
	Password     string
	RotateCA     bool
	KeepSettings bool
}

ResetInput is a confirmed-looking reset request; the Resetter checks Confirm against the instance name and Password against the actor's account and audits a refusal.

type Resetter

type Resetter interface {
	ResetPreview(ctx context.Context) (protocol.ResetPreview, error)
	ClearContent(ctx context.Context, in ResetInput) (protocol.ContentCleared, error)
	FactoryReset(ctx context.Context, in ResetInput) (protocol.FactoryReset, error)
	// Backup streams an encrypted backup archive of the data directory.
	Backup(ctx context.Context, w io.Writer, passphrase string) error
}

Resetter runs the reset lifecycle of the server (the composition root implements it). A wrong confirmation or password is an error matching reset.ErrConfirm or reset.ErrPassword.

Jump to

Keyboard shortcuts

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