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
- func New(d Deps) http.Handler
- func NewServer(h http.Handler, getCert func(*tls.ClientHelloInfo) (*tls.Certificate, error), ...) *http.Server
- func RequestID(ctx context.Context) string
- func SameOrigin(r *http.Request) bool
- func WriteError(w http.ResponseWriter, status int, code, message string)
- func WriteErrorDetails(w http.ResponseWriter, status int, code, message string, ...)
- func WriteFieldErrors(w http.ResponseWriter, status int, code, message string, ...)
- func WriteRateLimited(w http.ResponseWriter, retryAfter time.Duration)
- type AdminHost
- type Deps
- type ErrorBody
- type ErrorDetail
- type HostStatus
- type ResetInput
- type Resetter
Constants ¶
const ( CodeBadRequest = protocol.CodeBadRequest CodeForbidden = protocol.CodeForbidden CodeNotFound = protocol.CodeNotFound CodeConflict = protocol.CodeConflict CodeTooLarge = protocol.CodeTooLarge CodeUnsupportedMedia = protocol.CodeUnsupportedMedia CodeRateLimited = protocol.CodeRateLimited CodeInsufficientStorage = protocol.CodeInsufficientStorage CodeInternal = protocol.CodeInternal )
Error codes of the REST error model (see docs/openapi.yaml).
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).
const MaxJSONBody = 1 << 20
MaxJSONBody is the largest request body a JSON endpoint accepts.
const PermissionsPolicy = "camera=(), microphone=(), geolocation=(), payment=(), usb=()"
PermissionsPolicy turns off powerful features the app never uses.
const RequestIDHeader = "X-Request-Id"
RequestIDHeader carries the per-request id back to the client.
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 ¶
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 SameOrigin ¶
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 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.
Source Files
¶
- errors.go
- handlers_admin.go
- handlers_admin_apps.go
- handlers_admin_reset.go
- handlers_admin_webhooks.go
- handlers_alerts.go
- handlers_apps.go
- handlers_auth.go
- handlers_bootstrap.go
- handlers_channels.go
- handlers_commands.go
- handlers_devices.go
- handlers_files.go
- handlers_me.go
- handlers_messages.go
- handlers_pairing.go
- handlers_pins.go
- handlers_push.go
- handlers_reactions.go
- handlers_search.go
- handlers_users.go
- mcp_mount.go
- middleware.go
- origin.go
- pagination.go
- routes.go
- server.go
- spa.go