diff --git a/infra/scripts/drills/run-phase5b-selfpaced-rehearsal.sh b/infra/scripts/drills/run-phase5b-selfpaced-rehearsal.sh new file mode 100755 index 0000000..14c1d48 --- /dev/null +++ b/infra/scripts/drills/run-phase5b-selfpaced-rehearsal.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Orchestrates the Phase 5B §18 self-paced dress rehearsal: brings up the real dev stack, +# bootstraps an owner, runs test-phase5b-selfpaced-rehearsal.js, tears down. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../../../platform" + +export PROVISIONER_SHARED_SECRET="${PROVISIONER_SHARED_SECRET:-rehearsal-shared-secret-not-for-production}" +export INTEGRATION_SHARED_SECRET="${INTEGRATION_SHARED_SECRET:-dev-integration-secret-not-for-production}" + +docker compose -f docker-compose.dev.yml up -d --build + +cleanup() { + echo "==> Tearing down" + docker ps -aq --filter "name=rootnode-lab-" | xargs -r docker rm -f >/dev/null 2>&1 || true + docker network ls --filter "name=rootnode-lab-net-" --format "{{.Name}}" | xargs -r -n1 docker network rm >/dev/null 2>&1 || true + docker compose -f docker-compose.dev.yml down >/dev/null 2>&1 || true +} +trap cleanup EXIT + +echo "==> Waiting for the stack" +for _ in $(seq 1 60); do + curl -sf http://localhost:4300/healthz >/dev/null 2>&1 && curl -sf http://localhost:4200/healthz >/dev/null 2>&1 && break + sleep 2 +done + +echo "==> Bootstrapping the rehearsal owner" +( cd api && PLATFORM_DB_URL=postgres://postgres:postgres@localhost:5433/rootnode_platform \ + node bootstrap-owner.js p5b-rehearsal-owner@rootnode.test "P5B Rehearsal Owner" 'RehearsalPass!2026' ) + +echo "==> Running the rehearsal" +OWNER_EMAIL=p5b-rehearsal-owner@rootnode.test OWNER_PASSWORD='RehearsalPass!2026' \ + INTEGRATION_KEY="$INTEGRATION_SHARED_SECRET" \ + node ../infra/scripts/drills/test-phase5b-selfpaced-rehearsal.js diff --git a/infra/scripts/drills/test-phase5b-selfpaced-rehearsal.js b/infra/scripts/drills/test-phase5b-selfpaced-rehearsal.js new file mode 100755 index 0000000..c8ddc6a --- /dev/null +++ b/infra/scripts/drills/test-phase5b-selfpaced-rehearsal.js @@ -0,0 +1,174 @@ +#!/usr/bin/env node +// Phase 5B §18 — the self-paced dress rehearsal. One continuous realistic story, not synthetic +// unit assertions: a student is created, activates, has no program, a simulated website +// enrollment event enrolls them, they work real curriculum in a real Lab, the Lab is destroyed, +// they come back later, Continue Learning resumes correctly, a fresh Lab provisions, and they +// complete enough of the program to prove the completion transition. A second, uninvolved +// student proves they cannot reach the first student's program or Lab. No framework, matching +// project convention (see test-fake-cohort-rehearsal.js / test-phase5a-rehearsal.js). +// +// Run via run-phase5b-selfpaced-rehearsal.sh, which brings up platform/docker-compose.dev.yml +// first. + +const assert = require('assert'); +const { makeSession } = require('../../../platform/test/session-helper'); + +const GW = process.env.GATEWAY_URL || 'http://localhost:4200'; +const OWNER_EMAIL = process.env.OWNER_EMAIL; +const OWNER_PASSWORD = process.env.OWNER_PASSWORD; +const INTEGRATION_KEY = process.env.INTEGRATION_KEY || 'dev-integration-secret-not-for-production'; +if (!OWNER_EMAIL || !OWNER_PASSWORD) { console.error('Set OWNER_EMAIL and OWNER_PASSWORD'); process.exit(1); } +const RUN_ID = Date.now(); +const PROGRAM = 'root-kubernetes-foundations'; + +// Just enough of the real Foundation stage to prove stage-completion + capstone unlock without +// re-driving the entire curriculum a second time (e2e-phase5b.js already does that +// exhaustively) — this rehearsal seeds the REST of the curriculum's completion directly in +// Postgres (a real, documented technique — see test-phase5a-rehearsal.js's seedHistory) so the +// story can reach "program completed" without spending another 40+ real scenario round trips. +const FOUNDATION_FIRST = 'pod-basics-mcq'; + +let passed = 0, failed = 0; +async function step(name, fn) { + try { await fn(); console.log(` ok — ${name}`); passed++; } + catch (e) { console.error(` FAIL — ${name}\n ${e.stack || e.message}`); failed++; } +} +function fireIntegrationEvent(payload) { + return fetch(`${GW}/api/integrations/enrollments`, { + method: 'POST', headers: { 'Content-Type': 'application/json', 'X-RootNode-Integration-Key': INTEGRATION_KEY }, + body: JSON.stringify(payload), + }).then(async (r) => ({ status: r.status, body: await r.json() })); +} + +async function main() { + console.log('Phase 5B self-paced dress rehearsal — slow, real k3s boots\n'); + + const owner = makeSession(GW); + await owner.request('POST', '/api/auth/instructor/login', { email: OWNER_EMAIL, password: OWNER_PASSWORD }); + + const { body: created } = await owner.request('POST', '/api/admin/students', { + display_name: 'Rehearsal Self-Paced Student', login_identifier: `p5b-selfpaced-${RUN_ID}`, + }); + const session = makeSession(GW); + let enrollmentId, envId; + + await step('student activates credentials and logs in', async () => { + const { status } = await session.request('POST', '/api/student/activate', { token: created.activation_token, password: 'RehearsalPass123!' }); + assert.equal(status, 200); + }); + + await step('student initially has no program', async () => { + const { body } = await session.request('GET', '/api/student/programs'); + assert.equal(body.length, 0); + }); + + await step('a simulated website enrollment event enrolls the student (server-to-server, not a browser session)', async () => { + const { status, body } = await fireIntegrationEvent({ + event_id: `p5b-rehearsal-${RUN_ID}`, source: 'website', program_slug: PROGRAM, status: 'paid', + student: { login_identifier: `p5b-selfpaced-${RUN_ID}`, display_name: 'Rehearsal Self-Paced Student' }, + }); + assert.equal(status, 201); + assert.equal(body.status, 'active'); + enrollmentId = body.enrollment_id; + }); + + await step('the self-paced root program now appears on the student\'s dashboard, ready to go', async () => { + const { body } = await session.request('GET', '/api/student/programs'); + assert.equal(body.length, 1); + assert.equal(body[0].can_launch, true); + assert.equal(body[0].next_activity.scenario_id, FOUNDATION_FIRST); + }); + + await step('student launches a REAL Lab and completes the first real scenario', async () => { + const { status, body } = await session.request('POST', `/api/student/programs/${enrollmentId}/launch`); + assert.equal(status, 200); + assert.equal(body.status, 'running'); + const envRow = (await owner.request('GET', `/api/admin/students/${created.student_id}/environment`)).body.find((e) => e.status === 'running'); + envId = envRow.environment_id; + const complete = await session.request('POST', '/api/progress/record', { scenario_id: FOUNDATION_FIRST, status: 'completed', environment_id: envId }); + assert.equal(complete.status, 200); + }); + + await step('the Lab is destroyed (student closed the tab, session ended — the disposable-by-design lifecycle)', async () => { + await owner.request('DELETE', `/api/admin/environments/${envId}`); + }); + + await step('student logs out', async () => { + await session.request('POST', '/api/logout'); + }); + + const returningSession = makeSession(GW); + await step('time passes — student logs back in on a new session', async () => { + const { status } = await returningSession.request('POST', '/api/student/login', { identifier: `p5b-selfpaced-${RUN_ID}`, password: 'RehearsalPass123!' }); + assert.equal(status, 200); + }); + + await step('Continue Learning points to the correct next activity, unchanged by the Lab being gone', async () => { + const { body } = await returningSession.request('GET', `/api/student/programs/${enrollmentId}`); + assert.notEqual(body.next_activity.scenario_id, FOUNDATION_FIRST); // moved past it + assert.ok(body.progress.percent_complete > 0); + }); + + await step('a new Lab provisions and prior progress is intact under it', async () => { + const { status, body } = await returningSession.request('POST', `/api/student/programs/${enrollmentId}/launch`); + assert.equal(status, 200); + assert.equal(body.status, 'running'); + const envRow = (await owner.request('GET', `/api/admin/students/${created.student_id}/environment`)).body.find((e) => e.status === 'running'); + envId = envRow.environment_id; + }); + + await step('seed the rest of curriculum completion directly (realistic bulk backfill, not re-driving 40+ real requests — see file header)', async () => { + const client = `docker compose -f docker-compose.dev.yml exec -T postgres psql -U postgres -d rootnode_platform -c`; + const { execSync } = require('child_process'); + const rest = ['kubectl-essentials-mcq', 'labels-selectors-mcq', 'init-containers-mcq', 'namespaces-basics', 'multi-container-pod-basics', + 'pod-labeling-basics', 'jsonpath-basics', 'dry-run-manifest-basics', 'delete-by-label-basics', 'annotate-resource-basics', + 'init-container-task-basics', 'restart-policy-mcq', 'kubectl-output-format-mcq', 'kubectl-explain-basics', 'kubectl-patch-basics', + 'field-selector-basics', 'sort-by-basics', 'kubectl-diff-basics', 'static-pods-mcq', + 'deploy-nginx', 'scale-deployment', 'rolling-update-task', 'liveness-probe-task', 'jobs-cronjobs-mcq', 'daemonset-mcq', 'edit-deployment-basics', 'deployment-strategy-mcq', + 'services-mcq', 'expose-service-basics', + 'configmap-volume', 'resource-limits-task', 'env-vars-configmap', 'secrets-basics', 'pod-env-vars-inline', + 'extract-logs-basics', 'kubectl-cp-basics', 'exec-command-basics', 'node-cordon-basics', 'pod-node-assignment-mcq']; + const values = rest.map((sid) => `('${created.student_id}','${sid}','completed',1,now(),now())`).join(','); + execSync(`${client} "INSERT INTO progress (student_id, scenario_id, status, attempts, completed_at, started_at) VALUES ${values} ON CONFLICT (student_id, scenario_id) DO UPDATE SET status='completed'"`, { cwd: `${__dirname}/../../../platform` }); + }); + + await step('student completes the RootNode Capstone for real (the actual server-authoritative draw + validation)', async () => { + const start = await returningSession.request('POST', '/api/assessments/rootnode-capstone/start'); + assert.equal(start.status, 201); + for (const s of start.body.scenarios) { + const r = await returningSession.request('POST', '/api/progress/record', { scenario_id: s.scenario_id, status: 'completed', environment_id: envId }); + assert.equal(r.status, 200); + } + }); + + await step('the program moves to Completed — server-derived, no client "mark complete" action', async () => { + const { body } = await returningSession.request('GET', `/api/student/programs/${enrollmentId}`); + assert.equal(body.status, 'completed'); + assert.ok(body.completed_at); + }); + + await step('the admin portal shows a durable completion record for this student', async () => { + const { body } = await owner.request('GET', `/api/admin/students/${created.student_id}/enrollments`); + const view = body.find((e) => e.enrollment_id === enrollmentId); + assert.equal(view.status, 'completed'); + }); + + // ── A second, uninvolved student — proves entitlement is real, not just "logged in" ────── + const { body: otherCreate } = await owner.request('POST', '/api/admin/students', { display_name: 'Rehearsal Outsider', login_identifier: `p5b-outsider-${RUN_ID}` }); + const outsider = makeSession(GW); + await outsider.request('POST', '/api/student/activate', { token: otherCreate.activation_token, password: 'OutsiderPass123!' }); + + await step('an uninvolved student cannot reach the first student\'s program or Lab path', async () => { + const read = await outsider.request('GET', `/api/student/programs/${enrollmentId}`); + assert.equal(read.status, 404); + const launch = await outsider.request('POST', `/api/student/programs/${enrollmentId}/launch`); + assert.equal(launch.status, 404); + const list = await outsider.request('GET', '/api/student/programs'); + assert.equal(list.body.length, 0); + }); + + console.log(`\n${passed} passed, ${failed} failed`); + if (failed > 0) process.exit(1); +} + +main().catch((e) => { console.error(e); process.exit(1); }); diff --git a/platform/test/e2e-phase5b.js b/platform/test/e2e-phase5b.js new file mode 100644 index 0000000..cc4d430 --- /dev/null +++ b/platform/test/e2e-phase5b.js @@ -0,0 +1,411 @@ +#!/usr/bin/env node +// Phase 5B — self-paced learning & enrollment foundation acceptance test. Covers the program/ +// enrollment model, entitlement gating (pending/future/expired/cancelled), curriculum +// assignment, resume/Continue Learning, disposable-Lab persistence across destroy/reaper/ +// recreate, server-derived idempotent completion, the website/commerce integration boundary +// (auth, idempotency, concurrency, minor/no-email path), RBAC scoping, and a real restart. Same +// conventions as e2e-phase5a.js/e2e-phase3b.js: assert-based, no framework, live +// docker-compose.dev.yml stack, real k3s boots for the Lab-persistence section. +// +// Usage: cd platform && docker compose -f docker-compose.dev.yml up -d +// (cd api && PLATFORM_DB_URL=... node bootstrap-owner.js OWNER_EMAIL "Owner" OWNER_PASSWORD) +// OWNER_EMAIL=... OWNER_PASSWORD=... INTEGRATION_KEY=... node test/e2e-phase5b.js + +const assert = require('assert'); +const { execSync } = require('child_process'); +const { makeSession } = require('./session-helper'); + +const GW = process.env.GATEWAY_URL || 'http://localhost:4200'; +const API = process.env.PLATFORM_API_URL || 'http://localhost:4300'; +const OWNER_EMAIL = process.env.OWNER_EMAIL; +const OWNER_PASSWORD = process.env.OWNER_PASSWORD; +const INTEGRATION_KEY = process.env.INTEGRATION_KEY || 'dev-integration-secret-not-for-production'; +const SKIP_RESTART_TEST = process.env.SKIP_RESTART_TEST === '1'; +if (!OWNER_EMAIL || !OWNER_PASSWORD) { + console.error('Set OWNER_EMAIL and OWNER_PASSWORD (bootstrap one first with platform/api/bootstrap-owner.js)'); + process.exit(1); +} +const RUN_ID = Date.now(); +const PROGRAM = 'root-kubernetes-foundations'; + +// Same curriculum snapshot e2e-phase3b.js drives full completion against — see that file's +// header for why this is a real (not synthetic) content list. +const FOUNDATION = ['pod-basics-mcq', 'kubectl-essentials-mcq', 'labels-selectors-mcq', 'init-containers-mcq', 'namespaces-basics', + 'multi-container-pod-basics', 'pod-labeling-basics', 'jsonpath-basics', 'dry-run-manifest-basics', 'delete-by-label-basics', + 'annotate-resource-basics', 'init-container-task-basics', 'restart-policy-mcq', 'kubectl-output-format-mcq', + 'kubectl-explain-basics', 'kubectl-patch-basics', 'field-selector-basics', 'sort-by-basics', 'kubectl-diff-basics', 'static-pods-mcq']; +const WORKLOADS = ['deploy-nginx', 'scale-deployment', 'rolling-update-task', 'liveness-probe-task', 'jobs-cronjobs-mcq', 'daemonset-mcq', 'edit-deployment-basics', 'deployment-strategy-mcq']; +const NETWORKING = ['services-mcq', 'expose-service-basics']; +const CONFIGURATION = ['configmap-volume', 'resource-limits-task', 'env-vars-configmap', 'secrets-basics', 'pod-env-vars-inline']; +const TROUBLESHOOTING = ['extract-logs-basics', 'kubectl-cp-basics', 'exec-command-basics', 'node-cordon-basics', 'pod-node-assignment-mcq']; +const ALL_NON_CAPSTONE = [...FOUNDATION, ...WORKLOADS, ...NETWORKING, ...CONFIGURATION, ...TROUBLESHOOTING]; + +let passed = 0, failed = 0; +async function test(name, fn) { + try { await fn(); console.log(` ok — ${name}`); passed++; } + catch (e) { console.error(` FAIL — ${name}\n ${e.message}`); failed++; } +} +async function complete(session, scenarioId, envId) { + const { status } = await session.request('POST', '/api/progress/record', { scenario_id: scenarioId, status: 'completed', environment_id: envId }); + assert.equal(status, 200, `completing ${scenarioId} should 200`); +} +// The routing token in launch_path is NOT the environment_id scenario_attempts/progress +// records expect (a UUID) — resolve the real one via the admin view, same technique +// e2e-phase3b.js uses. +async function resolveEnvId(owner, studentId) { + const { body } = await owner.request('GET', `/api/admin/students/${studentId}/environment`); + return body.find((e) => e.status === 'running')?.environment_id; +} +function fireIntegrationEvent(payload) { + return fetch(`${GW}/api/integrations/enrollments`, { + method: 'POST', headers: { 'Content-Type': 'application/json', 'X-RootNode-Integration-Key': INTEGRATION_KEY }, + body: JSON.stringify(payload), + }).then(async (r) => ({ status: r.status, body: await r.json() })); +} + +async function main() { + console.log('Phase 5B self-paced learning / enrollment foundation acceptance test\n'); + + const owner = makeSession(GW); + await owner.request('POST', '/api/auth/instructor/login', { email: OWNER_EMAIL, password: OWNER_PASSWORD }); + + // ── Regression: a malformed environment_id must never crash the whole Platform API ────── + // Found by this test suite — POST /api/progress/record's handler predated the wrap() + // convention and an unexpected internal error (Postgres rejecting a non-UUID environment_id) + // became an unhandled promise rejection that killed the entire process. Fixed in server.js + // (wrap() + explicit UUID-shape validation); this proves it stays fixed. + await test('malformed environment_id is a clean 400, not a process crash', async () => { + const s = makeSession(GW); + const { body: probe } = await owner.request('POST', '/api/admin/students', { display_name: `E2E-5B-CrashProbe-${RUN_ID}` }); + await s.request('POST', '/api/login', { student_id: probe.student_id }); + const bad = await s.request('POST', '/api/progress/record', { scenario_id: 'pod-basics-mcq', status: 'completed', environment_id: 'not-a-uuid' }); + assert.equal(bad.status, 400); + const health = await fetch(`${API}/healthz`); + assert.equal(health.status, 200, 'the API process must still be alive'); + }); + + // ── §1: program seed ───────────────────────────────────────────────────────────────────── + await test('program seed exists (root-kubernetes-foundations)', async () => { + const { status, body } = await owner.request('GET', '/api/admin/programs'); + assert.equal(status, 200); + const program = body.find((p) => p.program_id === PROGRAM); + assert.ok(program); + assert.equal(program.family, 'root'); + assert.equal(program.curriculum_path, 'rootnode-path'); + }); + + const { body: aliceCreate } = await owner.request('POST', '/api/admin/students', { display_name: `E2E-5B-Alice-${RUN_ID}`, login_identifier: `e2e5b-alice-${RUN_ID}` }); + const { body: bobCreate } = await owner.request('POST', '/api/admin/students', { display_name: `E2E-5B-Bob-${RUN_ID}`, login_identifier: `e2e5b-bob-${RUN_ID}` }); + const alice = makeSession(GW); + const bob = makeSession(GW); + await alice.request('POST', '/api/student/activate', { token: aliceCreate.activation_token, password: 'AlicePassword123!' }); + await bob.request('POST', '/api/student/activate', { token: bobCreate.activation_token, password: 'BobPassword123!' }); + + // ── §2: no entitlement ─────────────────────────────────────────────────────────────────── + await test('authenticated student with no enrollment sees an empty programs list', async () => { + const { status, body } = await alice.request('GET', '/api/student/programs'); + assert.equal(status, 200); + assert.equal(body.length, 0); + }); + + // ── §3-4: admin enrolls, activation, entitlement gating ───────────────────────────────── + let enrollmentId; + await test('admin manually enrolls student', async () => { + const { status, body } = await owner.request('POST', '/api/admin/enrollments', { student_id: aliceCreate.student_id, program_id: PROGRAM }); + assert.equal(status, 201); + assert.equal(body.status, 'pending'); + enrollmentId = body.enrollment_id; + }); + + await test('pending enrollment is visible but launch is blocked server-side, not just hidden', async () => { + const { body } = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + assert.equal(body.can_launch, false); + assert.equal(body.blocked_reason, 'pending_activation'); + const { status } = await alice.request('POST', `/api/student/programs/${enrollmentId}/launch`); + assert.equal(status, 403); + }); + + await test('activated enrollment appears active on the student dashboard/API', async () => { + const activated = await owner.request('POST', `/api/admin/enrollments/${enrollmentId}/activate`); + assert.equal(activated.status, 200); + const { body } = await alice.request('GET', '/api/student/programs'); + const view = body.find((p) => p.enrollment_id === enrollmentId); + assert.equal(view.can_launch, true); + assert.ok(view.progress); // §8: curriculum assignment resolved — real progress state, not a stub + }); + + // ── §5-7: future / expired / cancelled ────────────────────────────────────────────────── + await test('future-dated enrollment is visible but blocked before starts_at', async () => { + const created = await owner.request('POST', '/api/admin/enrollments', { + student_id: bobCreate.student_id, program_id: PROGRAM, status: 'active', starts_at: '2099-01-01', + }); + assert.equal(created.status, 201); + const { body } = await bob.request('GET', `/api/student/programs/${created.body.enrollment_id}`); + assert.equal(body.effective_status, 'active'); + assert.equal(body.can_launch, false); + assert.equal(body.blocked_reason, 'not_yet_started'); + const launch = await bob.request('POST', `/api/student/programs/${created.body.enrollment_id}/launch`); + assert.equal(launch.status, 403); + await owner.request('POST', `/api/admin/enrollments/${created.body.enrollment_id}/cancel`); // cleanup for later RBAC tests + }); + + await test('expired enrollment (access_ends_at passed) is visible historically but blocked from new Lab work', async () => { + const created = await owner.request('POST', '/api/admin/enrollments', { + student_id: bobCreate.student_id, program_id: PROGRAM, status: 'active', access_ends_at: '2020-01-01', + }); + assert.equal(created.status, 201); + const { body } = await bob.request('GET', `/api/student/programs/${created.body.enrollment_id}`); + assert.equal(body.effective_status, 'expired'); + assert.equal(body.can_launch, false); + const launch = await bob.request('POST', `/api/student/programs/${created.body.enrollment_id}/launch`); + assert.equal(launch.status, 403); + await owner.request('POST', `/api/admin/enrollments/${created.body.enrollment_id}/cancel`); + }); + + await test('cancelled enrollment is blocked from launch', async () => { + const created = await owner.request('POST', '/api/admin/enrollments', { student_id: bobCreate.student_id, program_id: PROGRAM, status: 'active' }); + await owner.request('POST', `/api/admin/enrollments/${created.body.enrollment_id}/cancel`); + const { body } = await bob.request('GET', `/api/student/programs/${created.body.enrollment_id}`); + assert.equal(body.effective_status, 'cancelled'); + const launch = await bob.request('POST', `/api/student/programs/${created.body.enrollment_id}/launch`); + assert.equal(launch.status, 403); + }); + + // ── §16-17: cross-student isolation ───────────────────────────────────────────────────── + await test('student B cannot read student A\'s enrollment or launch A\'s program entitlement', async () => { + const read = await bob.request('GET', `/api/student/programs/${enrollmentId}`); + assert.equal(read.status, 404); + const launch = await bob.request('POST', `/api/student/programs/${enrollmentId}/launch`); + assert.equal(launch.status, 404); + }); + + // ── §9/§10/§11/§12: resume, real Lab launch, destroy/reaper/recreate persistence ──────── + let aliceEnvId; + await test('entitled launch provisions the real disposable Lab (same mechanism as /api/environment/launch)', async () => { + const { status, body } = await alice.request('POST', `/api/student/programs/${enrollmentId}/launch`); + assert.equal(status, 200); + assert.equal(body.status, 'running'); + aliceEnvId = await resolveEnvId(owner, aliceCreate.student_id); + assert.ok(aliceEnvId); + }); + + await test('resume/Continue Learning points at the first real activity', async () => { + const { body } = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + assert.equal(body.next_activity.type, 'scenario'); + assert.equal(body.next_activity.scenario_id, FOUNDATION[0]); + }); + + await test('completing a scenario advances resume state deterministically', async () => { + await complete(alice, FOUNDATION[0], aliceEnvId); + const { body } = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + assert.equal(body.next_activity.scenario_id, FOUNDATION[1]); + assert.ok(body.progress.percent_complete > 0); + }); + + await test('academic progress survives a Lab destroy + a fresh Lab recreation', async () => { + const before = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + await owner.request('DELETE', `/api/admin/environments/${aliceEnvId}`); + const relaunch = await alice.request('POST', `/api/student/programs/${enrollmentId}/launch`); + assert.equal(relaunch.body.status, 'running'); + aliceEnvId = await resolveEnvId(owner, aliceCreate.student_id); // a NEW environment_id — same student, fresh container + assert.ok(aliceEnvId); + const after = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + assert.deepEqual(after.body.progress.percent_complete, before.body.progress.percent_complete); + assert.equal(after.body.next_activity.scenario_id, before.body.next_activity.scenario_id); + }); + + await test('academic progress survives the reaper\'s exact consequence (destroy out-of-band + Provisioner reconciliation, same as test-lab-host-loss.js)', async () => { + // Mirrors infra/scripts/drills/test-lab-host-loss.js's technique exactly: kill the + // container directly (bypassing the Provisioner entirely, exactly what the real idle + // reaper's failure mode looks like from the Provisioner's point of view), then restart the + // Provisioner to run its real reconcileOnStartup pass — a plain `docker rm` alone leaves + // the DB row still saying 'running' and launch would just hand back the now-dead + // environment instead of a fresh one, which wouldn't prove anything. + const before = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + const containers = execSync(`docker ps --filter "name=rootnode-lab-" --format "{{.Names}}"`).toString().trim().split('\n').filter(Boolean); + for (const c of containers) execSync(`docker rm -f ${c}`, { stdio: 'pipe' }); + execSync('docker compose -f docker-compose.dev.yml restart provisioner', { cwd: `${__dirname}/..`, stdio: 'pipe' }); + await new Promise((r) => setTimeout(r, 5000)); + + const relaunch = await alice.request('POST', `/api/student/programs/${enrollmentId}/launch`); + assert.equal(relaunch.body.status, 'running'); + aliceEnvId = await resolveEnvId(owner, aliceCreate.student_id); + const after = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + assert.deepEqual(after.body.progress.percent_complete, before.body.progress.percent_complete); + }); + + // ── §13-15: completion is server-derived, idempotent, and correctly categorized ───────── + await test('completing every remaining stage scenario + the capstone transitions the enrollment to completed (server-derived, not a client button)', async () => { + for (const sid of ALL_NON_CAPSTONE.filter((s) => s !== FOUNDATION[0])) await complete(alice, sid, aliceEnvId); + const { status: startStatus, body: capstone } = await alice.request('POST', '/api/assessments/rootnode-capstone/start'); + assert.equal(startStatus, 201); + for (const s of capstone.scenarios) await complete(alice, s.scenario_id, aliceEnvId); + + // No client ever calls anything like "mark enrollment complete" — reading the program + // status is what triggers the (idempotent) server-side check, via program-status.js's + // maybeCompleteEnrollment. + const { body } = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + assert.equal(body.status, 'completed'); + assert.ok(body.completed_at); + }); + + await test('completion is idempotent — reading again does not change completed_at or error', async () => { + const first = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + const second = await alice.request('GET', `/api/student/programs/${enrollmentId}`); + assert.equal(first.body.completed_at, second.body.completed_at); + assert.equal(second.status, 200); + }); + + await test('completed program is categorized correctly in the programs list', async () => { + const { body } = await alice.request('GET', '/api/student/programs'); + const view = body.find((p) => p.enrollment_id === enrollmentId); + assert.equal(view.effective_status, 'completed'); + }); + + // ── §18-23: website/commerce integration boundary ─────────────────────────────────────── + await test('integration endpoint rejects a request carrying an ordinary browser/student session instead of the shared key', async () => { + const res = await fetch(`${GW}/api/integrations/enrollments`, { + method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: `rn_session=${alice.getCookie('rn_session')}` }, + body: JSON.stringify({ event_id: 'evt-session-auth', program_slug: PROGRAM, status: 'paid', student: { email: 'x@example.com' } }), + }); + assert.equal(res.status, 401); + }); + + let integrationEnrollmentId, integrationStudentId; + await test('a valid integration event creates the correct enrollment', async () => { + const { status, body } = await fireIntegrationEvent({ + event_id: `evt-${RUN_ID}-1`, source: 'website', program_slug: PROGRAM, status: 'paid', + student: { email: `newkid-${RUN_ID}@example.com`, display_name: 'New Kid' }, + }); + assert.equal(status, 201); + assert.equal(body.status, 'active'); + assert.equal(body.program_id, PROGRAM); + integrationEnrollmentId = body.enrollment_id; + integrationStudentId = body.student_id; + }); + + await test('the exact same external event_id replayed creates no duplicate enrollment', async () => { + const { status, body } = await fireIntegrationEvent({ + event_id: `evt-${RUN_ID}-1`, source: 'website', program_slug: PROGRAM, status: 'paid', + student: { email: `newkid-${RUN_ID}@example.com` }, + }); + assert.equal(status, 200); + assert.equal(body.created, false); + assert.equal(body.enrollment_id, integrationEnrollmentId); + }); + + await test('concurrent duplicate integration events create exactly one logical enrollment', async () => { + const eventId = `evt-${RUN_ID}-race`; + const fire = () => fireIntegrationEvent({ event_id: eventId, source: 'website', program_slug: PROGRAM, status: 'paid', student: { email: `racer-${RUN_ID}@example.com` } }); + const [a, b, c] = await Promise.all([fire(), fire(), fire()]); + const ids = new Set([a.body.enrollment_id, b.body.enrollment_id, c.body.enrollment_id]); + assert.equal(ids.size, 1); + assert.equal([a, b, c].filter((r) => r.body.created).length, 1); + }); + + await test('unknown program_slug rejected cleanly (404), not a raw FK error', async () => { + const { status } = await fireIntegrationEvent({ event_id: `evt-${RUN_ID}-badprog`, program_slug: 'not-a-real-program', status: 'paid', student: { email: `x-${RUN_ID}@example.com` } }); + assert.equal(status, 404); + }); + + await test('inactive program rejected cleanly (409)', async () => { + await owner.request('POST', '/api/admin/programs', { program_id: `e2e-5b-inactive-${RUN_ID}`, name: 'Inactive Test Program', family: 'root' }); + await owner.request('PATCH', `/api/admin/programs/e2e-5b-inactive-${RUN_ID}`, { status: 'inactive' }); + const { status } = await fireIntegrationEvent({ event_id: `evt-${RUN_ID}-inactive`, program_slug: `e2e-5b-inactive-${RUN_ID}`, status: 'paid', student: { email: `x2-${RUN_ID}@example.com` } }); + assert.equal(status, 409); + }); + + await test('the integration payload/response never carries payment-card data (no such field exists to leak)', async () => { + const { body } = await owner.request('GET', `/api/admin/enrollments/${integrationEnrollmentId}`); + const serialized = JSON.stringify(body).toLowerCase(); + assert.ok(!serialized.includes('card') && !serialized.includes('cvv') && !serialized.includes('pan')); + }); + + await test('minor/no-email enrollment works via login_identifier alone (§13)', async () => { + const { status, body } = await fireIntegrationEvent({ + event_id: `evt-${RUN_ID}-minor`, source: 'website', program_slug: PROGRAM, status: 'paid', + student: { login_identifier: `guardian-ref-${RUN_ID}`, display_name: 'Guardian-Enrolled Kid' }, + }); + assert.equal(status, 201); + assert.ok(body.student_id); + }); + + // ── §25-26: RBAC ───────────────────────────────────────────────────────────────────────── + const { body: assignedInstr } = await owner.request('POST', '/api/admin/instructors', { + email: `e2e5b-assigned-${RUN_ID}@rootnode.test`, display_name: 'Assigned', role: 'instructor', password: 'AssignedPass123!', + }); + const { body: unrelatedInstr } = await owner.request('POST', '/api/admin/instructors', { + email: `e2e5b-unrelated-${RUN_ID}@rootnode.test`, display_name: 'Unrelated', role: 'instructor', password: 'UnrelatedPass123!', + }); + await test('admin RBAC: creating a program/enrollment is admin/owner only', async () => { + const assigned = makeSession(GW); + await assigned.request('POST', '/api/auth/instructor/login', { email: `e2e5b-assigned-${RUN_ID}@rootnode.test`, password: 'AssignedPass123!' }); + const { status } = await assigned.request('POST', '/api/admin/enrollments', { student_id: bobCreate.student_id, program_id: PROGRAM }); + assert.equal(status, 403); + }); + await test('instructor scope: an instructor sharing a cohort with the student can manage the enrollment; an unrelated instructor cannot', async () => { + const assigned = makeSession(GW); + await assigned.request('POST', '/api/auth/instructor/login', { email: `e2e5b-assigned-${RUN_ID}@rootnode.test`, password: 'AssignedPass123!' }); + const unrelated = makeSession(GW); + await unrelated.request('POST', '/api/auth/instructor/login', { email: `e2e5b-unrelated-${RUN_ID}@rootnode.test`, password: 'UnrelatedPass123!' }); + + // Neither plain instructor can create (admin/owner only, proven above) — so exercise scope + // on an owner-created enrollment via cohort-sharing instead: assign `assigned` to a cohort + // Bob is in, leave `unrelated` with no relationship at all. + const cohortId = `e2e5b-scope-${RUN_ID}`; + await owner.request('POST', '/api/admin/cohorts', { cohort_id: cohortId, name: 'E2E 5B scope' }); + await owner.request('POST', `/api/admin/cohorts/${cohortId}/instructors`, { instructor_id: assignedInstr.instructor_id }); + await owner.request('POST', `/api/admin/students/${bobCreate.student_id}/cohort`, { cohort_id: cohortId }); + const enr = await owner.request('POST', '/api/admin/enrollments', { student_id: bobCreate.student_id, program_id: PROGRAM, external_reference: 'scope-test' }); + + const assignedRead = await assigned.request('GET', `/api/admin/enrollments/${enr.body.enrollment_id}`); + assert.equal(assignedRead.status, 200); + const unrelatedRead = await unrelated.request('GET', `/api/admin/enrollments/${enr.body.enrollment_id}`); + assert.equal(unrelatedRead.status, 403); + }); + + // ── §30: no secrets in new APIs ────────────────────────────────────────────────────────── + await test('no password/credential-token hashes are ever returned by the new program/enrollment APIs', async () => { + const list = await owner.request('GET', '/api/admin/programs'); + const detail = await owner.request('GET', `/api/admin/enrollments/${enrollmentId}`); + const serialized = JSON.stringify(list.body) + JSON.stringify(detail.body); + assert.ok(!/password_hash|credential_token_hash/i.test(serialized)); + }); + + // ── §28-29: Phase 5A still works ───────────────────────────────────────────────────────── + await test('Phase 5A student authentication still works unmodified', async () => { + const s = makeSession(GW); + const { status } = await s.request('POST', '/api/student/login', { identifier: `e2e5b-alice-${RUN_ID}`, password: 'AlicePassword123!' }); + assert.equal(status, 200); + }); + + await test('Phase 5A remote classroom still works unmodified', async () => { + const cohortId = `e2e5b-classroom-${RUN_ID}`; + await owner.request('POST', '/api/admin/cohorts', { cohort_id: cohortId, name: 'E2E 5B classroom check' }); + const created = await owner.request('POST', `/api/admin/cohorts/${cohortId}/classroom-sessions`, { title: 'Still works' }); + const started = await owner.request('POST', `/api/admin/classroom-sessions/${created.body.classroom_session_id}/start`); + assert.equal(started.status, 200); + await owner.request('POST', `/api/admin/classroom-sessions/${created.body.classroom_session_id}/end`); + }); + + // ── §27: restart persistence ───────────────────────────────────────────────────────────── + if (!SKIP_RESTART_TEST) { + await test('enrollment and resume state survive a real Platform API restart', async () => { + const before = await alice.request('GET', '/api/student/programs'); + execSync('docker compose -f docker-compose.dev.yml restart api', { cwd: `${__dirname}/..`, stdio: 'pipe' }); + await new Promise((r) => setTimeout(r, 4000)); + const after = await alice.request('GET', '/api/student/programs'); + assert.equal(after.status, 200); + assert.deepEqual(after.body.map((p) => p.enrollment_id).sort(), before.body.map((p) => p.enrollment_id).sort()); + const completedView = after.body.find((p) => p.enrollment_id === enrollmentId); + assert.equal(completedView.status, 'completed'); + }); + } else { + console.log(' skip — restart persistence (SKIP_RESTART_TEST=1)'); + } + + console.log(`\n${passed} passed, ${failed} failed`); + if (failed > 0) process.exit(1); +} + +main().catch((e) => { console.error(e); process.exit(1); });