API transport, realtime connections, and webhooks
Arcane's API transport layer turns HTTP requests, live connection requests, and external webhook calls into authorized application operations. It provides typed REST contracts, live feeds for the web app, remote-environment routing, and a safe path from a public webhook token to a background action. See also API services and request lifecycle.
Transport boundary
The API boundary groups the application's external traffic under /api. Shared middleware applies request policy before traffic reaches domain handlers. Huma owns the typed REST contract and OpenAPI document. Echo owns WebSocket, server-sent event, streaming, and feature-gated routes that need connection behavior outside the main REST contract.
The boundary separates three traffic classes:
| Traffic | Purpose | Main owner |
|---|---|---|
| REST | Read and change application resources | Huma domain handlers and feature-gated Echo handlers |
| Realtime | Send logs, stats, diagnostics, and client feed updates | Echo WebSocket and server-sent event handlers |
| External triggers | Start a stored application action from a URL token | Public webhook trigger and webhook service |
The same environment-scoped path can address the local Docker environment or a remote environment. The environment route checks the caller's identity and permission before it forwards HTTP or WebSocket traffic. Manager-owned paths stay on the manager instead of being sent to an environment.
References: backend/…/api.go• L286-348 backend/…/api.go• L403-446 backend/…/router_bootstrap.go• L213-321 backend/…/environment_middleware.go• L68-190
REST request handling
Huma operations define the input, output, security, permission, and API description for resource requests. API setup attaches Huma to the Echo API group, installs authentication and activity middleware, registers normalization before the domain routes, and then mounts the domain modules. This keeps transport rules close to the service that owns each operation.
The API also builds an OpenAPI contract from the registered operations. The Scalar page reads /api/openapi.json and presents it at /api/docs. Live routes remain outside that document because their connection behavior is not a normal request-and-response exchange.
Request authentication and authorization
Authentication identifies the caller. Authorization maps that identity to permissions for the target environment. The API supports bearer tokens, session cookies, API keys, environment access tokens, and agent tokens for the edge-agent path.
For a remote environment, the manager resolves the environment and checks the operation permission before it forwards the request. The remote agent's infrastructure credential does not replace the manager's user-level decision. Unknown permission mappings fail closed, so a new environment-scoped operation must declare its permission before it can be proxied.
References: backend/…/api.go• L310-343 backend/…/huma_middleware.go• L179-225 backend/…/huma_middleware.go• L258-315 backend/…/environment_middleware.go• L127-190 backend/…/environment_middleware.go• L208-275
JSON serialization and input normalization
The API uses one JSON wire format for Arcane and Docker data. Its serializer keeps duration values in the numeric form expected by existing clients. It also uses strict JSON decoding so malformed bodies, duplicate field names, and invalid encoding do not enter application code.
JSON request bodies with normalization rules are normalized before Huma validates them. This lets clients use the accepted form of values such as trimmed or Unicode-normalized text while preserving identity fields that must pass through unchanged. The boundary reports syntax and body-limit errors as 400 or 413, request timeouts as 408, and valid JSON that fails Huma validation as 422.
Schema names include their source type family when needed. This prevents domain and Docker types with the same short name from colliding in the OpenAPI document.
References: backend/…/json_serializer.go• L11-29 backend/…/normalization.go• L21-66 backend/…/normalization.go• L106-154 backend/…/api.go• L109-136 backend/…/api.go• L330-343
Feature-gated authentication routes
Buildable routes extend the API only when the related feature is enabled. The auto-login route checks the feature state and required password, uses the normal authentication service, and returns the same token and browser-session result as an ordinary login. It does not bypass a required multi-factor step.
References: backend/…/buildables.go• L21-26 backend/…/buildables.go• L47-105
Realtime connections
Realtime transport keeps the client current without repeated REST polling. WebSockets support resource streams and interactive terminal sessions. The /api/stream endpoint uses Server-Sent Events (SSE) to carry several dashboard feeds over one server-to-client connection. Diagnostics WebSockets provide snapshots, commands, and server log flow.
The following diagram shows how a live request passes through policy and reaches a local producer or a remote environment before updates return to the client.
flowchart LR
Client[Client] --> Router[API router]
Router --> Policy[Origin and permission checks]
Policy --> Local[Local producer]
Policy --> Proxy[Remote HTTP or WebSocket proxy]
Local --> Hub[Stream or WebSocket hub]
Proxy --> Remote[Remote environment producer]
Remote --> Hub
Hub --> Client
WebSocket connection policy
Environment WebSockets are grouped under /api/environments/{id}/ws. The shared connection layer checks the request origin before upgrade, records the connection and resource in WebSocket metrics, and uses ping and read loops to detect peers that stop responding. These controls apply to logs, stats, terminals, and remote upgrades.
Each proxied route carries its permission with its route definition. This gives local registration and remote permission matching one source of truth. WebSocket routes do not enter the Huma OpenAPI permission scan, so this explicit mapping is part of the remote authorization contract.
References: backend/…/handler.go• L33-105 backend/…/handler.go• L119-153 backend/…/proxy_permissions.go• L11-44
Resource streams
Resource WebSockets expose project logs, container logs, swarm service logs, container stats, and system stats. Each stream has a producer suited to its data. Shared hubs let clients that request the same resource and stream options receive one upstream feed rather than create one feed per browser.
| Connection type | Client view | Producer model |
|---|---|---|
| Project, container, and service logs | Text or structured log output | Shared stream keyed by resource and options |
| Container stats | Container resource samples | Shared per-container hub with idle cleanup |
| System stats | Periodic host resource samples | Shared sampler using the fastest active interval |
| Container terminal | Bidirectional command input and output | One interactive command session |
| Diagnostics | Snapshots, commands, and server logs | Snapshot producer or backlog plus live broadcaster |
Log clients can request text or JSON output and can ask for batched JSON messages. Slow clients are removed from a hub so one blocked browser does not stop other subscribers. A failed stats or log producer sends a client-visible error when possible and is removed so a later connection can build a fresh producer.
References: backend/…/log_streams.go• L25-167 backend/…/log_streams.go• L280-369 backend/…/container_stats.go• L23-60 backend/…/container_stats.go• L88-167 backend/…/system_stats.go• L64-213
Interactive terminal sessions
The container terminal connects WebSocket frames to a container command. Client frames become command input. Command output becomes binary WebSocket messages. A concurrent reader services peer control frames so keep-alive handling continues while output is sent.
The session ends with a protocol close status that tells the client whether the shell exited, the peer closed the connection, the server shut down, or an internal error stopped the session. Cleanup closes the command session even when the request context is already canceled.
References: backend/…/exec.go• L26-60 backend/…/exec.go• L63-105 backend/…/exec.go• L113-181
Diagnostics connections
Diagnostics REST returns collected actor diagnostics for an environment. Diagnostics WebSockets serve runtime snapshots, actor snapshots, and recent server logs. The diagnostics stream sends an initial snapshot and later snapshots at a fixed interval. It can also answer refresh, leak-scan, dump, and profile commands, with profile data limited to global administrators.
The server-log stream subscribes before it replays its recent backlog. This ordering prevents a new log entry from being lost between the backlog read and the live subscription.
References: backend/…/diagnostics.go• L16-50 backend/…/diagnostics.go• L55-82 backend/…/diagnostics.go• L84-189 backend/…/diagnostics.go• L191-245
Multiplexed client stream
The /api/stream endpoint is one SSE connection for the environments, dashboard, activities, events, and version channels. The client names the channels in the request. Each channel keeps its own producer and permission check, then the handler wraps the channel event in a shared envelope.
A caller can receive only the channels and environment data allowed by its permission set. A request with no permitted channel can stay connected for heartbeats without receiving protected data. Local and remote dashboard or activity producers remain separate so the stream can combine both sources without changing their domain-specific event types.
References: backend/…/stream.go• L43-91 backend/…/stream.go• L94-137 backend/…/stream.go• L139-223
Remote WebSocket proxy
A WebSocket request for a remote environment follows the same permission decision as a local request. The manager then uses an active edge tunnel or a direct remote API connection. The bridge opens the remote connection with the forwarded access credential and copies frames in both directions.
The remote bridge uses the same origin protection as local WebSockets. A valid session cookie therefore does not let an unrelated page open a remote terminal or log stream.
References: backend/…/environment_middleware.go• L170-190 backend/…/environment_middleware.go• L381-418 backend/…/environment_middleware.go• L589-603 backend/…/proxy.go• L14-97 backend/…/proxy_permissions.go• L21-44
Webhook trigger path
A webhook is a stored external trigger for one known application action. Authenticated users manage webhooks within an environment. External systems call a public route with the webhook token as the only credential. The route validates and accepts the trigger quickly, while the target action runs in the background and reports its result through the event log.
The trigger path follows this sequence:
- An external caller sends
POST /api/webhooks/trigger/{token}. - Route middleware applies token-aware rate limits. Known tokens get separate token budgets. Other values share a source-IP budget.
- The webhook service narrows the lookup by token prefix, verifies the full token hash, checks that the webhook is enabled, and resolves the stored target and action.
- The service records the accepted trigger time and starts work without the request cancellation.
- The action runs against the local service or becomes an environment-scoped request for a remote environment.
- The service writes a success or error event after the action completes. The caller keeps the earlier
202 Acceptedresult.
The following diagram shows the separation between fast request acknowledgement and later application work.
sequenceDiagram
participant Source as External source
participant Route as Public trigger route
participant Service as Webhook service
participant Target as Local service or remote environment
participant Events as Event log
Source->>Route: POST token URL
Route->>Service: Validate token and enabled state
Service-->>Route: Accepted
Route-->>Source: 202 Accepted
Service->>Target: Run configured action
Target-->>Service: Result or error
Service->>Events: Record trigger outcome
Webhook management
Webhook management is an authenticated, environment-scoped REST surface. Clients can list summaries, create a webhook, enable or disable it, and delete it. The raw token appears only in the create response. List responses show a short prefix for recognition but never expose the secret.
Webhook records support four target families:
| Target | Action scope |
|---|---|
| Container | Update, start, stop, restart, or redeploy |
| Project | Update services, bring up, bring down, restart, or redeploy |
| Updater | Run the environment-wide updater |
| GitOps | Run a GitOps sync |
Creation normalizes the record, validates the target and action pair, and supplies a default action when the caller omits one. Container, project, and GitOps targets need a target ID. The updater acts on the whole environment and does not need one. The service also accepts the project deploy name as an alias for its up action.
References: backend/…/module.go• L15-86 backend/…/handler.go• L40-101 backend/…/handler.go• L104-147 backend/…/service.go• L173-224 backend/…/service.go• L234-309
Webhook token identity
The service creates a random token and returns the raw value only once. It stores a SHA-256 hash and a short lookup prefix instead of the raw secret. At startup it loads token hashes into an in-memory index so rate-limit admission can distinguish known tokens from random probes without a database query. A failed reload does not discard the existing index. Deletion removes the token from that index. A disabled token remains known for rate limiting but cannot trigger work.
The full trigger check still uses the database. It finds candidates by prefix, compares the full token hash, and then checks the enabled state. This keeps the public admission path fast while preserving the secret boundary in storage and list responses.
References: backend/…/service.go• L39-45 backend/…/service.go• L110-170 backend/…/service.go• L445-466 backend/…/service.go• L521-561 backend/…/service_test.go• L134-162 backend/…/service_test.go• L202-237
Webhook action routing
The webhook service chooses local execution or remote forwarding from the webhook environment. Local actions call the container, project, updater, or GitOps service. Remote actions map to the same operation family on the remote environment through the environment proxy.
Container targets can keep both a target ID and a stable reference. Local creation can resolve the reference early. Remote targets keep the reference for trigger-time resolution in the remote environment. This avoids looking up a remote container against the manager's Docker daemon.
Accepted actions run without the caller's request cancellation and remain tracked until they finish. The service records failures as error events and drains accepted actions during shutdown so an earlier 202 Accepted response does not promise work that shutdown silently drops.
References: backend/…/service.go• L521-585 backend/…/service.go• L587-677 backend/…/service.go• L680-775 backend/…/service.go• L777-832 backend/…/service_test.go• L687-716 backend/…/service_test.go• L730-798
Change checklist
When these files or sections are changed, remember to consider these:
- A new Huma operation must carry the correct security and permission metadata so local handling and remote proxy authorization agree.
- A new proxied WebSocket route must stay in the shared route-permission mapping because WebSocket routes are outside the Huma OpenAPI permission scan.
- A change to a stream event or JSON shape must keep the shared type, SSE or WebSocket framing, and client-facing serialization mode aligned.
- A change to WebSocket close handling must keep protocol status and reason values valid and useful to the client.
- A change to system-stat sampling must preserve the fastest active subscriber interval and the sampler's idle shutdown.
- A change to webhook target or action names must update validation, default actions, local execution, and remote request mapping together.
- A change to webhook token handling must keep creation, stored hashes and prefixes, startup loading, rate-limit admission, reload failure behavior, and deletion state aligned.
- A change to local or remote container references must preserve their different lookup timing.
- A change to the public webhook trigger path must preserve its token-only authentication, CSRF exception, and route-specific rate limit.
- A change to accepted webhook work must keep event outcomes and shutdown draining aligned with the
202 Acceptedcontract.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| An environment-scoped route has no permission metadata | Remote access is denied by default or can drift from local authorization | Register the required permission with the Huma operation or shared WebSocket route mapping |
| A WebSocket origin is not allowed | The upgrade is rejected before a stream or terminal starts | Use the configured origin validator for local and proxied upgrades |
| A slow WebSocket client fills its queue | The hub removes that client to protect other subscribers | Use bounded hub queues and slow-client removal |
| A stats producer fails while its hub remains cached | Clients keep an open socket that produces no new samples | Send an error frame, remove the dead hub, and allow a later connection to rebuild it |
| A system-stats subscriber asks for a faster interval but the sampler does not rearm | Fast clients read stale snapshots | Wake and rearm the shared sampler when the effective interval changes |
| A terminal input or output stream fails | The client sees an internal-error close and the command session must stop | Propagate the cause, close the session, and keep the close reason within the protocol limit |
| A malformed or duplicate JSON body reaches the serializer | The request is rejected as a bad request | Use strict JSON decoding at the API boundary |
| A normalized body exceeds its Huma limit | Application code must not receive the body | Apply the operation body limit while reading for normalization |
| A token-index reload fails and replaces the valid index | Known tokens lose their separate admission budget until the next successful load | Keep the prior index when loading fails and retry the load |
| A webhook token is malformed, unknown, or disabled | No application action starts | Use prefix lookup, full hash validation, and enabled-state checks |
| A webhook target or action is invalid | The webhook is rejected before accepted work starts | Validate target/action pairs and apply target-specific defaults |
| The raw webhook token is lost after creation | A later trigger cannot authenticate | Show the raw token only at creation and store only its hash |
| A webhook action fails after acceptance | The caller still sees accepted work, but the target operation does not complete | Record an error event and log the background failure |
| Accepted webhook work reaches shutdown | A caller could be told that work was accepted and then lose it | Drain the tracked webhook actions during shutdown |
Key files
| File | Why to read it |
|---|---|
| backend/…/api.go | Shows Huma setup, security schemes, JSON formats, schema naming, OpenAPI docs, and domain route composition. |
| backend/…/huma_middleware.go | Explains how request credentials become an effective permission set. |
| backend/…/environment_middleware.go | Explains local-versus-remote routing and authorization before forwarding. |
| backend/…/json_serializer.go | Defines the JSON request and response boundary. |
| backend/…/normalization.go | Defines the pre-validation normalization boundary and body error behavior. |
| backend/…/stream.go | Shows the multiplexed SSE feed and per-channel permission filtering. |
| backend/…/handler.go | Defines shared WebSocket setup, origin checks, metrics, and keep-alive behavior. |
| backend/…/proxy_permissions.go | Couples WebSocket route registration to remote permission matching. |
| backend/…/log_streams.go | Shows the shared log-stream lifecycle and client sharing model. |
| backend/…/exec.go | Shows the interactive terminal lifecycle and close outcomes. |
| backend/…/system_stats.go | Shows shared system-stat sampling and subscriber timing. |
| backend/…/diagnostics.go | Shows diagnostics snapshots, commands, and server-log streaming. |
| backend/…/webhooks_trigger.go | Defines the public token-based trigger response. |
| backend/…/module.go | Shows webhook dependency wiring and authenticated route registration. |
| backend/…/handler.go | Defines the authenticated webhook management contract. |
| backend/…/service.go | Defines token handling, validation, action routing, background work, and event outcomes. |
| backend/…/service_test.go | Shows the guarantees for token identity, environment scope, action validation, acceptance, and remote request mapping. |
| types/…/webhook.go | Defines the shared webhook request and response shapes. |