Lewati ke isi

API dan Secure-Proctoring Contract — OS-v1.0

Last verified: 2026-09-12. Target behavior specification; bukan served API certification. Acuan: baseline, data model, authorization, acceptance.

1. Status kontrak dan freeze per slice

openapi-v1.yaml adalah draft machine-readable yang dikembangkan dari kontrak lama; tidak boleh dianggap semua routes/DTO sudah implemented atau lengkap. runtime-route-inventory.yaml mengunci 88 operasi yang ditemukan dari schema FastAPI pada 2026-09-13, tetapi bukan pengganti DTO/security/error contract. Dokumen ini menetapkan behavior dan coverage target. RM-010 menyediakan contract generation/drift gates. Sebelum story READY, endpoint story tersebut harus punya DTO lengkap, response/error, auth dan contract tests; sebelum I7, seluruh release surface harus tercakup.

Gunakan existing /runner/sessions untuk scheduled sessions dan /runner/attempts untuk pengerjaan; jangan menyalin /exam-sessions dari paket dengan dua makna. Endpoint target baru di bawah bukan hasil runtime discovery. Path final yang berubah harus dimapping dan memperbarui OpenAPI/client sebelum code merge.

2. Envelope, security dan command semantics

  • Prefix /api/v1, UTC ISO8601, canonical English names, UI Bahasa Indonesia.
  • Structured error: code, message, correlation_id, safe details. Authentication 401; forbidden visible action 403; invisible resource 404; state/revision/key collision 409; expired one-time authorization 410 bila aman; validation 422; rate limit 429; unavailable dependency 503.
  • Schema whitelist: reject authoritative fields score/deadline/org/role dari participant; typed answer; request/body/query size limits disepakati pada OP-01. Tidak eval input matematika.
  • Browser staff/runner sesi terpisah: HttpOnly/Secure cookie, CSRF+origin check pada mutasi termasuk login binding sesuai desain; native launch authorization terpisah. Temp MFA credential hanya untuk verify/enroll challenge, tidak API bisnis.
  • Privileged MFA + recovery codes/session revocation diuji; RBAC memakai live membership/scoped assignment, bukan token roles stale.
  • Idempotency-Key wajib start, save, submit, recover, force-submit, scoring finalize/revision, freeze/publish/withdraw, export creation dan evidence completion. Key scoped tenant+principal+command+resource, request fingerprint persisted, result commit atomik.
  • Same key/same payload: original safe response setelah revalidasi current auth; same key/different payload: 409 IDEMPOTENCY_CONFLICT. Parallel same-key tidak menjalankan side effect dua kali. Retention idempotency mencakup retry lifecycle yang disetujui OP-01; no Redis-only dedupe.
  • Kontrak tidak menjanjikan exactly-once network delivery; outbox at-least-once + idempotent consumer memberi durable business effect.
  • Pagination cursor stabil untuk collections; authorization berlaku juga pada export/realtime reconnect/read models.

3. Coverage API per bounded context

Semua mutasi privileged memerlukan role/scope + audit; required reason untuk intervensi, override dan publikasi koreksi.

Context / story Existing atau target family Contract wajib sebelum story READY
Identity OS-020/RM-002 Existing /auth/login, /auth/mfa/verify; target /auth/logout, /auth/session, MFA enrollment/recovery Separate staff/participant cookie/token kinds; bootstrap/recovery; session expiry/revocation; negative CSRF
Competition OS-021/022 Existing /events, participants/enrollment families; target category/round/exam/room assignment Create/list/detail/update/clone/archive semantics, dry-run import report, uniqueness, overlap, freeze restrictions
Authoring OS-023/024 Existing /authoring/questions, /rubrics, /forms; target freeze/version/media operations Full typed questions/rubrics/items, media scoped authorization, policy complete-before-freeze
Runner OS-030–033 Existing /runner/auth/lookup; /runner/sessions/{session_id}/start; /runner/attempts/{attempt_id}/items, autosave, heartbeat, submit Session/enrollment/form/device context, typed answers, durable ACK/receipt; target read attempt state/resume if not covered by start/items
Secure OS-040–042 Existing /secure/launch-authorizations, /secure/launch-authorizations/{id}/config.seb, /secure/launch-authorizations/{id}/enter; target readiness-session persistence Short-lived one-time token, event-bound plist, official ConfigKeyHash verification, device binding, immutable launcher artifact metadata; participant config stays private and no permanent secret is embedded in the launcher
Monitoring OS-050/051 Existing /proctor/sessions/{session_id}/live, /proctor/attempts/{attempt_id}/log-incident; target scoped rooms and timeline/event channel Presence freshness, room scope, reconnect cursor/snapshot; machine vs human events
Intervention OS-033 Existing /proctor/attempts/{attempt_id}/revoke-session retained only as guarded alias if used; target manager force-submit exam_manager authority despite legacy proctor prefix; reason/idempotency; revoke old device; strict deadline preserved
Evidence OS-064/065 Target /runner/attempts/{attempt_id}/capture-requests; /evidence/uploads; /evidence/{id}/complete; /evidence/{id}/access Policy-bound challenge, bounded upload, completion idempotency, private access authorization/audit, expiration/deletion
Grading OS-060 Existing /grading/sessions/{session_id}/queue; /grading/submissions/{attempt_id}/questions/{question_id}/score and /moderate Assignment, valid rubric criteria, reviewer ≠ grader, expected version, immutable revisions
Results OS-061/062 Existing /results/sessions/{session_id}/rankings and /publish; target score finalize/ranking snapshots/freeze/approve/withdraw Ungraded/moderation block, snapshot-based approval, shared ranks, publication visibility; no is_public bypass
Reports OS-063 Existing export-csv; target /reports/exports and private artifact retrieval Async job request/state, scope/version/expiry, safe output, no unbounded synchronous participant-path work
Retention RM-008 Target policy/hold/delete administrative jobs DEC-08-approved privileged operations, tombstone/version/backup semantics, audit and evidence
Integration SC-001/002 Future integration mappings, roster import, signed result delivery/reconciliation Service identity, tenant/external mapping, signature/expiry/replay protection and durable outbox; no direct Odoo DB

Certificate routes in existing code are out of v1, not implicitly secured by docs. RM-011 must disable/remove them from release registration and verify deny behavior. Legacy route compatibility decisions cannot bypass authorization; actual code surface inventory required RM-010/I7.

4. Runner request/data contract

Start resolves current enrollment + authorized session, frozen form and policy. Response includes attempt_id, session_id, status, server_now, immutable server_deadline, accepted snapshot reference and safe item count; not answer keys. Duplicate start returns same attempt; different live device rejected until manager recovery.

Autosave fields: question_id, revision_number, answer_data and optional client_timestamp (informational only). Payload discriminates: - multiple_choice_single: selected_option_id (own snapshot option) or explicit cleared response. - numeric: finite numeric value or explicit cleared response; tolerance/rounding from frozen key, not client. - essay: bounded text; no executable markup; empty response does not bypass grading state. Target representation pada OpenAPI draft memakai discriminator kind dan null pada field selected_option_id/value/text untuk clear. UI harus membedakan pending clear dari saved clear; kompatibilitas payload existing dan limits wajib diselesaikan sebelum OS-031 READY.

Server verifies auth/device/secure context, locks attempt, checks current server time and state, validates snapshot item/type, resolves revision/idempotency, persists accepted answer and audit/outbox, then ACK. ACK contains accepted_revision, server_saved_at, attempt state and correlation; retry after lost response uses same key. Local pending draft is not an accepted answer and may be lost with device failure; never promise otherwise.

now >= server_deadline rejects NEW saves, even if request entered proxy earlier. Successfully committed pre-deadline result may be replayed after deadline with valid authorization; that is not a late save. Submit contains no answer patch; frontend attempts to flush valid pending answers first and displays failures. Server sweep atomically submits at deadline independently from browser/Celery scheduled message. Manual submit after deadline resolves terminal receipt rather than opening answer window.

Recovery rotates device generation and session credentials; invalidate old device on every endpoint. Camera/Zoom incident alone does not block valid saves; invalid runner identity or required secure context does. Both incident/rejection are observable without changing stored ACK.

5. SEB/launcher contract and validation boundary

Launcher is signed C#/.NET Windows app, not custom browser/process surveillance tool. It checks approved OS/SEB/display/network policy; retrieves short-lived enrollment-bound config authorization; hands off only authorized exam and returns safe support correlation.

Choose actual validation protocol for approved SEB version during OS-001: version/config allowlist, request validation through proxy canonical URL, handoff expiry/replay, config rotation/revocation. Mere user-agent, existence of an HTTP header, or client readiness boolean is not sufficient. No permanent key in browser bundle/config endpoint logs. Signed launcher does not make participant hardware trusted.

Spike evidence: install/update/uninstall and downgrade block; authorized launch; denied/expired/reused launch; ordinary browser/forged context; camera permission/preview/capture inside same SEB; device min-resource stress; safe support diagnostics. Failure blocks secure-profile acceptance and is escalated to PO; no hidden fallback browser.

6. Camera evidence protocol (CAM-01–10)

  1. Admission presents approved notice/policy and verifies browser support/permission, preview and test/pre-exam still. Pre-exam capture bound to a prepared attempt/admission identity; creating admission evidence must not start exam timer early.
  2. Server issues randomized capture request bound to attempt/device/policy/trigger/expiry; full periodic schedule is not published to client. Event-trigger allowlist, count and frequency bounded by DEC-07.
  3. Client obtains upload permission for allowed image content/size and private object location; upload HTTPS. No general-purpose arbitrary object/key path, public ACL, unbounded payload or cross-attempt reuse.
  4. Completion validates server-side checksum/type/size/object ownership/challenge. Persist metadata+audit atomically; deduplicate retry. Separate server received time from untrusted client captured time.
  5. Evidence viewers require DEC-08 authorization + room/event scope on access, short-lived access and audit. Participant upload does not grant retrieval of evidence library; local preview remains available. Grader/score reviewer cannot use evidence endpoints to recover identity.
  6. Retention worker applies expiry/hold/deletion across object versions/thumbnails/export/backups. Delete audited; restore reapplies tombstones before evidence access. TTL and hold rules must be approved; unknown policy is not “retain forever”.
  7. Object-store failure produces retry/alert but never stalls answer transaction, changes timer, or marks cheating. Bounded client/worker buffer and evidence workload bulkhead required.
  8. Events track end/mute/permission/device changes only where observable; do not equate to impersonation. No video/audio stream, AI/liveness, face recognition or automated disqualification.

There is no promised forensic proof of freshness/identity from a checksum or capture challenge alone. OS-071 must consider replay/substitution/client tampering and record residual risk without adding covert surveillance.

7. Scoring/publication contract

Objective scoring uses frozen policy and typed response only. DEC-03 freezes numeric precision/tolerance and objective points; no invented negative marking defaults. Essay sums bounded criteria; all applicable essays moderated by different actor before final snapshot.

Versioned score correction keeps prior values/reason. Publication identifies immutable snapshot, approval actor/time and publisher. Authorized correction builds new snapshot/publication with supersedes reference; withdrawal is an event, not DELETE. Display official rank from selected publication, not mutable latest grade query. Public result visibility remains DEC-12, not inferred from a client boolean.

8. API delivery gates

RM-010 inventories actual registered routes without unsafe app import (current main.py create_all requires remediation first). Per-slice review maps method/path/role/resource/DTO/error/idempotency/AC to OpenAPI and generated client. CI fails drift and key leakage; I7 fails any release route without schema/security/tests. Retain source reference IDs FR/CAM/OS in operation metadata where useful.