Skip to content

Device REST API

Status: 2026-11-04 source implementation. The optional device_management_api.create_app() factory starts no listener. This does not accept a built or installed service.

Access and hosting

This implementation requires Flask 3.1 or later for host validation. All nine routes require actual HTTPS, an accepted host name and Authorization: Bearer <token>. X-User, X-Role, query tokens and forwarded assertions of HTTPS do not authenticate callers. The factory denies access without an authority and explicit host profile. Supported host profiles are pro_desktop and enterprise_worker; Basic and EnterpriseClient do not provide this entry point. Pro uses SQLite and EnterpriseWorker PostgreSQL. The existing api.drivercard feature must be checked against current licensing at the composition root; allowed is this mandatory callback, never an HTTP caller-controlled value.

Trusted application code composes DeviceApiAuthority(db_path, allowed=licence_check) and create_app(db_path, authority=authority, host_profile=profile, trusted_hosts=[hostname]). licence_check, profile and hostname come from verified host configuration. Without an explicit host list only localhost/loopback host names are accepted, still requiring HTTPS. Certificates, listener, firewall and any strictly configured proxy boundary require separate setup. This change opens no port and accepts no arbitrary forwarded headers.

Identity and grants

The new device audience is separate from mobile, driver, portal and webhook credentials. The user must be active and hold current business permissions in app_role_permission. Each credential receives explicit scopes and either a list of permitted device-customer IDs or an explicit all_customers=True grant. No credential is issued without an assignment. The empty customer value "" denotes unassigned devices and must be explicitly granted for restricted credentials. Device customers are separate from workshop customers.

Scope Current business permissions Routes
devices.read devices.read List and detail
devices.manage devices.read, devices.manage Create, update, deactivate, archive
devices.check devices.read, devices.check Status check
devices.audit devices.read, audit.read Device audit
devices.dashboard devices.read, dashboard.read Dashboard

Assignments also restrict filters, status history, audit, counts and mutations. A supplied customer filter never expands access. Foreign and unknown devices both return 404. Reassignment requires access to the existing device and permission for the target customer; locations must belong to that customer. Device groups retain the existing global catalogue.

Credential administration

Administration is available only through trusted Python composition; there is no anonymous login/token endpoint or new administration menu.

# authenticated_admin_session comes from actual login, never HTTP JSON.
credential_id, token = authority.issue_integration(
    authenticated_admin_session, owner_user_id, "Device reader",
    scopes=["devices.read"], customer_ids=[approved_customer_id],
    expires_seconds=86400,
)

Issuers need current users.manage; the owner must hold every requested business permission. Integration credentials use at least 32 random bytes, store only a digest and expire after the explicitly chosen duration: one day by default, at most 365 days. Show the raw value only at issuance; never place it in logs, reports or URLs. authority.revoke(authenticated_admin_session, credential_id) revokes and audits the credential. A new authority for the same database can continue verifying valid integration credentials.

Alternatively, issue_session(authenticated_session, scopes=..., customer_ids=...) supports verified desktop composition, with an eight-hour maximum and validity only in the issuing process. The host must call revoke_sessions() on logout, user/database change and shutdown; the factory does not attach itself to UI lifecycle events. LOCAL checks enabled local login, lock and password state. Microsoft/Google SSO checks the enabled provider and unchanged linked identity. Persistent integration credentials are independent of desktop logout and local password flags; account activity, scope, permissions, expiry, revocation, licence and database binding still apply.

Routes and responses

Method/path Response
GET /api/devices Array of permitted devices; existing search/customer/location/group/status/active/archive filters
POST /api/devices 201, projected detail of created device
GET /api/devices/<device_id> Detail containing device, groups, status_history
PUT /api/devices/<device_id> 200, projected detail
POST /api/devices/<device_id>/deactivate ok, device_id
POST /api/devices/<device_id>/archive ok, device_id
POST /api/devices/<device_id>/status-check status, success, checked_at, last_successful_contact, response_code
GET /api/devices/<device_id>/audit Array of permitted audit metadata
GET /api/dashboard/devices Counts for accessible non-archived devices only; stale_minutes 1–525600, default 1440

HEAD and OPTIONS inherit route protection. Later undeclared routes deny access. Responses use explicit field lists: no credentials, device base URLs, raw device responses, internal errors or old/new audit payloads. Details have no embedded audit list. New business audits recursively remove known credential fields and raw responses; existing historical audits are not rewritten. API status checks persist no raw responses or error text and log no unfiltered upstream exceptions.

Writes and replay

POST creation and PUT require JSON. All five POST/PUT write-operation types require Idempotency-Key, containing 1–128 letters, digits, ., _, :, -. Keys are bound to credential, operation and device ID; a canonical input hash prevents conflicting reuse. Identical replay returns the stored result and changed input returns 409. Current permissions and device assignment are checked on replay too. Requests do not duplicate business changes or audits. Receipt, business mutation and audit commit in one transaction.

At most 1000 write receipts per credential; further writes return 429 and require administrative issuance of a new credential. Receipts are not automatically deleted or silently re-executed after a deadline. Credential issuance/revocation and business changes use verified user identity; business audit records additionally contain credential ID, correlation ID and device-api origin.

Unknown and read-only input fields are rejected; a body ID cannot override the path ID. Omitted credential fields are preserved on update. Changing the device base URL clears credential fields that were not explicitly supplied again, preventing old secrets from being sent to a new destination. URLs containing user info, query or fragment are invalid for new/revised API inputs.

Limits and errors

Requests are limited to a 64-KiB body, 8-KiB query and 2048 path characters. Lists use limit=100 by default (1–500) and offset=0 (0–100000), retaining array responses. Customer boundaries apply before pagination. Projected text fields are capped at 4096 characters and successful JSON responses at 2 MiB; excess responses return 503/response_size_limit. Dashboard counts are computed in the database independently of the list page. Each application permits at most eight concurrent device API requests. The minute window allows at most 240 requests per actual peer and 120 per credential/scope; status checks allow ten per credential/minute. Status checks have a maximum 30-second network timeout and 1-MiB device response; these API calls disable redirects and environment proxies. Authorization is repeated before mutations, repository access and successful responses. Completed external contacts or bytes already sent cannot be recalled.

Error object: ok=false, stable error, server-side requestId. Codes: 400 input/host/missing idempotency key, 401 missing Bearer with challenge, 403 invalid/revoked credential or missing permission, 404 unknown/foreign device, 409 idempotency conflict, 413 size, 415 media type, 426 missing HTTPS, 429 load/receipt limit, 503 unavailable verification/operation. No internal exception text. Responses set no-store, nosniff, framing/referrer/CSP protection and no general CORS allowance.

Migration and acceptance

Clients using role headers must explicitly migrate to new credentials, customer grants, write keys and reduced responses. There is no anonymous transition mode. Native device UI and outgoing device protocols receive no new HTTP login. Credential and audit schema are initialized by repeatable device migration 2 on SQLite and PostgreSQL. Existing PostgreSQL installations need the normal schema update and its established backup/rollback procedure; request handlers do not migrate databases.

Source anchors: api_identity.py, api_security.py, device_api_service.py, device_management_api.py, device_management.py; regressions: test_device_api_security.py, test_drivercard_api_security.py. Actual executed tests are recorded in the timestamped report. TLS/firewall/frozen/installed acceptance and actual third-party consumer inventory remain separate release steps.