feat(labs): describe the lab task contract and the provisioner port

This commit is contained in:
shira committed 2026-10-11 15:40:14 +03:00
1 parent 3de226b16c
commit 9fdaa62b9b
91 files changed
+19262 -155

No files matched your search

+721
View File
@@ -0,0 +1,721 @@
openapi: 3.2.0
info:
title: Lincodex Lab Provisioner API
version: 0.1.0
description: |-
Internal API of the lab provisioner `labd`. Only the Go backend calls it;
it is never exposed to browsers or to the public network. `labd` is the
only component that talks to the LXD API on the app host: the backend
never receives the LXD socket, an LXD certificate, or a node address.
Transport and authentication: `labd` listens on a private address of the
app host that only the backend network reaches and serves HTTPS (TLS
1.3). Every operation except the health routes requires `Authorization:
Bearer <token>`; the token is a shared random secret of at least 32
characters that comes from the deployment secret store, never from this
repository. A missing or wrong token answers 401 `unauthenticated`. Plain
HTTP exists only behind an explicit development switch.
Data minimization: a lab request carries only a template reference, a
variant seed, and a lifetime. It has no candidate, account, attempt,
task, or company identifier. The lab ID is a random UUID chosen by the
backend for idempotency. Responses never carry node addresses, MAC
addresses, bridge or instance names, keys, or passwords: the backend
reaches a node only through a console token and learns a lab's state
only through these operations.
Lifecycle: CreateLab reserves capacity and answers immediately with the
lab in `provisioning`; `labd` clones the nodes of the template from
prepared snapshots, connects them with per-lab L2-only bridges, boots
them, and waits until their management ports answer. The caller polls
GetLab until `ready`. Every lab has a fixed `expires_at`; `labd` deletes
it at that time even after a restart of its own process, and DeleteLab
deletes it earlier. A deleted lab stays readable as `deleted` for a
bounded time, then answers 404.
Capacity: the number of concurrent labs follows the host memory budget of
`labd`. A request that does not fit answers 503 `lab_pool_busy` with
Retry-After and stores nothing; it is a capacity signal, not an
infrastructure failure. `labd` does not queue labs.
servers:
- url: /
security:
- bearerAuth: []
paths:
/healthz:
get:
operationId: GetLabdHealthz
summary: Check whether the lab provisioner process is responding.
security: []
tags:
- health
responses:
'200':
description: The process is responding.
content:
application/json:
schema:
$ref: '#/components/schemas/LabdHealthResponse'
default:
$ref: '#/components/responses/Problem'
/readyz:
get:
operationId: GetLabdReadyz
summary: Check whether the provisioner can create and delete labs.
description: Ready means that the lab records were loaded, the startup reconciliation with LXD finished, the LXD API answered the latest probe, and the process is not draining. A provisioner without free capacity is still ready; capacity is reported by CreateLab.
security: []
tags:
- health
responses:
'200':
description: The provisioner is ready.
content:
application/json:
schema:
$ref: '#/components/schemas/LabdReadinessResponse'
'503':
description: The provisioner is not ready or is draining.
content:
application/json:
schema:
$ref: '#/components/schemas/LabdReadinessResponse'
default:
$ref: '#/components/responses/Problem'
/v1/labs/{lab_id}:
parameters:
- $ref: '#/components/parameters/LabId'
put:
operationId: CreateLab
summary: Create a lab from a template and a variant seed.
description: |-
Idempotent by `lab_id`:
- a new ID that fits the capacity reserves it, stores the lab, and answers 202 with `state: provisioning`; the nodes are cloned and booted in the background;
- the same ID with the same payload answers 200 with the current state of that lab, including `deleted` or `failed`, and never creates a second one;
- the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing;
- a new ID that does not fit the memory budget or the lab limit, or arrives while the provisioner is draining, answers 503 `lab_pool_busy` with Retry-After; nothing is stored, so the caller retries with the same ID.
Payloads are compared by a SHA-256 fingerprint of the decoded request.
An unknown template or template version, or a lifetime above the
configured maximum, answers 400 `validation_failed` with a pointer such
as `/template_id` or `/ttl_seconds`.
The lab is deleted at `expires_at` = creation time + `ttl_seconds`, also
when it is still provisioning. A lab that fails to provision or does not
answer within the provisioning timeout becomes `failed` and its
resources are deleted; its capacity returns when they are gone.
A record of a deleted or failed lab is kept for a bounded retention time;
after it, the ID is unknown again and a CreateLab with it starts a new
lab.
tags:
- labs
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/LabCreateRequest'
examples:
two_routers:
summary: A lab of a networking template for one attempt item
value:
template_id: mikrotik-ospf-pair
template_version: 1
seed: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
ttl_seconds: 3600
responses:
'200':
description: A lab with this ID and the same payload already exists.
content:
application/json:
schema:
$ref: '#/components/schemas/LabStatus'
'202':
description: The lab was accepted and is provisioning.
content:
application/json:
schema:
$ref: '#/components/schemas/LabStatus'
examples:
provisioning:
summary: A lab that is being cloned and booted
value:
lab_id: 2f1c7a52-0d3e-4b8e-9b61-3c7b1f2e9a40
state: provisioning
template_id: mikrotik-ospf-pair
template_version: 1
created_at: '2026-10-11T09:00:00Z'
expires_at: '2026-10-11T10:00:00Z'
nodes:
- name: r1
kind: mikrotik
- name: r2
kind: mikrotik
'503':
$ref: '#/components/responses/LabPoolBusy'
default:
$ref: '#/components/responses/Problem'
get:
operationId: GetLab
summary: Read the state of a lab.
description: Answers 404 `not_found` for an ID the provisioner does not hold, including a lab whose `deleted` record outlived its retention time. The response never contains an address, a key, or an LXD object name.
tags:
- labs
responses:
'200':
description: The current state of the lab.
content:
application/json:
schema:
$ref: '#/components/schemas/LabStatus'
default:
$ref: '#/components/responses/Problem'
delete:
operationId: DeleteLab
summary: Delete a lab before its timer.
description: 'Marks the lab for deletion and answers 202 with `state: deleting`; the provisioner removes its instances and bridges in the background and retries until LXD confirms that they are gone, also across its own restarts. Deleting a lab that is already `deleting` or `deleted` answers 200 with its state and changes nothing. An unknown ID answers 404 `not_found`.'
tags:
- labs
responses:
'200':
description: The lab was already being deleted or is deleted.
content:
application/json:
schema:
$ref: '#/components/schemas/LabStatus'
'202':
description: The lab is being deleted.
content:
application/json:
schema:
$ref: '#/components/schemas/LabStatus'
default:
$ref: '#/components/responses/Problem'
/v1/labs/{lab_id}/console-tokens:
parameters:
- $ref: '#/components/parameters/LabId'
post:
operationId: CreateLabConsoleToken
summary: Issue a short-lived console token for one node of a ready lab.
description: |-
The token lets the console gateway of the backend attach to the serial
console of one node. It is random, single-use, bound to the lab and the
node, and valid for at most 120 seconds; `labd` keeps only its SHA-256
digest in memory, so a restart invalidates every unused token. The token
is never a node password or an SSH key, and the response carries no node
address.
Attaching: the gateway opens a WebSocket to `attach_path` on the same
`labd` origin with the service bearer token and sends the console token
in the `X-Lab-Console-Token` header. The WebSocket attach is described
here as the planned interface; until it is implemented, `labd` answers
the attach path with 501 and issuing a token changes nothing else.
A lab that is not `ready` answers 409 `state_conflict`; an unknown node
answers 400 `validation_failed` with the pointer `/node`.
tags:
- consoles
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/ConsoleTokenRequest'
responses:
'201':
description: The token was issued.
headers:
Cache-Control:
description: The token must not be stored by any cache.
required: true
schema:
type: string
enum:
- no-store
content:
application/json:
schema:
$ref: '#/components/schemas/ConsoleToken'
default:
$ref: '#/components/responses/Problem'
/v1/labs/{lab_id}/check:
parameters:
- $ref: '#/components/parameters/LabId'
post:
operationId: CheckLab
summary: Run the checker of the template against the nodes of a ready lab.
description: |-
The checker of the template connects from the host side of the lab
management bridge to the nodes (SSH or the RouterOS API) and evaluates
the criteria of the variant that the seed selected. It only reads the
node state and never changes it, so a repeated call is harmless; the
result is not stored by `labd`. The call is synchronous and bounded by
the check timeout of the provisioner.
The result is checker state for the backend only: the backend scores the
lab answer with it and never forwards it to the candidate.
A lab that is not `ready` answers 409 `state_conflict`. When the
checker cannot reach a node or the template has no working checker, the
provisioner answers 503 `lab_unavailable`: nothing was evaluated, and the
outcome is never a failed check.
tags:
- checks
responses:
'200':
description: The checker evaluated every criterion.
content:
application/json:
schema:
$ref: '#/components/schemas/LabCheckResult'
default:
$ref: '#/components/responses/Problem'
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
description: 'Shared random service token sent as `Authorization: Bearer <token>` over TLS. `labd` compares it in constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user tokens.'
responses:
Problem:
description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode.
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
validation_failed:
summary: The template is unknown
value:
type: urn:lincodex:problem:validation_failed
title: Request validation failed
status: 400
code: validation_failed
detail: One or more request fields are invalid.
errors:
- in: body
pointer: /template_id
code: invalid
message: The value does not match the contract.
state_conflict:
summary: The lab is not ready
value:
type: urn:lincodex:problem:state_conflict
title: State conflict
status: 409
code: state_conflict
detail: The lab is not ready.
lab_unavailable:
summary: The checker could not reach a node
value:
type: urn:lincodex:problem:lab_unavailable
title: Lab unavailable
status: 503
code: lab_unavailable
detail: The lab could not be evaluated. Nothing was checked.
LabPoolBusy:
description: The lab does not fit the memory budget or the lab limit of the provisioner, or the provisioner is draining; code lab_pool_busy. Nothing was stored and no capacity was reserved. Retry with the same lab ID after Retry-After.
headers:
Retry-After:
description: Number of seconds to wait before retrying the request.
required: true
schema:
type: integer
format: int32
minimum: 0
maximum: 3600
example: 30
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
examples:
lab_pool_busy:
summary: No capacity for another lab
value:
type: urn:lincodex:problem:lab_pool_busy
title: Lab pool busy
status: 503
code: lab_pool_busy
detail: No capacity for another lab. Retry later with the same lab ID.
schemas:
ProblemCode:
type: string
description: |-
Stable error code of the lab provisioner API. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.
- validation_failed (400): parameters or body do not match the contract or a semantic rule, such as an unknown template or node; `errors` points at the fields.
- unauthenticated (401): the bearer token is missing or wrong.
- not_found (404): the route or the lab does not exist.
- method_not_allowed (405): the route does not support the method.
- state_conflict (409): the lab is not in a state that allows the operation, for example a console token or a check for a lab that is not ready.
- payload_too_large (413): the request body exceeds the limit.
- unsupported_media_type (415): the request Content-Type is not accepted.
- idempotency_key_reused (422): the lab ID was already used with a different payload.
- internal (500): unexpected server error.
- not_implemented (501): the route is described but not implemented yet, such as the console attach.
- lab_pool_busy (503): the lab does not fit the capacity or the provisioner is draining; see Retry-After.
- lab_unavailable (503): LXD or a node could not be reached, so nothing was done or evaluated. It is an infrastructure failure, never a failed check.
The Problem shape is the api/core shape; only this enum is specific to the lab provisioner.
enum:
- validation_failed
- unauthenticated
- not_found
- method_not_allowed
- state_conflict
- payload_too_large
- unsupported_media_type
- idempotency_key_reused
- internal
- not_implemented
- lab_pool_busy
- lab_unavailable
ProblemFieldLocation:
type: string
description: Part of the request that contains the invalid field.
enum:
- body
- query
- path
- header
- cookie
ProblemFieldError:
type: object
description: One reason why a request field or parameter is invalid.
additionalProperties: false
required:
- in
- pointer
- code
- message
properties:
in:
$ref: '#/components/schemas/ProblemFieldLocation'
pointer:
type: string
maxLength: 1024
pattern: ^(/([^~/]|~[01])*)*$
description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/ttl_seconds`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/lab_id`.
code:
type: string
minLength: 1
maxLength: 64
pattern: ^[a-z][a-z0-9_]*$
description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.
message:
type: string
minLength: 1
maxLength: 500
description: Fixed English message that never echoes the submitted value.
Problem:
type: object
description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the lab provisioner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values.
additionalProperties: false
required:
- type
- title
- status
- code
properties:
type:
type: string
format: uri-reference
maxLength: 256
description: URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.
title:
type: string
minLength: 1
maxLength: 200
description: Short, fixed English summary of the problem type. It does not change between occurrences.
status:
type: integer
format: int32
minimum: 400
maximum: 599
description: HTTP status code generated by the origin server.
code:
$ref: '#/components/schemas/ProblemCode'
detail:
type: string
maxLength: 1000
description: Safe English explanation of this occurrence. It never contains internal error text or request values.
instance:
type: string
format: uri-reference
maxLength: 2048
description: URI reference that identifies this occurrence, when one exists.
trace_id:
type: string
minLength: 1
maxLength: 128
pattern: ^[A-Za-z0-9._-]+$
description: Request identifier of the call when the caller propagated one; it is not a secret.
errors:
type: array
maxItems: 100
description: Field-level reasons for validation_failed. Other codes omit it.
items:
$ref: '#/components/schemas/ProblemFieldError'
LabdHealthResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ok
LabdReadinessResponse:
type: object
additionalProperties: false
required:
- status
properties:
status:
type: string
enum:
- ready
- not_ready
LabState:
type: string
description: |-
State of a lab.
- provisioning: capacity is reserved and the nodes are being cloned, connected, and booted.
- ready: every node answers on its management port; console tokens and checks are allowed.
- deleting: the timer ended, DeleteLab was called, or provisioning failed; the instances and bridges are being removed.
- deleted: every instance and bridge of the lab is gone and its capacity is free.
- failed: provisioning failed or timed out, or the provisioner restarted while provisioning; `failure_reason` says which. Its resources are removed as for `deleting` and the capacity returns once they are gone; create a new lab with a new ID.
Adding a value is a contract change.
enum:
- provisioning
- ready
- deleting
- deleted
- failed
TemplateId:
type: string
minLength: 1
maxLength: 48
pattern: ^[a-z0-9][a-z0-9-]{0,47}$
description: Identifier of a lab template known to the provisioner, such as `mikrotik-ospf-pair`. Templates are part of the provisioner build; the request never carries node images, commands, or configuration.
LabFailureReason:
type: string
description: |-
Why a lab failed. None of the reasons depends on the person who uses the lab.
- provisioning_failed: LXD refused or failed an operation of the provisioning.
- provisioning_timed_out: a node did not answer on its management port within the provisioning timeout.
- interrupted: the provisioner process stopped while the lab was provisioning.
enum:
- provisioning_failed
- provisioning_timed_out
- interrupted
NodeName:
type: string
minLength: 1
maxLength: 15
pattern: ^[a-z][a-z0-9-]{0,14}$
description: Name of a node inside its template, such as `r1` or `srv`. It is the same in every lab of the template and is not an LXD instance name or a host name.
NodeKind:
type: string
description: |-
Guest system of a node.
- mikrotik: a MikroTik Cloud Hosted Router VM; its console is RouterOS.
- ubuntu: a small Ubuntu VM; its console is a Linux login.
Adding a value is a contract change.
enum:
- mikrotik
- ubuntu
LabNode:
type: object
description: A node of a lab by its template name and kind. It never carries an address, a MAC address, an instance name, or a credential.
additionalProperties: false
required:
- name
- kind
properties:
name:
$ref: '#/components/schemas/NodeName'
kind:
$ref: '#/components/schemas/NodeKind'
LabStatus:
type: object
description: State of a lab after one call. It never contains the seed, a node address, a key, a password, or an LXD object name.
additionalProperties: false
required:
- lab_id
- state
- template_id
- template_version
- created_at
- expires_at
- nodes
properties:
lab_id:
type: string
format: uuid
state:
$ref: '#/components/schemas/LabState'
template_id:
$ref: '#/components/schemas/TemplateId'
template_version:
type: integer
format: int32
minimum: 1
maximum: 10000
created_at:
type: string
format: date-time
ready_at:
type: string
format: date-time
description: Time the lab became `ready`; absent before.
expires_at:
type: string
format: date-time
description: Time the provisioner deletes the lab. It never moves, also not across restarts of the provisioner.
deleted_at:
type: string
format: date-time
description: Time the last resource of the lab was removed; absent before.
failure_reason:
$ref: '#/components/schemas/LabFailureReason'
nodes:
type: array
minItems: 1
maxItems: 8
description: Nodes of the template in template order.
items:
$ref: '#/components/schemas/LabNode'
LabCreateRequest:
type: object
description: A lab of one template variant. It has no field for a candidate, account, attempt, task, or company.
additionalProperties: false
required:
- template_id
- template_version
- seed
- ttl_seconds
properties:
template_id:
$ref: '#/components/schemas/TemplateId'
template_version:
type: integer
format: int32
minimum: 1
maximum: 10000
description: Version of the template. The provisioner refuses a version it does not hold, so a lab always matches the variant the backend served.
seed:
type: string
minLength: 64
maxLength: 64
pattern: ^[0-9a-f]{64}$
description: 'Variant seed: 32 random bytes in lowercase hex chosen by the backend for the item instance. The template renders the variant configuration of every node and the checker criteria from it. It is never returned by the provisioner.'
ttl_seconds:
type: integer
format: int32
minimum: 300
maximum: 14400
description: Lifetime of the lab from its creation. The provisioner refuses a value above its configured maximum.
ConsoleTokenRequest:
type: object
additionalProperties: false
required:
- node
properties:
node:
$ref: '#/components/schemas/NodeName'
ConsoleToken:
type: object
description: 'Single-use console token for one node. The token is a secret of the console gateway: it is never logged, stored by the backend, or passed to a browser.'
additionalProperties: false
required:
- token
- node
- expires_at
- attach_path
properties:
token:
type: string
minLength: 43
maxLength: 43
pattern: ^[A-Za-z0-9_-]{43}$
description: 32 random bytes in unpadded base64url.
node:
$ref: '#/components/schemas/NodeName'
expires_at:
type: string
format: date-time
attach_path:
type: string
maxLength: 128
pattern: ^/v1/labs/[0-9a-f-]{36}/console$
description: Path of the WebSocket attach on the provisioner origin.
CriterionId:
type: string
minLength: 1
maxLength: 32
pattern: ^[a-z0-9][a-z0-9_-]{0,31}$
description: Opaque identifier of a checker criterion of the template.
CriterionResult:
type: object
additionalProperties: false
required:
- id
- passed
properties:
id:
$ref: '#/components/schemas/CriterionId'
passed:
type: boolean
LabCheckResult:
type: object
description: 'Result of one check: whether each criterion of the variant holds on the nodes. It carries no node output, address, or configuration text.'
additionalProperties: false
required:
- lab_id
- checked_at
- score
- max_score
- criteria
properties:
lab_id:
type: string
format: uuid
checked_at:
type: string
format: date-time
score:
type: integer
format: int32
minimum: 0
maximum: 50
description: Number of passed criteria.
max_score:
type: integer
format: int32
minimum: 1
maximum: 50
description: Number of criteria.
criteria:
type: array
minItems: 1
maxItems: 50
items:
$ref: '#/components/schemas/CriterionResult'
parameters:
LabId:
name: lab_id
in: path
required: true
description: Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not encode a candidate, attempt, or task identifier.
schema:
type: string
format: uuid