Test stand authenticated controls and reports¶
These endpoints belong to the dedicated test stand, not the trading server or client REST API. Read-only monitoring, reports, and evidence remain accessible without a session. Start, cancel, and delete require a stand user session. The default standalone account is configured in test-stand/.env with STAND_AUTH_USERNAME and STAND_AUTH_PASSWORD; it has all three stand-control permissions. It is not a trading-server manager account. Restrict this destructive test environment to trusted operators.
Trading readiness after restart¶
Before scenario work continues after a trading-server restart, the stand waits
for GetTradingReadiness to report trading_ready: true. Connection closure or
replacement, connect/request timeouts, and socket/write errors are retried at
one-second intervals within the original configured server-start timeout. Each
attempt uses the TCP client's normal connection and manager-authentication path.
An AuthManager response of 503 LICENSE_NOT_ACTIVE is also retried: a v2 lease
can still be initializing even when the server's network listeners are available.
The stand respects the server's trading_ready result: a false value remains
a waiting state even when all legacy numeric status fields are valid, because
the server also checks the authenticated v2 lease. A true result with invalid
legacy status fields remains an inconsistent-response failure.
The deadline is not restarted by retries. Cancellation interrupts both an outstanding readiness read and retry backoff. Unsupported commands, malformed readiness responses, inconsistent flags, ordinary authentication failures, and unclassified programming/storage errors fail immediately. The stand does not automatically replay trading commands or change license binding/lease policy.
The success checkpoint and failure incident evidence include these additional
readiness diagnostics, without raw transport errors or authentication payloads:
| Field | Type | Description |
|---|---|---|
readinessRetries |
integer | Count of retries after transport or license-gated authentication failures. |
lastRetry |
object or null | Latest retry reason; null if no such failure occurred. |
lastRetry.sampledAt |
string | ISO timestamp of the latest retryable failure. |
lastRetry.kind |
string | connection_closed, connection_changed, connect_timeout, request_timeout, socket_error, write_error, or license_not_active. |
Readiness observations remain actual successful server replies; retryable errors
do not fabricate observations. For example, a timeout before any readiness reply
has the following complete evidence object:
{
"elapsedMs": 120000,
"observations": [],
"latest": null,
"readinessRetries": 2,
"lastRetry": {
"sampledAt": "2026-10-08T11:01:49.000Z",
"kind": "connection_changed"
}
}
Authentication and request security¶
Sign-in verifies the configured username/password locally, using constant-time comparisons of fixed-length digests. It makes no AuthManager request and does not depend on trading-server availability, managers, OTP, test-generated users, or restored trading data. Sessions contain only username and expiry; passwords are not retained in them. Trading-server restarts do not affect sign-in or sessions. A stand process restart clears all sessions and reloads credentials.
Required environment fields: STAND_AUTH_USERNAME (1–128 ASCII letters/digits or _.@-) and STAND_AUTH_PASSWORD (12–256 characters). No hardcoded default password exists. Without valid credentials the normal stand process refuses to start. Add these variables to the existing .env without overwriting PostgreSQL settings; keep the file mode 0600 and outside Git. Restart the stand after changing credentials.
All modifying endpoints, including login/logout, require the exact Origin header. The expected value is STAND_PUBLIC_ORIGIN when set, otherwise the request protocol and Host. Sec-Fetch-Site: cross-site is rejected. Configure STAND_PUBLIC_ORIGIN=https://stand.example behind a TLS proxy, without a trailing slash, and restrict direct access to the HTTP port. Never send credentials over public plain HTTP.
The browser receives an opaque stand_session cookie with Path=/, HttpOnly, SameSite=Strict, and Max-Age=28800. Secure is added on HTTPS or with an HTTPS public origin. Modifying clients send this cookie and the matching Origin. Authentication status responses are marked Cache-Control: no-store.
POST /api/auth/login¶
JSON request fields:
| Field | Type | Required | Description |
|---|---|---|---|
| username | string | Yes | Nonempty standalone username, at most 128 characters. |
| password | string | Yes | Nonempty password, at most 256 characters. |
Request example:
{ "username": "admin", "password": "<stand-password>" }
Complete success response (200; also sets the session cookie):
{
"authenticated": true,
"user": { "username": "admin", "expiresAt": "2026-10-02T02:00:00.000Z" }
}
authenticated is boolean. user contains username (string) and expiresAt (ISO-8601 UTC timestamp). Login attempts are limited to five per IP per minute. Error responses contain only error (string code): 400 INVALID_CREDENTIALS_FORMAT, 401 INVALID_CREDENTIALS, 403 INVALID_ORIGIN, 429 LOGIN_RATE_LIMITED with Retry-After: 60, or 503 SESSION_CAPACITY_REACHED / AUTH_NOT_CONFIGURED (credentials absent if this module is embedded without the normal startup validation). The request body limit is 4096 bytes; oversized requests receive the framework's 413 response. Neither password nor a trading-manager token is returned in the JSON response.
GET /api/auth/session¶
No request fields. A valid cookie returns the same complete 200 response shape as login. Without a valid cookie:
{ "authenticated": false, "user": null }
POST /api/auth/logout¶
No request body fields. Requires a valid cookie and Origin. Invalidates the current session and clears its cookie. Complete 200 response:
{ "authenticated": false, "user": null }
Protected mutations return 401 {"error":"AUTHENTICATION_REQUIRED"} without a valid session, or 403 {"error":"INVALID_ORIGIN"} for an invalid Origin. Authorization is enforced by the server, not only the UI.
Run controls¶
Scenario selection and one-click start¶
In the live console, the Scenario native select is populated from GET /api/scenarios; the separate Snapshot select is unchanged. Choose the scenario and snapshot, then press Run test once to start. The button calls the existing POST /api/scenarios/:id/run endpoint with the selected scenario ID and snapshot ID; no additional confirmation step is inserted. While the request is outstanding its label is Starting….
The button remains disabled until the stand user is signed in and a scenario and snapshot are available. It is also disabled while a start request is outstanding or another run is active. If the scenario list is empty, the select shows No scenarios available. These UI guards do not replace server-side authentication and authorization.
POST /api/scenarios/:id/run¶
Requires standalone user authentication and Origin. id is the scenario identifier. Optional JSON field snapshotId (string) selects a snapshot; omitted uses the configured default. A successful request returns 202 and a compact run summary. Unknown scenarios return 404 {"error":"SCENARIO_NOT_FOUND"}. Existing runner/storage failures retain their existing HTTP behavior.
Run-summary fields:
| Field | Type | Description |
|---|---|---|
| id | string | Run identifier. |
| scenarioId, scenarioName | string | Scenario identity and display name. |
| status | string | queued, preparing, running, passed, failed, or cancelled. |
| requestedAt | string | ISO-8601 UTC request time. |
| startedAt, finishedAt | string, optional | ISO-8601 UTC lifecycle times. |
| snapshotId, snapshotName | string, optional | Snapshot identity and display name. |
| testedBuild | object, optional | version and buildDate, both strings. |
| error | string, optional | Compact run error; full evidence remains separate. |
| revision | integer | Durable journal revision. |
| logCount, assertionCount, passed, failed | integer | Saved log and check counters. |
| levels | object | Integer counts keyed by info, success, warning, error. |
| sections | object | Section names mapped to { "passed": integer, "failed": integer }. |
| reportReady | boolean | Derived report availability. |
Complete response example (optional absent fields are omitted on the wire):
{
"id": "2026-10-01T18-09-56-520Z-basic-regression-2e03df1f",
"scenarioId": "basic-regression",
"scenarioName": "Basic trading and finance regression",
"status": "queued",
"requestedAt": "2026-10-01T18:09:56.520Z",
"snapshotId": "clean",
"revision": 3,
"logCount": 1,
"assertionCount": 0,
"passed": 0,
"failed": 0,
"levels": { "info": 1, "success": 0, "warning": 0, "error": 0 },
"sections": {},
"reportReady": false
}
POST /api/runs/:id/cancel¶
Requires authentication and Origin. No body fields. Complete 202 response:
{ "cancelled": true }
The boolean acknowledges cancellation was requested, not that all cleanup has finished. Noncancellable or nonexistent runs return 409 {"error":"RUN_NOT_CANCELLABLE"}.
DELETE /api/runs/:id¶
Requires authentication and Origin. No body fields. Only terminal runs with completed reports and no ongoing execution/report task may be removed. Complete 200 response:
{
"deleted": true,
"id": "2026-10-01T18-09-56-520Z-basic-regression-2e03df1f",
"evidenceRetained": true
}
deleted and evidenceRetained are booleans; id is the removed run identifier. Errors contain only error: 404 RUN_NOT_FOUND, 409 RUN_BUSY, or 503 RUN_DELETE_FAILED.
Removal hides the run from history and evidence/report endpoints. It deletes the PostgreSQL run/entry index transactionally and records a deletion tombstone. If PostgreSQL is unavailable, the durable local deletion takes effect and index cleanup retries in the background. Original artifact files are not erased. deleted.json remains in the artifact directory with this complete format:
{
"id": "2026-10-01T18-09-56-520Z-basic-regression-2e03df1f",
"username": "admin",
"deletedAt": "2026-10-01T18:30:00.000Z"
}
Recovery skips directories containing this marker. The fields are id (string), username (string), and deletedAt (ISO-8601 UTC timestamp). Older internal deletion markers containing a positive integer managerId instead of username remain readable and are labeled legacy-manager-<id> in the rebuilt index; original markers are not rewritten. This UI action is labeled Hide and does not reclaim artifact disk space. Restoring a hidden run requires an administrator to reconcile both local and PostgreSQL tombstones offline; no restore endpoint is exposed.
GET /api/runs/hidden¶
Requires a stand session. This read-only endpoint does not require Origin. Lists hidden runs whose artifact directories are retained, including remnants of interrupted permanent removal discovered during startup recovery. Results become available as deletion markers are recovered; loading history is not blocked.
| Query field | Type | Required | Description |
|---|---|---|---|
| limit | integer | No | Page size, 1–100; default 25. |
| after | string | No | Exclusive run-ID cursor from nextAfter. IDs are sorted lexicographically ascending. |
Complete 200 response:
{
"items": [
{
"id": "2026-10-01T18-09-56-520Z-basic-regression-2e03df1f",
"username": "admin",
"deletedAt": "2026-10-01T18:30:00.000Z"
}
],
"hasMore": false,
"nextAfter": null
}
items is an array of objects containing id, username and deletedAt, all
strings. hasMore is boolean; nextAfter is the last item ID when more items
exist, otherwise null. Authentication failure returns 401
{"error":"AUTHENTICATION_REQUIRED"}. An invalid page limit returns HTTP 400
through the stand's standard pagination error handler.
POST /api/runs/:id/purge¶
Requires a stand session and matching Origin. Permanently removes one completed
run's artifact directory, including its reports, journals and evidence. It can
target a visible completed run or a retained hidden run. The UI labels this
Delete files permanently and offers a paginated Hidden runs list for
previously hidden evidence. Hide and permanent deletion execute immediately on
click, without browser confirmation dialogs or manual ID entry. The interface
automatically sends the matching confirmRunId; server-side validation remains
required. Permanent deletion cannot be undone.
| JSON field | Type | Required | Description |
|---|---|---|---|
| confirmRunId | string | Yes | Must exactly match the run ID in the URL. |
Complete request example:
{ "confirmRunId": "2026-10-01T18-09-56-520Z-basic-regression-2e03df1f" }
Complete 200 response:
{
"deleted": true,
"id": "2026-10-01T18-09-56-520Z-basic-regression-2e03df1f",
"evidenceRetained": false,
"auditMarkerRetained": true
}
deleted, evidenceRetained and auditMarkerRetained are booleans; id is a
string. Success means the artifact directory has been removed. A small audit
marker remains outside that directory, in artifacts/.deletions/<id>.json,
containing id, username, deletedAt and purged: true. This durable marker
records purge intent and prevents remnants from being imported after interrupted
cleanup; it is not proof that every file was removed if the request failed.
Active runs, runs without completed reports, competing deletion and ongoing report generation are rejected. The target must be an exact child of the configured artifact root; traversal and directory symlinks are rejected. Index deletion must commit before file removal. If it cannot commit, files remain and the run may already be hidden. After interrupted file removal, recovered remnants remain hidden and can be purged again. There is no bulk/root-directory purge.
Complete application error responses contain only error:
- 400
{"error":"RUN_CONFIRMATION_REQUIRED"}: missing or mismatched confirmation. - 401
{"error":"AUTHENTICATION_REQUIRED"}: no valid session. - 403
{"error":"INVALID_ORIGIN"}: missing or mismatched Origin. - 404
{"error":"RUN_NOT_FOUND"}: unknown run or invalid target path. - 409
{"error":"RUN_BUSY"}: active/incomplete run or conflicting operation. - 503
{"error":"RUN_PURGE_FAILED"}: index or filesystem failure. Inspect retained markers/files before retrying; removal may be partial.
Completed-history startup recovery¶
Completed v3 runs can use a derived history-checkpoint.json cache. Startup
validates its checksum, contiguous segment ranges, complete inventory, file sizes
and modification/change timestamps, then verifies the final segment's content
hash and journal-head summary. Missing, corrupt or stale caches fall back to a
full journal scan and are refreshed after successful recovery. Active runs are
never recovered solely from this completed-run cache.
Completed legacy v2 runs also receive a checkpoint. It validates the record directory's size/modification/change timestamps, the head record's metadata, content hash and summary. This avoids enumerating all individual JSON records on each restart. Directory-entry changes or a changed head invalidate the cache and trigger the existing full filename-range/head validation. Initial recovery of an older run without a checkpoint still performs its usual work once.
This optimization is not a full historical integrity audit: older segment contents are not rehashed during the fast path. Indexed evidence reads still verify their existing content hashes. Keep artifact directories private to the stand service. For legacy v2 checkpoints, older record contents are not inspected at startup either; they retain the existing indexed-read checksum verification.
The existing storage.recovery shape is unchanged. During full v3 scans,
processedEntries and totalEntries count journal records and phase is scan;
legacy migration uses import. Directory counts include hidden runs, which are
skipped without reading their journals. The UI displays a preparation message
instead of misleading entries 0/0 while counts are not yet available. New test
execution remains available during background history recovery.
Section-specific check pages¶
GET /api/runs/:id/assertions adds optional section (nonempty string, maximum 200 characters), an exact section-name match. Existing fields: limit (integer 1–200, default 100), after (nonnegative integer sequence, default 0), failedOnly (true/false), and tail (true selects the latest unfiltered sequence window before filtering). The section filter is supported only for assertion pages; invalid filters return 400 {"error":"INVALID_FILTER"}. Invalid numeric pagination returns the existing framework 400 response; missing runs return 404 {"error":"RUN_NOT_FOUND"}; index failures return 503 with error: "RUN_INDEX_UNAVAILABLE" and storage as below.
Example URL: /api/runs/<id>/assertions?limit=50&after=0&failedOnly=false§ion=Recovery.
Response fields: items (array of check previews), nextAfter (integer last returned sequence, or the supplied cursor), hasMore (boolean), and storage (status object). Each item has sequence and revision (integers), name and section (strings), passed and hasDetails (booleans), and detailUrl (string). Fetch detailUrl only to retrieve the original full check, unchanged and untruncated.
storage fields: mode (string), pendingRuns, pendingRecords, pendingWrites (integer counts), indexReady (boolean), error (string or null), and recovery. Recovery contains state (loading, ready, failed), totalRuns, loadedRuns, processedEntries, totalEntries (integers), currentDirectory and error (string or null), and phase (scan, import, report, done).
Complete response example:
{
"items": [{
"sequence": 12, "revision": 26, "name": "Recovery: portfolio restored",
"passed": true, "section": "Recovery", "hasDetails": true,
"detailUrl": "/api/runs/example-run/entries/assertion/12"
}],
"nextAfter": 12,
"hasMore": false,
"storage": {
"mode": "postgres-with-local-journal", "pendingRuns": 0,
"pendingRecords": 0, "pendingWrites": 0, "indexReady": true, "error": null,
"recovery": {
"state": "ready", "totalRuns": 1, "loadedRuns": 1, "currentDirectory": null,
"phase": "done", "processedEntries": 0, "totalEntries": 0, "error": null
}
}
}
Interactive reports¶
GET /api/runs/:id/report serves bounded HTML with section PASS/FAIL charts, count/percentage scaling, sorting, filtering, section drill-down, observed-order distribution, financial search/mismatch filtering, on-demand full JSON, and Copy JSON. No external chart service/CDN or periodic REST polling is used. Old derived reports upgrade on first open. Original checks and journals are not rewritten. A section with no checks is not a PASS; pass percentage is not engine coverage. Order counts are deduplicated observed artifacts, not current positions; SO/closure counts overlap order categories. Financial currencies are not aggregated and display filtering does not change test assertions.
The derived report-summary.json artifact now has schemaVersion: 2. All fields: schemaVersion (integer), id (string), passed, failed, warnings (integer check/log counts), sections (section-name object of passed/failed integers), and evidence. Evidence contains integer counters market, buy, sell, closed, so, pending, finance, plus warnings (array of unavailable-artifact messages). Complete example:
{
"schemaVersion": 2,
"id": "example-run",
"passed": 100,
"failed": 0,
"warnings": 2,
"sections": { "Recovery": { "passed": 100, "failed": 0 } },
"evidence": {
"market": 20, "buy": 12, "sell": 8, "closed": 20,
"so": 5, "pending": 3, "finance": 4, "warnings": []
}
}