pushleft
Deploy your first app
Manual contents
Handbook
HandbookPushleftArchitecture
Operate
Install the control planeYour own serversFleetOperations and alertsAuthenticationAccess gateDomains and DNSUsage and budgetsScheduled jobsAbuse controlsAI provider proxyCustomer mailErrors and performanceLogs and metricsRetentionObject storageContainer registryGit server
Develop
The .pl.yaml manifestOnboard with an AI agentThe pl up demoBuild executorSource ingestionAgent gatewayManaged databasesSecurity findingsTunnels and shellsDev workspacesPrivate hostnamesMesh coordinatorsDesign baseline
Runbooks
Control-plane host failoverControl-plane PostgreSQL failoverControl-plane PostgreSQL restoreCustom domains and certificatesGateway key compromiseIngress host failureNode busyNode disk fullNode drain and replacementNode lostRegistry outageHetzner Robot hostsSecret rotationSecurity incidentStaging fleet on ProxmoxStaging build cacheStuck deploymentVault/OpenBao backup and recovery
More
CI pipelines
Manual · docs/agent-gateway.md

Agent gateway

The agent gateway is how fleet nodes get work from the control plane. This page explains how a node proves its identity, leases jobs, receives secrets and downloads build sources, so you can operate and debug the gateway.

pushleft-agent-gateway is a separate HTTPS surface for agents only. It does not share the browser API’s authentication or listener. TLS client authentication is mandatory at handshake time, and there is no header-based fallback.

Identity

Each node proves who it is with a client certificate. The gateway:

  1. Validates the client chain against PUSHLEFT_AGENT_CLIENT_CA.
  2. Hashes the leaf certificate DER with SHA-256.
  3. Resolves that fingerprint to an active database record.

The database lookup gives immediate revocation, without waiting for certificate expiry. A certificate must be inside both its X.509 validity window and its control-plane validity window.

Fleet nodes are platform-owned (owner_org_id IS NULL) or customer-owned. A customer-owned node can lease only jobs for its owning organization. A platform node can lease only work that the placement controller assigned to it.

Locks. Authentication holds a shared certificate lock and a node NO KEY UPDATE lock through the handler transaction. Then it checks certificate validity again with a fresh post-wait snapshot. Revocation and node reassignment cannot commit between authorization and lease publication.

  • Heartbeats and completions also check current node ownership against the job’s organization.
  • The migrated database regression suite runs concurrent changes of ownership, status and certificates, and revocation that waits for the request to commit.
  • Fleet reassignment still needs the explicit identity-rotation and drain workflow (drain and replacement). Changing ownership metadata does not wipe a host.

Time limits. Gateway transactions require PostgreSQL 17 or newer. They use request-local limits:

LimitValue
Each lock wait1 second
Each statement3 seconds
Whole transaction10 seconds

A completion blocked by provider-held attachment locks rolls back promptly. It releases its authorization locks, so another heartbeat can proceed. Contention is retryable, and no partial result is committed. A real-database regression holds the provider lock and checks that an authenticated heartbeat still works after the bounded rollback.

Database role. The gateway needs a dedicated PostgreSQL service role with BYPASSRLS, because it works across organizations. Startup fails if the current role is neither a superuser nor BYPASSRLS. The browser API must use a different, non-owner, non-bypass role (database roles).

Lease protocol

A lease gives one node the exclusive right to run one job for a short time. The protocol:

  1. POST /v1/agent/lease updates bounded node capabilities and atomically leases one queued, node-targeted job with FOR UPDATE SKIP LOCKED.

  2. A random lease token and 45-second expiry fence every mutation.

  3. POST /v1/agent/jobs/{id}/heartbeat extends an unexpired lease. A single attempt cannot be extended past twelve hours (a long dataset load), or four hours for an open_session job.

    A build also sends its output so far to POST /v1/agent/jobs/{id}/output after each heartbeat. The body has lease_token, a batch id, from (the build’s line number of the first line), at most 200 lines, and skipped.

    • The gateway checks the lease like the source download.
    • It strips control characters and caps each line at 2,048 characters.
    • It appends one build_output deployment event per batch id. The agent resends a batch that was not accepted under the same id. A timed-out send that did commit is not appended twice.
    • Sending is best effort. An older gateway answers 404, and the result’s log tail still carries the end of the build.
  4. The agent cancels its local child process when it loses the lease or cannot renew safely. Docker child processes use kill-on-drop.

  5. POST /v1/agent/jobs/{id}/complete accepts one result for the current node, token, and attempt. Stale completion returns 409.

  6. Retryable failures return to the queue with bounded exponential backoff. Terminal results set completed_at.

Results are append-only and limited to 64 KiB. The gateway rejects recursively nested fields whose names suggest passwords, secrets, tokens, credentials or authorization data. Raw logs use the telemetry and log stream.

Credential revisions. Network jobs also bind the attachment’s credential revision.

  • A missing credential_revision means legacy revision 1. An explicit null or a malformed value is not accepted as revision 1.
  • Selection and post-wait lease publication both check the current revision.
  • A superseded heartbeat or completion returns 409. It inserts no result and does not change attachment evidence.
  • Superseded jobs are terminalized at the node’s next poll: queued ones, and leased ones whose lease expired. The lease gate never leases them again, so before 2026-11-04 an expired one with attempts left stayed leased. Exhausted or stale failures cannot erase newer health.

The revision check is a database publication fence. It does not prove that a remote Docker operation that was already dispatched has stopped. Automatic credential renewal stays disabled until agent-side restaging and quiescence are verified (gap).

Execution lanes

The agent runs five independent execution lanes, so slow work on one lane does not hold back the others. Four are serial; session runs up to eight jobs at once:

LaneSelects
networkOnly manage_network jobs.
durabilityLong data work on database files: manage_database jobs whose operation is a backup, restore drill, restore, import, upgrade, relocation, generation retirement or removal. The agent’s WAL sealing and spool catch-up run between them in the same lane.
namesOnly sync_environment_names jobs (private hostnames). A role whose start waits for another node’s role name never holds back that name’s update.
sessionOnly open_session jobs (developer access): tunnels and shells, up to eight at once per node, each renewing its own lease for up to four hours. No other lane selects them.
generalEverything else. A backup of up to six hours never holds back a deploy on that node, its database setup included.
  • The rule is one SQL function, job_lane (migrations 0095, 0096, 0129, 0130).
  • An agent from before the names lane asks for general without the names_lane capability. The gateway then gives it name sync in general, as before.
  • Agents from before it ask for lane: workload: every non-network job, as before. A node keeps its backups in that lane until its agent is upgraded.
  • Both expired-job cleanup and new lease selection respect the lane.
  • Network, durability, names and session polling refresh node liveness without overwriting the general lane’s capabilities. They do not run storage quota probes. A database command that waits on Docker does not stop recurring mesh checks.
  • Network work stays serial per agent, with the existing environment filesystem locks and generation fences.
  • Each executing job renews its own lease.
  • An omitted lane defaults to all for older clients. Unknown values are rejected.

Upgrade the gateway before you deploy an agent that asks for a new lane.

Completion and transport errors stay local to the attempt. The lane logs the failure and resumes polling. The unreported lease expires and retries under its existing token fencing. The error does not cancel another lane’s host operation.

One outer shutdown handler (SIGINT or SIGTERM, crates/pushleft-ops) cancels all lanes. This includes their in-flight child commands and their polling and backoff waits. Lane-local error recovery cannot swallow shutdown. A fatal malformed or misrouted lease response can still stop the agent.

The integration regression proves independent dispatch, reporting, failure isolation and process shutdown:

  1. It blocks a database Docker command behind an explicit test gate.
  2. It runs a network health attempt through the same authenticated agent, and checks that the failure result arrives while the database stays leased.
  3. It injects HTTP 500 during a second network completion. It checks that the database lane stays alive and completes after release.
  4. A second gated run checks that SIGINT exits promptly without releasing the database gate.

It does not prove successful real mesh health or fleet-scale throughput.

Brokered secrets

Nodes hold no Vault token. The gateway hands each node only the secrets its leased job needs. After a lease commits, and after validate and validate_secret_scope pass, the gateway adds wrapped_secrets to the response. Each entry is a reference to a single-use Vault wrapping token with a 5-minute TTL. The stored job never contains them.

JobSecret
manage_database ensure_instance, restoreAdmin password, created if absent
manage_database create_user, rotate_credentialPrincipal password
manage_network ensure_environment_gatewayThe pre-auth key, only under mesh/<this node>/

POST /v1/agent/secrets/backup-key with {"organization_id"} returns {"wrap_token"} for the organization’s backup key, created if absent. It works only while that organization has, on the node, a live database instance or volume, or a leased database or volume job. Otherwise the answer is 403.

Details: node secrets. Tests: secrets::tests and, against real PostgreSQL and the fake Vault, authorization_tests::brokered_secrets_reach_only_the_node_they_are_placed_on (npm run test:mesh-controller).

Session relay

The gateway relays developer access sessions (pl db connect, pl tunnel, pl exec). The agent side is GET /v1/agent/jobs/{id}/relay on this listener, with x-pushleft-lease-token. It is an HTTP/1.1 upgrade (Upgrade: pushleft-session) for the caller’s current open_session lease. A session that has ended gets 409. The pl side is a separate loopback listener (PUSHLEFT_SESSION_RELAY_BIND) behind the control-plane TLS proxy, with the session’s one-time token. It takes the same upgrade from pl. Since 2026-11-06 it also takes a WebSocket from the console’s shell, with the token as the second subprotocol (Sec-WebSocket-Protocol: pushleft-session, pls_…). The gateway pairs the two in memory and copies bytes. Where the relay runs explains the choice.

Volume migration archives

The gateway moves sealed application volume archives between hosts.

  • Store. PUT /v1/agent/jobs/{id}/volume stores the sealed volume archive. It accepts the archive only for the caller’s current targeted manage_volume export lease, with the x-pushleft-lease-token, x-pushleft-volume-sha256 and x-pushleft-volume-backup-id headers. The body must match the digest and be at most twice the volume size. It answers 201.
  • Fetch. POST on the same path with {"lease_token"} returns that archive only for an import lease, at the backup ID and digest its task names.
  • Key. The key comes from the lease’s migration ID (volumes/<org>/<migration>/<backup id>.tar.sealed in the backups blob use), never from the request.
  • Any authorization failure, or a gateway without a backups blob store, is 404. The gateway never opens the sealed bytes.
  • Usage. Lease capabilities may carry volume_usage ([{project, used_bytes}], at most 500). This updates the usage of this node’s volumes. The gateway ignores a malformed report.

Details: migration between hosts.

Build-source delivery

Build nodes get short-lived registry tokens and the verified source archive from the gateway.

Registry tokens. Nodes hold no registry login (H1). POST /v1/agent/registry/token with {"repository": "<host>/<name>"} returns {"token","expires_in","actions"}. token is a 15-minute ES256 registry token with:

  • pull,push, while the node holds a live build_image lease for exactly that repository.
  • pull, while an application instance of a release from that repository is placed on the node.
  • Otherwise 403. The answer is 404 registry_tokens_disabled when the gateway has no signing key.

The scheduler’s delete tokens come from the separate realm listener. Details: registry tokens. Tests: registry::tests and build::tests::registry_tokens_follow_build_leases_and_placement.

Source. POST /v1/agent/jobs/{id}/source with {"lease_token": "<token>"} returns the exact verified source archive (source ingestion) for the caller’s current targeted build_image lease, and nothing else. Only the mandatory-mTLS listener serves it.

  • 200: Content-Type: application/vnd.pushleft.source+tar.zstd, exact Content-Length, X-Pushleft-Source-Sha256, X-Pushleft-Source-Snapshot and X-Pushleft-Artifact-Id; the body is the archive bytes.
  • 404: any authorization failure. It covers another node, another organization’s node, a non-build_image job and a non-build-pool node. It covers a node without oci_build/isolated_build capabilities (and vm_isolated_build unless PUSHLEFT_REQUIRE_VM_ISOLATED_BUILD=false). It also covers an inactive/torn-down deployment, or any claim/snapshot/artifact/plan provenance mismatch. The answer does not disclose whether another caller’s job exists.
  • 409: the job is targeted to this node but the lease token, leased status or wall-clock expiry (clock_timestamp()) is no longer current.
  • 503: source delivery is not configured (PUSHLEFT_SOURCE_ROOT unset; the gateway logs that delivery is disabled at startup) or all download slots are busy.
  • 401: an unknown/revoked certificate or revoked node, as on every other gateway route.
  • 500: the stored object is missing, not a private regular file, truncated, or its bytes differ from the verified digest. No bytes are returned.

The download runs in three steps:

  1. Authorization runs in a bounded transaction (certificate, node, job and deployment locks in the usual order). It captures the node, object key, digest, length, snapshot and artifact IDs, and commits.
  2. Blocking work reads and verifies the object outside every database lock (SourceStore::read_verified: store key grammar only, no symlinks or hard links, exact length and SHA-256).
  3. A second bounded transaction repeats the full authorization. Any difference withholds the bytes.

PUSHLEFT_GATEWAY_SOURCE_SLOTS (default 2, 1 to 64) bounds concurrent downloads per gateway process. The blocking read holds a slot even if the request is cancelled. The response body holds it until it is sent or the connection drops. Buffered archives stay bounded at slots x 2 GiB, so size the gateway’s memory for it.

With the local store, the gateway reads the same private tree the API writes. Its service identity must be able to read that directory tree (0700 directories). The final reauthorization narrows the window between the check and the agent receiving the bytes, but does not close it. Heartbeat and publication fence a lease lost during transmission. This route does not.

Verified behavior

scripts/agent-gateway-e2e.sh creates an ephemeral CA, a server certificate, known and unknown client certificates, and a clean PostgreSQL database. It checks that:

  • Clients without a certificate fail the TLS handshake.
  • A CA-valid but unknown certificate receives 401.
  • Only the targeted node can lease the job.
  • Wrong or stale lease tokens receive 409.
  • Heartbeats fence execution, and completion is idempotent.
  • Secret-shaped results are rejected.
  • The real agent leases and runs a typed database health task.
  • Result rows are immutable.
  • Database certificate revocation takes effect on the next request.

Fleet describes enrollment (POST /v1/enroll on the separate server-auth listener), renewal (POST /v1/agent/certificate/renew) and rotation completion. Every agent route on this listener still requires a client certificate. The gateway refuses retired nodes like revoked ones. Until placement assigns jobs.target_node_id, queued agent work is invisible to every node.

Rendered from the repository at build time. Edit docs/agent-gateway.md to change it.