Skip to content

Latest commit

 

History

History
1130 lines (929 loc) · 74.1 KB

http-reference.md

File metadata and controls

1130 lines (929 loc) · 74.1 KB

HTTP API Reference

The default process policy rejects POST /ssh/sessions and POST /proxmox/console/sessions with a fixed HTTP 403 before authentication, body parsing, or effectful dependencies. The documented successful interactive contracts require explicit PROXBOX_EXECUTION_MODE=legacy and their existing authentication. Authenticated GET /execution-policy reports only local scoped boundary readiness and always returns aggregate_ready=false. See the interactive policy contract.

This page summarizes the HTTP endpoints exposed by proxbox-api.

For full request and response schemas, use the runtime OpenAPI at /docs.

Root and Utilities

  • GET / - Service metadata and links.
  • GET /version - Backend service version for external cache invalidation.
  • GET /cache - Inspect the in-memory cache snapshot.
  • GET /clear-cache - Clear in-memory NetBox GET and application caches.
  • GET /cache/metrics - JSON snapshot of cache, reconciliation, and aggregate auth-lockout metrics, including failure-row count and in-flight/orphan reservation gauges.
  • GET /cache/metrics/prometheus - Prometheus text-format exposition of the same label-free metric families for scrape jobs.

Authentication (/auth)

All requests except bootstrap endpoints require the X-Proxbox-API-Key header. See Authentication for the full bootstrap flow and key management guide.

  • GET /auth/bootstrap-status - Check whether first-time key registration is still needed. Auth-exempt. needs_bootstrap is false once the durable bootstrap claim exists or any key row (active or inactive) exists.
  • POST /auth/register-key - Register the first API key. Auth-exempt; the durable singleton bootstrap claim and the bcrypt hash are committed in one transaction, so bootstrap can be consumed exactly once per database. Any later call — including after every key is deleted or deactivated — returns 409 Conflict.
  • POST /auth/keys - Create a new API key. Returns the raw key value once; store it securely. Returns 409 (active_api_key_limit_reached) if activation would exceed PROXBOX_AUTH_MAX_ACTIVE_KEYS.
  • GET /auth/keys - List all API keys. Key values are redacted (only metadata is returned).
  • DELETE /auth/keys/{key_id} - Delete an API key by ID. Refuses to delete the final active key with 409 (last_active_api_key_required); create and verify a replacement first.
  • POST /auth/keys/{key_id}/activate - Re-activate a previously deactivated key. Returns 409 (active_api_key_limit_reached) if activation would exceed the configured cap.
  • POST /auth/keys/{key_id}/deactivate - Deactivate an active key without deleting it. Refuses to deactivate the final active key with 409 (last_active_api_key_required).

Admin

  • GET /admin/ - HTML admin dashboard for the configured NetBox endpoint records. This route is excluded from OpenAPI.
  • GET /admin/logs - In-memory backend log buffer with optional filters for level, limit, offset, since, and operation_id.
  • GET /admin/logs/stream - SSE real-time log stream. Supports query parameters level, errors_only, operation_id, and newer_than_id.

Service Route Groups

PBS, PDM, Ceph, intent, SSH, and the broader cloud management route groups are documented in Service Routes. That page also explains PROXBOX_FEATURES sidecar-only mounting and the write gates used by cloud and intent routes. Ceph v2 mutations additionally require the durable, two-person, single-use flow in Ceph v2 Write Approval and Recovery, including both default-off execution flags, a stable endpoint configuration revision, exact operation-node and typed-payload binding, owner-bound leases, provider-global unique node-consistent UPIDs, repeated-cancellation-safe durable checkpoints, and unknown-outcome recovery. netbox-ceph supplies the canonical proxbox-api endpoint ID resolved from its plugin endpoint; it never substitutes the plugin primary key. Dashboard and external providers are read/plan/reconcile-only until durable write authority exists.

Cloud Image Pipeline (/cloud/templates/images)

Read-only preflight

POST /cloud/templates/images/preflight accepts the v1 request fields contract_version ("1.0"), endpoint_id, target_node, vmid, image_storage, vm_storage, and the additive provider, snippets_required, snippets_storage, and recipe_digest fields. The provider is the sole authority for snippet readiness: release/source providers require snippets and proxmox_iso does not. snippets_required remains only as a deprecated v1 compatibility assertion and a disagreeing value is rejected. Older v1 callers that omit the additive fields retain provider="release_image" readiness behavior, but only a request carrying the server-rendered recipe_digest can receive an executable signed plan.

The endpoint resolves the exact enabled persisted endpoint and requires exactly one matching database-backed Proxmox session. It never falls back to the first configured session. It then performs only read calls for node status, node storage, authoritative GET /cluster/nextid?vmid=..., and supplemental cluster VM resources. Consequently, preflight works when allow_writes=false; the response's writes_enabled field is informational and no Proxmox or database mutation occurs.

The v1 response contains ready, capabilities, findings, and the submitted recipe_digest. When readiness passes and a digest was supplied, it also contains plan_id, plan_digest, plan_token, and expires_at. The signed token expires after five minutes and binds endpoint configuration, node, provider, all storage roles, VMID, and the exact rendered recipe. Issuing it does not mutate the database; execution consumes it once into the durable operation journal. Capability status is passed, failed, or unsupported. Every finding has exactly code, severity, target, and message; upstream exceptions and endpoint credentials are not returned. Malformed collection payloads fail closed as unsupported, and storage readiness passes only when both enabled and active are explicitly healthy. Checks cover:

  • the exact endpoint session and online target node;
  • images configured on VM storage;
  • iso configured on image storage only for provider="proxmox_iso"; release and source builds use a private /var/tmp staging directory and do not claim an image-storage capability;
  • snippets configured on snippet storage when the provider requires it; and
  • VMID availability from the authoritative cluster/nextid?vmid= probe. The resource enumeration can identify a visible collision but can never turn a denied or malformed authoritative result into a pass.

Proxmox storage configuration does not define import as a content type. The pipeline passes content=import only to the separate download-url POST. Preflight therefore validates the actual configured images capability and does not require an import entry.

Build response privacy

The executable sequence is intentionally three-step:

  1. POST /cloud/templates/images with execute=false returns the exact opaque recipe_digest: a domain-separated HMAC of the rendered recipe, never a raw script hash (and no sensitive material unless the separately protected preview was requested).
  2. POST /cloud/templates/images/preflight with that digest returns a signed plan only when every read-only capability passes.
  3. POST /cloud/templates/images with execute=true and preflight_plan_token=<plan_token> revalidates the signature, expiry, separately keyed endpoint configuration binding, and recipe; reruns the exact preflight; authoritatively refreshes and revalidates endpoint/SSH authority; then atomically acquires the one-time endpoint_id:vmid blocker.

Reusing a plan returns preflight_plan_already_consumed; an active target lease returns build_target_leased; drift and expiry return fixed preflight_plan_mismatch and preflight_plan_expired details. A target held by recovery, cancellation, unknown state, or an expired execution lease returns build_target_recovery_required and remains blocked; this API exposes no destructive reconciliation or automatic release.

POST /cloud/templates/images returns build-response contract v2. Default and executed responses omit image/source URLs, generated cloud-init, first-boot and build scripts, command lists, stdout, and stderr. Execution exposes only fixed typed diagnostics, the exit code, and bounded output byte/line counts. Unexpected execution or direct Proxmox SDK failures are normalized without returning or logging raw exception text. Direct SDK failures return a fixed 502 detail with code proxmox_build_failed; cleanup failures cannot replace an otherwise valid response.

Raw rendered material can be returned only for a non-executable preview by sending both execute=false and include_sensitive_preview=true. It appears under sensitive_preview, is explicitly marked sensitive, and may contain credentials, signed URLs, keys, or cloud-init secrets. Do not log or persist it. Validation rejects sensitive preview when execute=true or when execute is omitted, so normal execution can never return it.

Executable pipeline requests derive SSH authority exclusively from the selected persisted ProxmoxEndpoint. The endpoint must be enabled, have both allow_writes=true and the separate allow_packer_template_builds=true capability, use access_methods="api_ssh", and have a complete binding: ssh_target_node, ssh_host, ssh_username, ssh_port, ssh_identity_file, and ssh_known_host_fingerprint. The identity path must resolve under PROXBOX_SSH_KEY_DIR; the file must be a root/service-owned regular non-symlink with no group/world permissions. The service opens it with O_NOFOLLOW, verifies the descriptor with fstat, and gives OpenSSH the inherited /proc/self/fd/<fd> path so a concurrent pathname replacement cannot change the key. Legacy request fields ssh_host, ssh_user, ssh_port, ssh_identity_file, and ssh_known_host_fingerprint are assertions only: omission uses the persisted binding and any supplied mismatch returns 409 before a subprocess starts. The route scans the server key, verifies the persisted SHA-256 fingerprint, and passes the exact verified key to OpenSSH with strict host checking. The SSH process uses absolute client binaries, -F none, and explicit ProxyCommand=none, ProxyJump=none, and CanonicalizeHostname=no options, so ambient user/system configuration cannot redirect the connection.

The gate order is stable: broad allow_writes, narrow allow_packer_template_builds, then SSH transport. A missing or revoked narrow capability returns HTTP 403 with reason="packer_template_builds_disabled_for_endpoint" before any SDK write or SSH subprocess. After host-key pinning, the execution boundary rechecks enabled, broad, narrow, and the signed endpoint digest immediately before spawning SSH; a denial fails the consumed operation lease durably. Direct Proxmox API template-image builds require the same two write capabilities, resolve enabled authority before opening a session, and compare the initial endpoint digest before download/import, VM creation, and template conversion. Read-only planning and preflight do not require the narrow capability.

The signed endpoint-configuration binding includes the narrow capability. Pipeline execution refreshes and rechecks broad then narrow after preflight and before leasing, then revalidates enabled/broad/narrow plus the signed digest after host-key pinning immediately before SSH. Direct SDK execution resolves enabled authority before session creation and refreshes both gates plus the original endpoint digest before image download/import, VM creation, and template conversion.

Execution runs inside a unique server-generated systemd-run unit through asyncio subprocess APIs. Stdout and stderr are continuously drained into byte/line counters and never accumulated, returned, logged, or persisted. A timeout, request cancellation, or operator POST /cloud/templates/images/operations/{operation_id}/cancel stops the fixed unit. Mandatory local/remote cleanup, journal persistence, and session close continue through repeated cancellation. Cancel and completion journal transitions use compare-and-swap ordering so a stale request cannot overwrite the winner. GET /cloud/templates/images/operations/{operation_id} returns the secret-free durable journal state. The service marks an operation completed only after a final Proxmox API read verifies the expected template or ISO-backed installer VM. Otherwise it preserves all possible partial artifacts and records recovery_required; it never performs cleanup deletion.

Consumer rollout hold

The fixture at tests/fixtures/netbox_packer_preflight_v1.json is owned by proxbox-api. It exercises a consumer-shaped parser maintained in this producer repository, so it records compatibility intent only; it is not downstream conformance evidence. Operators must leave PROXBOX_ENABLE_CLOUD_IMAGE_EXECUTION unset or false until a compatible netbox-packer release with endpoint-bound authorization is deployed and validated against the released proxbox-api contract. Planning and GET-only preflight remain available while execution fails closed. After rollout, remote execution still requires both endpoint write gates.

Rendered user-data, first-boot, metadata, and authorized-key files are base64-encoded into fixed write commands, so caller content cannot terminate a shell delimiter. Snippet and ISO paths are resolved from their exact storage volume IDs with pvesm path; custom snippets_dir mappings are rejected. source_build_command accepts only the typed pfsense_memstickserial and opnsense_dvd assertions. The catalog selects fixed root-owned wrappers under /usr/local/libexec/proxbox, canonical source roots under /opt/proxbox/image-sources, and fixed root-contained artifacts. Caller source_tree_path and source_artifact_path values are compatibility assertions and any mismatch is rejected. The script verifies canonical paths, root ownership, and non-group/world-writable modes before use. Release, source, and ISO providers create randomized mode-0700 staging with mktemp; no predictable caller-derived staging path is used.

Durable operation state

CloudImageBuildOperation stores plan/recipe/config digests, endpoint, node, VMID, provider, lease and timestamps, bounded counters, cancellation result, verification state, and a fixed error code. It deliberately does not store the rendered script, URL, cloud-init, SSH material, stdout, or stderr. An expired lease is converted to recovery_required while retaining the unique target blocker. No new owner can acquire that endpoint/VMID until a future explicit, non-destructive reconciliation workflow exists, preserving possible remote and partial state.

vm_storage is the single VM-disk storage authority. The legacy input name storage is accepted during the 0.0.21.x window as an alias, is normalized to vm_storage, and is rejected when both names disagree. It is not emitted in OpenAPI or responses. Pipeline requests that omit both names retain the legacy local-lvm destination; an explicitly supplied value is never replaced.

Application-level request-validation responses are deliberately generic and contain no Pydantic input, validation context, request fields, signed URLs, keys, or user-data. Callers receive a stable 422 request_validation_error shape and should validate detailed input locally against OpenAPI.

Compatibility window: preflight v1 and secret-safe build response v2 remain supported through 0.0.21.x. A breaking replacement cannot be introduced before v0.0.22.0 and must be documented first. Legacy raw build/output fields were removed immediately from default responses as a security correction and are not covered by this compatibility window.

Cloud Firecracker (/cloud/firecracker)

These endpoints are called by the management backend after it resolves the selected Firecracker host/image inventory from netbox-proxbox and creates the FirecrackerMicroVM row in NetBox.

Both mutations require X-Proxbox-Actor. Firecracker hosts have no local ProxmoxEndpoint row, so allow_writes does not apply to this route family.

  • POST /cloud/firecracker/provision - Provision a Firecracker micro-VM through one host-agent and return a final JSON response.
  • POST /cloud/firecracker/provision/stream - Same provisioning flow as Server-Sent Events. Emits provision_step and terminal_line events, then a terminal complete event.

Provisioning steps:

Step Purpose
host_agent_health Check host-agent reachability, status, Firecracker version, and KVM availability
capabilities Confirm the requested network mode and capacity fit the host
prepare_assets Prepare or verify the kernel and rootfs image bundle on the host
create_microvm Create the Firecracker micro-VM through the host-agent
start_microvm Start the micro-VM when start_after_provision=true, otherwise emit skipped

Request fields are defined by FirecrackerProvisionRequest: host_agent_base_url, optional host_agent_token, optional host_id and host_pool_id, image, optional netbox_microvm_id, microvm_id, name, optional tenant_id, network, vcpus, memory_mib, disk_mib, ssh_authorized_keys, metadata, and start_after_provision.

host_agent_base_url is validated before proxbox-api creates the outbound host-agent client: it must be http or https, include a host, omit embedded credentials/query/fragment components, and pass the shared SSRF guard. The SSE variant returns a generic failure message by default unless PROXBOX_EXPOSE_INTERNAL_ERRORS=true. The non-streaming route maps host-agent failures to a fixed HTTP 502 response, and upstream response bodies are never reflected. URL validation and the HTTP connection currently perform separate DNS resolutions; address pinning with correct HTTPS SNI and certificate verification remains follow-up work.

Successful responses return FirecrackerProvisionResponse with ok, microvm_id, instance_ref, host_id, host_pool_id, image_id, status, optional guest_ip, and optional detail.

Cloud Azure VHD Import (/cloud/azure)

Operator-facing Azure managed-disk V2V planning and optional remote execution. This endpoint is consumed by the management page /cloud/azure-to-proxbox-migration.

  • POST /cloud/azure/vhd-imports - Validate an Azure-exported VHD import request and return the generated operator script. When execute=true, run the script remotely over SSH and return execution status plus stdout/stderr.

Request highlights:

  • Required: target_node, vmid, name, azure_vhd_url
  • Optional: source_vhd_filename, vm_storage, bridge, vlan_tag, memory_mb, cores, cpu, description
  • vm_generation: gen1 or gen2
  • guest_profile: linux_standard or windows_first_boot_safe
  • Execution fields: execute, endpoint_id, plus compatibility assertions ssh_host, ssh_user, ssh_port, ssh_identity_file, and ssh_known_host_fingerprint

Execution rules:

  • azure_vhd_url is protected by the normal SSRF validator.
  • execute=true requires endpoint_id so the route can enforce ProxmoxEndpoint.allow_writes.
  • execute=true also requires PROXBOX_ENABLE_CLOUD_IMAGE_EXECUTION=true.
  • The persisted endpoint binding exclusively supplies the execution node, host, user, port, identity path, and pinned SHA-256 host-key fingerprint. Any caller-supplied SSH field must match that binding.
  • Execution refuses incomplete bindings or a host-key mismatch. ssh_identity_file must resolve under PROXBOX_SSH_KEY_DIR; the service opens it once and passes its descriptor to a fixed /usr/bin/ssh -F none invocation with strict host-key checking and all proxy authority disabled.
  • After host-key pinning, the service refreshes the endpoint from the database and repeats the complete authorization/binding check immediately before the child starts. Each import runs in a unique server-generated systemd unit so bounded timeout and cancellation cleanup can target only that operation.

Generated pipeline behavior:

  • preflights host tooling, destination node name, VMID availability, storage, and bridge presence
  • downloads the Azure VHD to /var/lib/vz/template/cache/ with resumable curl -C -
  • validates source and converted images with qemu-img info
  • converts it with qemu-img convert -f vpc -O qcow2
  • creates the VM shell with Gen1/Gen2-aware BIOS defaults
  • imports the disk with qm importdisk and attaches the volid parsed from the import command output
  • attaches the imported volume as:
    • scsi0 + virtio-scsi-single for linux_standard
    • sata0 + e1000 for windows_first_boot_safe

The response includes:

  • build_script
  • commands
  • follow_up_steps
  • bios, machine, disk_interface, network_model, boot_order
  • source_vhd_filename, source_vhd_path, qcow2_filename, qcow2_path
  • when executed remotely: status, returncode, bounded execution byte/line counts, fixed diagnostics, and recovery_required. Execute-mode responses blank the SAS URL, generated script, and command list and never return raw stdout or stderr.
  • recovery_required is false for failures proven to occur before the remote child starts and for timeouts whose targeted unit stop is confirmed. It is true for nonzero remote exits and unconfirmed timeout/cancellation outcomes.

NetBox Routes (/netbox)

  • POST /netbox/endpoint - Create the singleton NetBox endpoint. The response includes an advisory probe result produced with a dedicated 10-second request timeout and a separately bounded one-second temporary-client cleanup; an unreachable NetBox or stalled cleanup never rolls back or indefinitely blocks the endpoint write.
  • GET /netbox/endpoint - List NetBox endpoint records.
  • NetBox endpoint updates and deletion atomically retire every cached SDK facade for that endpoint, so new requests cannot acquire an obsolete credential generation. Retired transports remain available to requests that already borrowed them and are closed with the current generation only after the final application lifespan exits. Failed shutdown closures remain queued for retry instead of becoming unreachable.
  • GET /netbox/endpoint/{netbox_id} - Get endpoint by ID.
  • GET /netbox/endpoint/{netbox_id}/probe - Run the same authenticated, request-private reachability probe used after endpoint writes. The result reports reachable, a stable status, the NetBox API version when available, and credential-redacted error classification.
  • PUT /netbox/endpoint/{netbox_id} - Update endpoint and return an advisory probe result without blocking the durable update on reachability.
  • DELETE /netbox/endpoint/{netbox_id} - Delete endpoint.
  • GET /netbox/status - Fetch NetBox API status.
  • GET /netbox/openapi - Fetch NetBox OpenAPI.

A failed probe is cached for 30 seconds against an unambiguous exact URL, TLS, and credential fingerprint. The bounded, locked cache file is shared by all proxbox-api workers and stores no credentials. Sync dependencies fail fast with HTTP 502 for connection failures or HTTP 504 for timeouts while that result is fresh, before bootstrap or tag reconciliation can contact NetBox. A missing, expired, successful, or differently configured probe never blocks sync.

NetBox singleton rule

Attempting to create a second endpoint returns HTTP 400 with:

{
  "detail": "Only one NetBox endpoint is allowed"
}

Proxmox Routes (/proxmox)

Browser Console Session

POST /proxmox/console/sessions creates the short-lived upstream session used by the trusted management console relay. The request selects an exact endpoint, node, VMID, workload type, and console type. QEMU supports novnc and term; LXC supports term only.

The response contains the one-time VNC ticket URL, endpoint TLS policy, and a bounded websocket_auth object. websocket_auth.kind is authorization for a Proxmox API-token endpoint or cookie for a password-session endpoint. Its value is sensitive service-to-service transport material. The management backend stores it in its one-use Redis relay ticket and attaches it only to the upstream WebSocket handshake; it must never be returned to browser JavaScript or written to logs.

POST /proxmox/console/browser-sessions is the distinct standalone browser contract. It accepts the same endpoint and guest selector plus an exact HTTPS origin, then returns only stream_token, websocket_path, expires_at, and console_type. websocket_path is exactly /proxmox/console/browser-stream and never contains the token. Connect with the same serialized Origin and offer exactly binary plus proxbox-token.<stream_token>; the server accepts only binary. Query-token, missing, duplicate, malformed, and extra token protocols are rejected before upstream access. Shared SQLite state is Fernet-encrypted, expires after 30 seconds, and is atomically consumed once across workers. The route is unavailable when encryption is not configured; the lab-only plaintext credential setting does not weaken this boundary. The upstream connector disables ambient proxies and refuses all WebSocket redirects before any second connection, preventing credential replay.

The relay supports QEMU noVNC, QEMU terminal, and LXC terminal. For noVNC it performs the RFB 3.8 VNC challenge response on the server and advertises the post-authenticated stream to the browser, so the Proxmox ticket never enters browser memory. The relay uses the endpoint's persisted verify_ssl value and never accepts a request-level TLS override.

See Proxmox Console Sessions for the complete request flow, response-field sensitivity, endpoint resolution, ticket normalization, WebSocket URL construction, authentication modes, TLS policy, failure behavior, security invariants, and tests.

Endpoint configuration CRUD

  • POST /proxmox/endpoints
  • GET /proxmox/endpoints
  • GET /proxmox/endpoints/{endpoint_id}
  • PUT /proxmox/endpoints/{endpoint_id}
  • DELETE /proxmox/endpoints/{endpoint_id}

Validation rules:

  • Provide password, or both token_name and token_value.
  • token_name and token_value must be set together.
  • Endpoint names must be unique.
  • PUT is idempotent: when every supplied field, including credentials, already matches the persisted endpoint, it returns the current representation without repeating host validation or writing to the database.

Session and discovery

  • GET /proxmox/sessions
  • GET /proxmox/version
  • GET /proxmox/
  • GET /proxmox/storage
  • GET /proxmox/nodes/{node}/storage/{storage}/content
  • GET /proxmox/storage/zfs/pools?node= - Read-only ZFS pool health and capacity summaries. Tier 1 uses Proxmox REST /nodes/{node}/disks/zfs via proxmox-sdk; the response reports the selected source and attempted fallback tiers.
  • GET /proxmox/storage/zfs/pools/{name}?node= - Read-only ZFS pool detail including state/status/action/scan/errors and recursive vdev children[] from Proxmox REST /nodes/{node}/disks/zfs/{name}. InfluxDB and JSON-native SSH fallback tiers currently degrade gracefully when not configured/implemented.
  • POST /proxmox/metrics/influx/query - Authenticated, provider-neutral InfluxDB v2 query contract. The typed request builds bounded Flux from URL/org/bucket/token, time window, measurement, field/tag filters, optional aggregation, and row/response limits; raw Flux is not accepted. The normalized response supports annotated CSV and supported JSON with columns, rows, row_count, truncated, query_window, captured_at, and response_format.
  • POST /proxmox/metrics/pull/query - Authenticated direct Proxmox metrics pull. The typed request selects one configured endpoint, applies bounded time/object/metric/row/byte filters, and invokes only cluster/metrics/export.
  • GET /proxmox/{top_level} where top_level is one of access, cluster, nodes, storage, or version
  • GET /proxmox/{node}/{type}/{vmid}/config

Cluster, node, and replication data

  • GET /proxmox/cluster/status
  • GET /proxmox/cluster/resources
  • GET /proxmox/nodes/
  • GET /proxmox/nodes/{node}/network
  • GET /proxmox/nodes/{node}/qemu
  • GET /proxmox/replication

Metrics query transports

POST /proxmox/metrics/influx/query is authenticated by the normal X-Proxbox-API-Key middleware and queries the caller-selected InfluxDB v2 endpoint. The token is used only for that upstream request; it is not stored, returned, or included in logs and errors. The backend does not call NetBox, any separate monitoring or management plugin for this contract.

The request includes url, org, bucket, token, measurement, optional mutually exclusive field or bounded fields[], filters[] (key, value, scope of tag or field, and operator of == or !=), optional aggregation (every, function), start, stop, timeout_seconds, max_rows, and max_response_bytes. URLs must use HTTPS and cannot contain credentials, query strings, or fragments. Time values are bounded relative Influx durations or timezone-qualified RFC3339 timestamps. The client adds an upstream limit of one row beyond the requested bound so the response can report truncated=true without returning extra rows.

Successful responses normalize annotated CSV and the supported Influx JSON results/tables and results/series shapes. Empty valid results return an empty normalized response; empty bodies, malformed data, timeouts, TLS and transport failures, upstream HTTP failures, and oversized responses map to stable secret-safe error reasons. max_response_bytes bounds both the upstream body and the normalized JSON response, preventing repeated column names from amplifying a compact upstream table during serialization. The URL must use HTTPS. The shared SSRF policy rejects loopback, link-local, metadata, multicast, and other unsafe resolved addresses while permitting private IPv4 ranges for on-premises InfluxDB. The backend pins the validated address, disables redirects and proxy environment variables, and rejects verify_ssl=false unless PROXBOX_ALLOW_INSECURE_INFLUX_TLS is explicitly enabled. This query route is separate from metric server configuration and does not read or mutate that configuration.

POST /proxmox/metrics/pull/query resolves exactly one existing endpoint from the database or NetBox endpoint source. It accepts an exact endpoint_id or one selector (target_name, target_domain, or target_ip_address), optional bounded object_ids, object_prefixes, and metric_names, plus start_time, history, local_only, max_rows, and max_response_bytes. History requires a start time. The implementation calls only cluster/metrics/export; callers cannot provide a Proxmox path. Rows are validated, sorted by timestamp/object/ metric, and deduplicated by (object_id, metric, timestamp). Conflicting duplicate identities and malformed, non-finite, oversized, or unbounded provider data fail with secret-safe reasons.

The pull transport enforces the response-byte limit while streaming from the authenticated Proxmox HTTPS backend, before JSON materialization. It requests identity encoding, disables automatic decompression, rejects a declared or observed body over the limit, rejects transport-compressed responses, and does not follow redirects. Boolean query parameters use the Proxmox-compatible 0 and 1 encodings. The service adapter delegates to the SDK's public bounded-read method (pinned proxmox-sdk==0.0.15) and maps its typed failures to secret-safe reasons.

High-Availability (read-only)

Aggregated across every configured Proxmox cluster. These endpoints back the HA tab on the NetBox VM detail page and the cluster-wide HA page added by netbox-proxbox for issue #243. Mutations (add/remove resource, migrate/relocate, group CRUD) are intentionally out of scope and may be added in a follow-up release.

  • GET /proxmox/cluster/ha/status - Per-service CRM/LRM rows from /cluster/ha/status/current, plus quorum/master entries.
  • GET /proxmox/cluster/ha/resources - Configured HA resources merged with their live runtime state (node, CRM state, request state).
  • GET /proxmox/cluster/ha/resources/by-vm/{vmid} - Convenience lookup for a single VM/CT id; tries vm:{vmid} then falls back to ct:{vmid}. Returns null (not 404) when the guest is not HA-managed so the NetBox tab can render an empty state.
  • GET /proxmox/cluster/ha/groups - List of HA groups with merged detail (nodes, restricted, nofailback).
  • GET /proxmox/cluster/ha/groups/{group} - Single group detail across clusters; returns null when no cluster has the group.
  • GET /proxmox/cluster/ha/rules - List configured HA rules across clusters (PVE 9.x+; empty list on older clusters).
  • GET /proxmox/cluster/ha/summary - Single envelope ({status, groups, resources, rules}) composed in parallel via asyncio.gather. groups is populated for PVE ≤ 8.x; rules for PVE 9.x+. Used by the NetBox cluster-wide HA page so a render only triggers one round-trip.
  • POST /proxmox/cluster/ha/disarm - Disarm the HA stack cluster-wide (PVE 9.2+). Gated by ProxmoxEndpoint.allow_writes. While disarmed, HA guests are not fenced or auto-migrated.
  • POST /proxmox/cluster/ha/arm - Re-arm the HA stack cluster-wide after maintenance (PVE 9.2+). Gated by ProxmoxEndpoint.allow_writes.
  • GET /proxmox/cluster/ha/manager-status - CRM manager status (queue depths, CRS scheduling state, quorum health) across clusters (PVE 9.2+).
  • GET /proxmox/cluster/ha/crs - CRS (Cluster Resource Scheduler) configuration from /cluster/options. Controls the dynamic load-balancer scheduling mode (static / basic / dynamic) (PVE 9.2+).

VM Operational Verbs

POST verbs that act on a single QEMU VM or LXC container. Implemented in proxbox_api/routes/proxmox_actions.py. Each handler is gated by ProxmoxEndpoint.allow_writes; the gate runs before any NetBox or Proxmox call, so a write-disabled endpoint returns 403 even when the downstream services are unreachable.

All verb routes accept:

  • endpoint_id (query parameter, required) — selects the target Proxmox cluster among many.
  • Idempotency-Key (header, optional) — 60-second cache window per (endpoint_id, verb, vmid). A second POST with the same key returns the cached body without re-dispatching.
  • X-Proxbox-Actor (header, optional) — actor label written to the NetBox journal entry. Defaults to proxbox-api.

Every invocation (success, failure, or no-op) writes exactly one journal entry on the linked NetBox VirtualMachine resolved by the proxmox_vm_id custom field. If the journal write fails, the route fails closed instead of returning a successful verb response without an audit record.

Method Path Purpose
POST /proxmox/qemu/{vmid}/start Start a QEMU VM. State-based no-op when already running (result: "already_running").
POST /proxmox/lxc/{vmid}/start Start an LXC container. Same no-op rule.
POST /proxmox/qemu/{vmid}/stop Stop a QEMU VM. State-based no-op when already stopped (result: "already_stopped").
POST /proxmox/lxc/{vmid}/stop Stop an LXC container. Same no-op rule.
POST /proxmox/qemu/{vmid}/snapshot Create a QEMU snapshot. Optional JSON body {snapname, description}; when snapname is omitted the route generates proxbox-{idempotency_key[:8]} or proxbox-{utc_stamp}. Always dispatched (no state-based no-op).
POST /proxmox/lxc/{vmid}/snapshot Create an LXC snapshot. Same body and default rules.
POST /proxmox/qemu/{vmid}/migrate Migrate a QEMU VM. Required body {target, online}. Runs a preflight against /nodes/{node}/qemu/{vmid}/migrate and rejects when the target is not allowed or online=true would hit local disks/resources. Returns 202 Accepted with proxmox_task_upid and sse_url (the cancel/stream endpoints below).
POST /proxmox/lxc/{vmid}/migrate Migrate an LXC container. Same body and 202 shape.
DELETE /proxmox/qemu/{vmid}/migrate/{task_upid} Best-effort cancel of an in-flight migrate task. Journals the cancel intent even if Proxmox refuses.
DELETE /proxmox/lxc/{vmid}/migrate/{task_upid} Best-effort cancel for LXC migrate.
GET /proxmox/qemu/{vmid}/migrate/{task_upid}/stream SSE stream emitting migrate_dispatched, repeated migrate_progress, then migrate_succeeded xor migrate_failed.
GET /proxmox/lxc/{vmid}/migrate/{task_upid}/stream SSE stream for LXC migrate task progress.

allow_writes gate (403 shape)

When endpoint_id is missing, the endpoint does not exist, or ProxmoxEndpoint.allow_writes is false, the handler returns HTTP 403 with one of three reason codes:

{
  "reason": "endpoint_writes_disabled",
  "detail": "Operational verbs are disabled on this endpoint. Enable ProxmoxEndpoint.allow_writes on the NetBox side after granting core.run_proxmox_action to the operator group.",
  "endpoint_id": 7
}

Other 403 shapes use reason: "endpoint_id_required" or reason: "endpoint_not_found" and omit endpoint_id. The gate is the load-bearing trust boundary documented in docs/design/operational-verbs.md §2.3 layer 3 — it must remain the first check in every handler.

Response shape (success / no-op)

{
  "verb": "start",
  "vmid": 100,
  "vm_type": "qemu",
  "endpoint_id": 7,
  "result": "ok",
  "dispatched_at": "2026-05-13T14:22:08Z",
  "proxmox_task_upid": "UPID:pve1:00012E34:...",
  "journal_entry_url": "/api/extras/journal-entries/42/"
}

result is one of ok, already_running, already_stopped, accepted (migrate dispatch), cancel_requested, cancel_failed, rejected, or failed. Error paths add reason and detail. The migrate 202 response also carries sse_url, target, online, and source_node.

Create a Proxmox Backup Server storage

POST /proxmox/storage/pbs?endpoint_id={id} registers one PBS datastore as a create-only Proxmox storage. The JSON body contains storage, server, optional port (default 8007), datastore, optional namespace, username in user@realm!tokenname form, write-only password, required SHA-256 fingerprint, and optional nodes. The server fixes type=pbs, content=backup and prune-backups=keep-all=1; callers cannot override these values. The retention is fixed because Proxmox otherwise applies the storage or node retention after every backup and can delete older PBS backups, which the PBS prune jobs own.

The allow_writes gate runs before body validation. The verb compares the normalized existing storage first. An equal storage returns result="already_present" without a write. A difference returns HTTP 409 with reason="storage_conflict" and only the differing field names (an existing storage without prune-backups=keep-all=1 differs). A timeout or connection loss after the single create request causes one configuration read; an equal storage then returns result="created", and the POST is never retried within the request. The idempotency scope is (endpoint_id, pbs_storage_create, storage, Idempotency-Key) for 60 seconds.

Every gated request uses one write-ahead NetBox journal entry and a terminal update assigned to the mirrored netbox-proxbox ProxmoxEndpoint; an invalid body, which dispatches nothing, gets one terminal entry. A request that is cancelled after the gate (for example by a client disconnect or a graceful shutdown) still completes its Proxmox call, its terminal journal update and its cache entry before the cancellation propagates. A failed terminal update is retried twice within the request. When it still fails, the answer is HTTP 502 with journal_finalized=false; a replay with the same Idempotency-Key within the 60-second idempotency window retries the update of the original entry and then returns the terminal answer, without another Proxmox write. Like the other operational verbs, the repair metadata lives only in that in-memory window: after it, or after a restart, the original entry stays in_progress although the Proxmox write completed. The password is excluded from responses, logs, journals, exceptions, validation details, and idempotency cache entries. An invalid body returns HTTP 422 with reason="request_validation_failed" and the names of the invalid schema fields only (an unexpected key is reported as unexpected field, never by its name). A Proxmox refusal returns HTTP 502 with reason="proxmox_dispatch_failed", the Proxmox HTTP status and the names of the rejected parameters, never their values. The generated POST /proxmox/api2/storage route remains read-only and returns HTTP 403.

Firewall (read and write)

Implemented in proxbox_api/routes/proxmox/firewall.py. All read endpoints are safe regardless of allow_writes. Write endpoints (POST/PUT/DELETE) are gated by ProxmoxEndpoint.allow_writes and require the X-Proxbox-Actor header. When allow_writes is false, write endpoints return HTTP 403:

{"detail": {"reason": "writes_disabled_for_endpoint"}}

Datacenter-level (read-only):

  • GET /proxmox/firewall/datacenter/rules — List datacenter firewall rules. Returns list[FirewallRuleSchema].
  • GET /proxmox/firewall/datacenter/security-groups — List security groups with their inline rules. Returns list[FirewallSecurityGroupSchema].
  • GET /proxmox/firewall/datacenter/ipsets — List IP sets with their entries. Returns list[FirewallIPSetSchema].
  • GET /proxmox/firewall/datacenter/aliases — List datacenter aliases. Returns list[FirewallAliasSchema].
  • GET /proxmox/firewall/datacenter/options — Datacenter firewall options (enable, policy_in, policy_out). Returns FirewallOptionsSchema.
  • GET /proxmox/firewall/summary — Aggregated datacenter-level firewall data across all configured Proxmox endpoints. Returns FirewallSummarySchema.

Datacenter-level write endpoints (gated by allow_writes):

  • POST /proxmox/firewall/datacenter/rules — Create datacenter firewall rule. Body: FirewallRuleWrite.
  • PUT /proxmox/firewall/datacenter/rules/{pos} — Update datacenter rule at position.
  • DELETE /proxmox/firewall/datacenter/rules/{pos} — Delete datacenter rule at position.
  • POST /proxmox/firewall/datacenter/security-groups — Create security group. Body: FirewallSecurityGroupWrite.
  • POST /proxmox/firewall/datacenter/security-groups/{group}/rules — Add rule to security group.
  • PUT /proxmox/firewall/datacenter/security-groups/{group}/rules/{pos} — Update rule in security group.
  • DELETE /proxmox/firewall/datacenter/security-groups/{group}/rules/{pos} — Delete rule from security group.
  • DELETE /proxmox/firewall/datacenter/security-groups/{group} — Delete security group.
  • POST /proxmox/firewall/datacenter/ipsets — Create IP set. Body: FirewallIPSetWrite.
  • POST /proxmox/firewall/datacenter/ipsets/{name} — Add entry to IP set. Body: FirewallIPSetEntryWrite.
  • PUT /proxmox/firewall/datacenter/ipsets/{name}/{cidr} — Update IP set entry.
  • DELETE /proxmox/firewall/datacenter/ipsets/{name}/{cidr} — Delete IP set entry.
  • DELETE /proxmox/firewall/datacenter/ipsets/{name} — Delete IP set.
  • POST /proxmox/firewall/datacenter/aliases — Create datacenter alias. Body: FirewallAliasWrite.
  • PUT /proxmox/firewall/datacenter/aliases/{name} — Update alias.
  • DELETE /proxmox/firewall/datacenter/aliases/{name} — Delete alias.
  • PUT /proxmox/firewall/datacenter/options — Update datacenter firewall options. Body: FirewallOptionsWrite.

Per-node (read-only):

  • GET /proxmox/firewall/nodes/{node}/rules?cluster_name= — List firewall rules for a node.
  • GET /proxmox/firewall/nodes/{node}/options?cluster_name= — Firewall options for a node.

Per-VM (read-only, QEMU and LXC):

  • GET /proxmox/firewall/vms/{vmid}/rules?node=&vm_type=qemu|lxc — List VM firewall rules.
  • GET /proxmox/firewall/vms/{vmid}/ipsets?node=&vm_type= — List VM IP sets with entries.
  • GET /proxmox/firewall/vms/{vmid}/aliases?node=&vm_type= — List VM aliases.
  • GET /proxmox/firewall/vms/{vmid}/options?node=&vm_type= — VM firewall options.

SDN (read-only, PVE 9.2+)

Implemented in proxbox_api/routes/proxmox/sdn.py. All endpoints are read-only. Older clusters that do not expose a path are counted as skipped warnings; healthy clusters still contribute their rows.

  • GET /proxmox/sdn/controllers — List SDN controllers across all clusters. Returns list[SdnControllerSchema].
  • GET /proxmox/sdn/zones — List SDN zones across all clusters. Returns list[SdnZoneSchema].
  • GET /proxmox/sdn/vnets — List SDN VNets across all clusters. Returns list[SdnVNetSchema].
  • GET /proxmox/sdn/subnets — List SDN VNet subnets across all clusters. Returns list[SdnSubnetSchema].
  • GET /proxmox/sdn/fabrics — List SDN fabrics (WireGuard/BGP/VXLAN/OSPF) across all clusters. Returns list[SdnFabricSchema].
  • GET /proxmox/sdn/fabrics/all — List all SDN fabrics including inherited ones across all clusters. Returns list[SdnFabricSchema].
  • GET /proxmox/sdn/route-maps — List SDN route-map objects (BGP/EVPN route filtering) across all clusters. Returns list[SdnRouteMapSchema].
  • GET /proxmox/sdn/prefix-lists — List SDN prefix-list objects (CIDR ranges for BGP/EVPN filtering) across all clusters. Returns list[SdnPrefixListSchema].
  • GET /proxmox/sdn/node-status — List node-local zone content, bridge, MAC-VRF, and IP-VRF rows. Returns list[SdnNodeStatusSchema].
  • GET /proxmox/sdn/create/stream?sync_mode_sdn_bgp= — Server-Sent Events stage that reconciles read-only SDN state into NetBox: EVPN/VXLAN VNets to vpn.L2VPN, resolvable runtime targets to vpn.L2VPNTermination, EVPN import route targets to ipam.RouteTarget, valid subnets to ipam.Prefix, and all Proxmox-specific SDN rows to netbox-proxbox plugin metadata. sync_mode_sdn_bgp=always or bootstrap_only additionally projects BGP fabrics/controllers, sessions, route-maps, prefix-lists, and validated communities into the optional netbox_bgp plugin; disabled skips that projection.

Datacenter (PVE 9.2+)

Implemented in proxbox_api/routes/proxmox/datacenter.py. Write routes (POST, PUT, DELETE) require a cluster_name query parameter when multiple clusters are configured.

  • GET /proxmox/datacenter/cpu-models — List all custom CPU models across all clusters. Returns list[CustomCpuModelSchema]. Returns 501 on PVE < 9.2.
  • GET /proxmox/datacenter/cpu-models/{cputype}?cluster_name= — Get a specific custom CPU model. Returns CustomCpuModelSchema | null.
  • POST /proxmox/datacenter/cpu-models?cluster_name= — Create a custom CPU model.
  • PUT /proxmox/datacenter/cpu-models/{cputype}?cluster_name= — Update a custom CPU model.
  • DELETE /proxmox/datacenter/cpu-models/{cputype}?cluster_name= — Delete a custom CPU model.
  • GET /proxmox/datacenter/options — Get datacenter options (includes CRS sub-object on PVE 9.2). Returns a merged dict of options across clusters.
  • PUT /proxmox/datacenter/options?cluster_name= — Update datacenter options.

Access tokens (PVE 9.2+)

Implemented in proxbox_api/routes/proxmox/access.py.

  • GET /proxmox/access/tokens/{userid}/{tokenid}?cluster_name= — Retrieve info for a Proxmox API token. Returns AccessTokenInfoSchema | null. value is only set on regenerate responses.
  • PUT /proxmox/access/tokens/{userid}/{tokenid}/regenerate?cluster_name= — Regenerate the secret of an existing API token in-place (PVE 9.2+). All ACL entries are preserved. Returns TokenRegenerateResponseSchema. Store the returned value immediately — it cannot be retrieved again.

Service Monitoring

Implemented in proxbox_api/routes/proxmox/services.py. Read-only, agentless systemd service-monitoring pulled over SSH using the endpoint's own registered SSH credential — no Proxmox-side agent required. endpoint_id is the NetBox-side ProxmoxEndpoint id (same id space as the SSH Terminal below), not proxbox-api's own SQLite endpoint id.

  • GET /proxmox/services/systemd?endpoint_id=&units= — Read current systemctl show state for one or more systemd units. units is optional and repeatable/comma-separated; when omitted, the endpoint's NetBox service_monitoring_units value is used, falling back to the default 11-unit Proxmox set (pve-cluster.service, corosync.service, pvedaemon.service, pveproxy.service, pvestatd.service, pve-firewall.service, pvescheduler.service, spiceproxy.service, qmeventd.service, pve-ha-lrm.service, pve-ha-crm.service). Unit names must match ^[A-Za-z0-9_][A-Za-z0-9_.@:-]*$, contain no .., be ≤100 characters, and at most 32 units may be requested per call (422 on violation). Returns ProxmoxServicesResponse (endpoint_id, host, collected_at, reachable, services: list[ProxmoxServiceRecord], optional error). reachable=false (SSH transport unreachable) is a legitimate monitoring result returned as HTTP 200, not an error.
    • Gated on the NetBox ProxmoxEndpoint being enabled, service_monitoring_enabled=true, allow_writes=true, access_methods="api_ssh", having complete SSH credentials, and netbox-rpc not disabled for the endpoint; otherwise 403 with a service_monitoring_* reason code. Unknown endpoint_id returns 404.
    • Executes a fixed-argv systemctl show --no-pager -p <prop> ... -- <unit> ... command (no sudo); each unit name is additionally shlex.quote'd as defense in depth. Bounded by a 10-second SSH command timeout (error.reason="command_timeout" with reachable=true on expiry, not an exception).
    • Called by the RPC executor's @rpc_handler("os.linux_proxmox.show_systemctl_services") via the matching netbox-rpc procedure; not intended to be called directly by end users.

SSH Terminal

Implemented in proxbox_api/routes/ssh_terminal.py. Provides a browser-based SSH terminal backed by asyncssh.

  • POST /ssh/sessions — Create a one-time ticket for a browser SSH session. Request body: TerminalSessionCreate (target_type, endpoint_id, optional node_id, optional host, optional actor, cols, rows). Returns HTTP 201 with TerminalSessionPublic (session_id, ticket, websocket_path, expires_at, target_type).
  • GET /ssh/host-key-fingerprint?host=&port= — Scan a host key without authenticating. The caller-selected host must pass the shared SSRF policy before the socket opens.
  • WebSocket /ssh/sessions/{session_id}/ws — Authenticate the ticket and bridge a PTY to the target SSH host. The first WebSocket frame must be {"type": "auth", "ticket": "<ticket>"}. On success, raw terminal I/O is relayed. On error, {"type": "error", "message": "..."} is sent before close.

Any caller-selected ticket host must also pass the shared SSRF policy before the ticket is retained. Before presenting a password or private key, the SSH service performs a separate credential-free handshake and compares the server fingerprint with the stored pin. It retains AsyncSSH callback validation and checks the negotiated key again after the authenticated connection, before a PTY or fixed command is started.

Viewer and generated contract helpers

  • POST /proxmox/viewer/generate - Development-only. It is absent and returns HTTP 404 unless the process starts with PROXBOX_RUNTIME_CODEGEN_ENABLED=true. When enabled, it crawls the Proxmox API Viewer and generates OpenAPI and Pydantic artifacts. Invalid or non-contained version tags return HTTP 422 before crawling or writing files. Bundled tags are immutable and return HTTP 409 when persist=true; update them only by installing a replacement package. Non-default-source artifacts are stored under custom/<version_tag>/ for inspection only.
  • GET /proxmox/viewer/openapi - Return a bundled Proxmox OpenAPI document by default. The regenerate=true and unknown-tag generation paths return HTTP 404 unless runtime code generation is enabled.
  • GET /proxmox/viewer/openapi/embedded - Return an embedded subset of the generated OpenAPI.
  • GET /proxmox/viewer/integration/contracts - Report Proxmox and NetBox schema contract sources.
  • POST /proxmox/viewer/routes/refresh - Development-only. It is absent and returns HTTP 404 unless runtime code generation is enabled. When enabled, it rebuilds runtime-generated Proxmox routes from disk without restarting.
  • GET /proxmox/viewer/schema-status - Report available bundled schema versions and active background generation tasks. Accepts optional version_tag to inspect a specific version.
  • GET /proxmox/viewer/pydantic - Render Pydantic v2 model source from a validated bundled OpenAPI document by default. Rendering runs off the event loop, is cached by schema digest, is limited to 2 MiB, and is rate-limited to six requests per minute per source. The route never reads persisted Python source.

See Schema Management for the full workflow guide and the proxbox-schema CLI reference.

Runtime-generated live proxy routes

proxbox-api mounts runtime-generated Proxmox proxy routes from bundled OpenAPI contracts under the following paths. PROXBOX_RUNTIME_CODEGEN_ENABLED defaults to false; production must keep it disabled.

  • /proxmox/api2/{version_tag}/*
  • /proxmox/api2/* as a compatibility alias to latest

Behavior:

  • Generated proxy dispatch is read-only: only GET is forwarded. Authenticated, schema-valid POST, PUT, and DELETE requests return HTTP 403 before target selection, credential resolution, or a Proxmox session is opened. Invalid requests can still return the normal authentication or schema-validation errors.
  • Mutation schemas remain visible for discovery, marked deprecated with an explicit 403 response. Existing clients must use supported typed, audited RPC procedures for mutations; an unsupported procedure is unavailable, not a reason to retry through a generated route. There is no generated-write opt-in flag or lease-header bypass.
  • The same denial applies to all explicit versions, the latest alias, in-process reuse, persisted cache reload, and forced rebuild. This method boundary does not certify every upstream GET as effect-free and does not change handcrafted lifecycle, console, Ceph, or Packer handlers.
  • With the default setting, route registration and schema discovery read bundled schemas only. The user-generated directory is not scanned for schemas. GET /proxmox/viewer/pydantic also renders bundled schemas only.
  • With PROXBOX_RUNTIME_CODEGEN_ENABLED=true, startup additionally admits non-conflicting user versions whose provenance.json digest matches openapi.json. Bundled tags always take precedence.
  • Provenance sidecars detect corruption; they do not authenticate artifacts. A process running as the same operating-system user can forge an artifact and its digest. Production therefore keeps runtime code generation disabled.
  • The mounted route set is cached under the configured user-generated schema directory in runtime_generated_routes_cache.json, with a separate provenance sidecar. This derived cache is the only runtime file written there under the default setting.
  • In an opted-in development process, startup uses the cache only when its provenance, document limits, and authoritative schema digests validate. Otherwise it rebuilds from eligible artifacts without replacing an already mounted last-known-good route set.
  • Route refresh persists the complete cache and provenance before swapping the mounted routes and OpenAPI schema, so a persistence failure preserves the authoritative in-process route set.
  • Routes are rebuilt on demand with POST /proxmox/viewer/routes/refresh only when runtime code generation is enabled.
  • POST /proxmox/viewer/routes/refresh with no query parameters rebuilds all available generated versions.
  • POST /proxmox/viewer/routes/refresh?version_tag=8.3 rebuilds only that mounted version.
  • The unversioned /proxmox/api2/* alias forwards to the latest generated contract.
  • Request bodies and responses are validated with runtime-generated Pydantic models.
  • Runtime route loading constructs those models directly from OpenAPI data and never evaluates the rendered Python source artifact.
  • Startup quarantines user-generated pydantic_models.py files and legacy route caches without valid provenance, plus orphan cache provenance sidecars. Quarantine uses an interprocess lock and no-follow, no-clobber moves. Operators can run the same upgrade step with proxbox-schema quarantine-legacy.
  • OpenAPI documents are rejected before persistence, cache restoration, or model construction when they exceed the fixed byte, depth, path, operation, property, model, or metadata-string limits. Field-name collisions, reserved Pydantic names, and duplicate operation-derived model names are also rejected.
  • Registration rejects more than 8 eligible versions, more than 32 MiB of aggregate OpenAPI bytes, more than 16,384 aggregate models, or more than 32,768 aggregate routes before constructing models or a cache.
  • Generated response models cover object, array, scalar, and null response schemas.
  • For array responses whose items are objects, generation emits {Operation}ResponseItem plus RootModel[list[{Operation}ResponseItem]] so Swagger shows concrete item fields.
  • Generated routes appear in FastAPI /docs and /openapi.json.
  • latest routes are mounted before older version tags so they appear first in Swagger.
  • Generated routes are prioritized ahead of older handcrafted /proxmox/* routes so path collisions resolve to the generated API surface.

Path parameter normalization:

  • When the Proxmox viewer uses path parameter names that are not valid FastAPI identifiers, the mounted FastAPI route uses a normalized placeholder name.
  • Example:
    • Proxmox contract path: /nodes/{node}/hardware/pci/{pci-id-or-mapping}
    • Mounted FastAPI path: /proxmox/api2/latest/nodes/{node}/hardware/pci/{pci_id_or_mapping}
  • The upstream proxmox-sdk SDK call still uses the original Proxmox parameter name from the generated OpenAPI contract.

Version discovery:

  • By default, a version is mountable only when proxbox_api/generated/proxmox/<version-tag>/openapi.json exists in the installed package. A bundled tag, including latest, can be refreshed only through package replacement.
  • With the development opt-in, a non-conflicting user version may also be mounted after its provenance and limits validate.
  • Non-version entries such as __pycache__ and files at the root of generated/proxmox/ are ignored.

Target selection:

  • If exactly one Proxmox endpoint exists, generated routes use it automatically.
  • If more than one endpoint exists, pass one of:
    • target_name
    • target_domain
    • target_ip_address
  • source selects whether endpoints come from the local database or NetBox plugin records.

Typed sync integration:

  • Handcrafted sync-facing routes still call Proxmox directly, but now do so through proxbox_api/services/proxmox_helpers.py backed by the proxmox-sdk SDK.
  • That helper layer validates live proxmox-sdk payloads with the generated models in proxbox_api/generated/proxmox/latest/pydantic_models.py before returning data to route handlers.
  • This avoids internal HTTP round-trips while keeping VM config, cluster status, cluster resources, storage listing, and node storage content aligned with the generated contract used by /proxmox/api2/*.

Examples of generated route shapes:

  • GET /proxmox/api2/latest/cluster/resources
  • GET /proxmox/api2/8.3/nodes/{node}/qemu/{vmid}/config
  • POST /proxmox/api2/latest/access/acl (disabled; valid authenticated requests return 403)
  • GET /proxmox/api2/cluster/resources as the compatibility alias for latest

Refresh response shape:

  • Top-level response: registration summary from register_generated_proxmox_routes() plus the message field.
  • state: nested snapshot from generated_proxmox_route_state().
  • state.mounted_versions: the versioned route sets currently mounted in FastAPI.
  • state.alias_version_tag: the version used by /proxmox/api2/*.
  • state.cache_path: persisted manifest path used to preserve generated routes across reloads.
  • state.cache_enabled: whether cache persistence is enabled for generated routes.
  • state.loaded_from_cache: whether the latest registration used the persisted runtime cache.
  • state.route_count: total generated FastAPI routes currently mounted.
  • state.versions.<tag>.route_count: number of FastAPI routes mounted for that version.
  • state.versions.<tag>.path_count: number of OpenAPI paths mounted for that version.
  • state.versions.<tag>.method_count: number of HTTP operations mounted for that version.
  • state.versions.<tag>.schema_version: the info.version value from the generated OpenAPI document.

Test coverage:

  • tests/test_generated_proxmox_routes.py runs a mock-based exhaustive route suite over every generated operation for every available version plus the latest alias. Reads must forward and validate their responses; mutation requests must be denied without an upstream call.
  • tests/test_generated_write_boundary.py independently fixes the denied-method matrix and checks authentication, refusal before target resolution, all registration modes, and fail-closed handling of unrecognized methods.
  • tests/test_pydantic_generator_models.py verifies generated response models for array, scalar, null, and aliased object payloads.
  • tests/test_session_and_helpers.py verifies the typed proxmox helper layer and confirms the handcrafted sync dependencies return helper-validated payloads.

NetBox Sync-Dependency Bootstrap

Every sync stage route that writes NetBox objects first reconciles the NetBox-side support objects Proxbox owns — the Proxbox tag, cluster type, manufacturer, generic device type, device role, VM roles, and VM types. This runs through ensure_netbox_sync_dependencies, declared as a route-level dependency (dependencies=[Depends(...)]) rather than as a handler parameter: FastAPI solves route-level dependencies before the path operation's own parameters, so the support objects exist before the route's data-producing dependencies attempt their first write.

Routes that run it:

  • GET /dcim/devices/create and /dcim/devices/create/stream
  • GET /virtualization/virtual-machines/storage/create and .../storage/create/stream
  • GET /virtualization/virtual-machines/create and .../create/stream
  • GET /virtualization/virtual-machines/{netbox_vm_id}/create and its stream variant
  • GET /full-update and /full-update/stream

The device and storage routes matter most: the plugin's stage order starts with devices and then storage, so on a fresh installation a stage-by-stage sync reaches them before anything else. The startup bootstrap does not cover this on a fresh install because no NetBox endpoint exists yet and the pass is skipped.

Adding a new route that writes NetBox objects means adding the same route-level dependency and extending tests/test_stage_route_bootstrap.py.

DCIM Routes (/dcim)

  • GET /dcim/devices
  • GET /dcim/devices/create - Create NetBox devices from Proxmox nodes. Runs the NetBox sync-dependency bootstrap first.
  • GET /dcim/devices/create/stream - SSE streaming variant. Runs the NetBox sync-dependency bootstrap first.
  • GET /dcim/devices/{node}/interfaces/create
  • GET /dcim/devices/interfaces/create - Sync all node interfaces across all clusters.
  • GET /dcim/devices/interfaces/create/stream - SSE streaming variant for all-node interface sync.

Virtualization Routes (/virtualization)

  • GET /virtualization/cluster-types/create - Stub that returns HTTP 501.
  • GET /virtualization/clusters/create - Stub that returns HTTP 501.
  • GET /virtualization/virtual-machines/create - Create NetBox VMs from Proxmox resources.
  • GET /virtualization/virtual-machines/create/stream - SSE streaming variant.
  • GET /virtualization/virtual-machines/{netbox_vm_id}/create - Create a single VM by NetBox ID.
  • GET /virtualization/virtual-machines/{netbox_vm_id}/create/stream - SSE streaming variant for single VM sync.
  • GET /virtualization/virtual-machines/
  • GET /virtualization/virtual-machines/{id}
  • GET /virtualization/virtual-machines/{id}/summary - Stub that returns HTTP 501.
  • GET /virtualization/virtual-machines/summary/example
  • GET /virtualization/virtual-machines/interfaces/create
  • GET /virtualization/virtual-machines/interfaces/create/stream
  • GET /virtualization/virtual-machines/interfaces/ip-address/create
  • GET /virtualization/virtual-machines/interfaces/ip-address/create/stream
  • GET /virtualization/virtual-machines/backups/create
  • GET /virtualization/virtual-machines/backups/all/create
  • GET /virtualization/virtual-machines/backups/all/create/stream
  • GET /virtualization/virtual-machines/{netbox_vm_id}/backups/create/stream
  • GET /virtualization/virtual-machines/snapshots/create
  • GET /virtualization/virtual-machines/snapshots/all/create
  • GET /virtualization/virtual-machines/snapshots/all/create/stream
  • GET /virtualization/virtual-machines/{netbox_vm_id}/snapshots/create/stream
  • GET /virtualization/virtual-machines/virtual-disks/create
  • GET /virtualization/virtual-machines/virtual-disks/create/stream
  • GET /virtualization/virtual-machines/{netbox_vm_id}/virtual-disks/create/stream
  • GET /virtualization/virtual-machines/storage/create - Runs the NetBox sync-dependency bootstrap first.
  • GET /virtualization/virtual-machines/storage/create/stream - Runs the NetBox sync-dependency bootstrap first.
  • GET /virtualization/virtual-machines/task-history/create/stream - Dedicated task-history SSE stage; accepts comma-separated netbox_vm_ids. Omitted means all VMs, while an explicitly empty, malformed, or non-positive value returns HTTP 422 before SSE starts. The optional fetch_max_concurrency must be at least 1. Each request resets and re-probes cached optional-sidecar unavailability. Internally, selected IDs are sent to NetBox as repeated values in deduplicated groups of at most 100; any failed group aborts the explicit selection.
  • GET /virtualization/virtual-machines/orphans/sweep
  • GET /virtualization/virtual-machines/orphans/sweep/stream - Standalone end-of-run orphan VM sweep for callers that drive each stage separately. The required run_id (non-empty; a missing or empty value is HTTP 422) is the run ID passed to the VM stage. Optional dry_run, vm_stage_failed, and comma-separated endpoint_ids / proxmox_endpoint_ids (the alias takes precedence; a malformed value is rejected before the sweep starts) scope and gate the run. A live (non-dry_run) sweep without an endpoint scope is rejected with HTTP 422, because run_id and vm_stage_failed are caller claims; only dry_run=true may be unscoped. The delete_orphans setting decides whether it acts. Orphans are soft-deleted only (status=decommissioning plus the proxbox-soft-deleted tag). The result, or the SSE complete result, always includes skipped_reason (null, disabled, vm_stage_failed, sidecar_unavailable, sidecar_read_failed, run_not_found, or live_inventory_unavailable). A live sweep also fetches the live Proxmox guest inventory of the scoped endpoints and only marks VMs confirmed absent from it, failing closed when that inventory cannot be fetched. Each request resets and re-probes cached optional-sidecar unavailability. See Orphan VM handling.

VM stream overwrite query parameters

Every VM stream endpoint listed above (/virtualization/virtual-machines/...create/stream) accepts the SyncOverwriteFlags query parameters defined in proxbox_api/schemas/sync.py. They control which user-managed NetBox fields the sync may overwrite:

  • overwrite_vm_tags, overwrite_vm_role, overwrite_vm_platform, overwrite_vm_description, overwrite_vm_custom_fields
  • overwrite_cluster_tags, overwrite_storage_tags, overwrite_node_interface_tags, overwrite_ip_tags

overwrite_vm_platform defaults to false. Enable it explicitly to reconcile an existing VM's NetBox platform from the Proxmox guest operating system; when it is false or omitted, platform remains operator-managed after initial VM creation.

  • sync_vm_network - when false, skips the VM-network sub-step.
  • sync_task_history - defaults to true; when false, skips the single post-VM task-history aggregate because a dedicated stage owns it. This flag is also declared on both targeted VM create routes and their SSE variants. A degraded owned aggregate retains reconciled rows but returns HTTP 502 from standalone REST; SSE reports the degraded task-history phase summary.

Task-history result field created is compatibility-named and counts all reconciled rows (created, updated, and unchanged), not only POST operations.

See Overwrite Flags for the full matrix and defaults.

The three virtual-disk endpoints also accept an optional fetch_max_concurrency query parameter to override the Proxmox VM-config fetch width for that request.

Degraded staged results

The VM-scoped stage routes (virtual-machines, virtual-disks, backups, snapshots, interfaces, and interfaces/ip-address) choose a selection mode by how they address VMs, as described in Staged-run selection. Routes that address one VM by path (/{netbox_vm_id}/...) fail closed on a VM whose Proxmox ownership cannot be resolved. List and estate routes (a netbox_vm_ids selection, /all/create, and the estate interface stages) drop that VM with a warning, process the rest, and report the drop instead of returning HTTP 502:

  • snapshots/all/create and virtual-disks/create (and their /stream variants) return their result object with two extra keys when a VM was dropped: degraded: true and warnings: [{"netbox_vm_id": <int>, "reason": "<text>"}]. Both keys are absent on a clean run.
  • backups/all/create, interfaces/create, and interfaces/ip-address/create keep returning a bare list on a clean run. When degraded they return {"<stage>": [...], "count": <int>, "warnings": [...], "degraded": true} where <stage> is backups, vm_interfaces, or vm_ip_addresses. The interfaces/create response already used this shape for partial interface failures; it now also carries degraded: true.
  • The /stream variants put the same warnings and degraded keys in the result of the stage step and the final complete events next to count. virtual-machines/create/stream does the same for a dropped selected VM; virtual-machines/create keeps returning a bare list when clean and returns {"virtual_machines": [...], "count": <int>, "warnings": [...], "degraded": true} when a selected VM was dropped. The by-id /{netbox_vm_id}/create routes stay strict.
  • GET /full-update and GET /full-update/stream aggregate every stage's warnings, each tagged with its phase, into the top-level warnings key and set degraded: true.

If every selected VM is dropped the stage still succeeds with an empty result plus the warnings. An unreadable sidecar scan, an invalid VM id, or a selection NetBox does not return in full remains an error in every mode. The task-history routes keep their own contract (see above).

Full Update

  • GET /full-update - Runs device sync, storage sync, VM sync, task history sync, disk sync, backup sync, snapshot sync, node interface sync, VM interface sync, VM IP sync, replication sync, and backup routine sync.
  • GET /full-update/stream - SSE streaming variant.

Both full-update variants pass sync_task_history=false to the VM stage and then run the dedicated task-history stage exactly once. Their optional fetch_max_concurrency query override must be at least 1.

Sync State Probe

  • GET /sync/active - Returns { active, started_at, id, kind, runs } reporting whether this API replica currently has a /full-update or /full-update/stream request in flight. Use this to fast-fail a cron / single-exec invocation when a sync is already running.

The registry is process-local and memory-only, so the probe answers for the worker that handles the request. With multiple uvicorn workers, callers may see disagreeing answers across workers; treat the response as advisory and keep the scheduling interval larger than the typical sync duration. The endpoint is covered by the standard X-Proxbox-API-Key middleware.

Response shape:

{
  "active": true,
  "started_at": "2026-05-12T17:53:28.122Z",
  "id": "9b6c0408-...",
  "kind": "full-update",
  "runs": [
    { "id": "9b6c0408-...", "kind": "full-update", "started_at": "2026-05-12T17:53:28.122Z" }
  ]
}

started_at / id / kind report the oldest in-flight run (FIFO). runs lists every registered run on the local replica for diagnostics.

WebSocket

  • GET / - Basic counter WebSocket for connectivity checks.
  • GET /ws/virtual-machines - WebSocket-triggered VM synchronization.
  • GET /ws - Command-driven WebSocket for sync orchestration.

SSE Streaming Format

All /stream endpoints return Content-Type: text/event-stream and emit three event types:

Event Description
step Progress frame with step, status, message, rowid, and payload.
error Error frame with step, status: "failed", error, and detail.
complete Final frame with ok, message, and optionally result or errors.

Headers:

  • Cache-Control: no-cache
  • X-Accel-Buffering: no

Sync Individual Routes (/sync/individual)

  • GET /sync/individual/node
  • GET /sync/individual/vm
  • GET /sync/individual/vm/{cluster_name}/{node}/{type}/{vmid}
  • GET /sync/individual/cluster
  • GET /sync/individual/interface
  • GET /sync/individual/ip
  • GET /sync/individual/disk
  • GET /sync/individual/storage
  • GET /sync/individual/snapshot
  • GET /sync/individual/task-history
  • GET /sync/individual/backup
  • GET /sync/individual/replication
  • GET /sync/individual/backup-routines

Extras Routes (/extras)

  • GET /extras/bootstrap-status

GET /extras/bootstrap-status returns the last startup NetBox bootstrap status and warnings. Proxbox custom-field creation and reconciliation routes have been removed; reflection state is stored only in typed netbox-proxbox sidecars.

Proxbox Plugin Config Routes

These route handlers exist in proxbox_api/routes/proxbox/__init__.py but are not currently mounted in main.py:

  • GET /netbox/plugins-config
  • GET /netbox/default-settings
  • GET /settings

Mounting them requires including that router in app startup if desired.