diff --git a/docs/peer-interviews.md b/docs/peer-interviews.md index 70da67b4f..6b27bb060 100644 --- a/docs/peer-interviews.md +++ b/docs/peer-interviews.md @@ -145,7 +145,7 @@ Only session members may export a saved transcript or audio; each member reads their own AI suggestions. Either member can delete the shared saved transcript or stop/delete shared audio. Deleting audio stops its writer before unlinking files. This does not stop the previously agreed temporary AI processing and -suggestions; terminate the session to stop the interview. A downloaded copy +suggestions; cancel the session to stop the interview. A downloaded copy cannot be recalled by deleting the server copy. A withdrawal made before capture starts is recorded, and the observer then declines to record that audio. @@ -289,7 +289,7 @@ actual transcripts or audio to a public issue. completion, confirm 24-hour expiry blocks reads and cleanup removes files. 9. Opt out of availability and expire a heartbeat; confirm the roster and pending requests disappear. Abandon a confirmed availability proposal and - verify ten-minute cleanup. Terminate an active session and confirm LiveKit + verify ten-minute cleanup. Cancel an active session and confirm LiveKit room deletion. 10. Allow a short round and hard deadline to expire with no polling; confirm final capture and settlement continue even while room deletion is stalled. diff --git a/docs/recording-contract.md b/docs/recording-contract.md index 7937626c5..74002f37d 100644 --- a/docs/recording-contract.md +++ b/docs/recording-contract.md @@ -442,10 +442,13 @@ made the distinction necessary: ### Ending -Normal end is `POST /api/interviews/{id}/end` or the LiveKit `room_finished` -webhook, whichever arrives first. Neither is optional: a browser can be closed -and a webhook can be lost. Both move the recording to `finalizing`, and -`finalizing` may become itself, so the second one to arrive changes nothing. +Normal end is the LiveKit `room_finished` webhook, which moves the recording to +`finalizing`. `finalizing` may become itself, so a repeated delivery changes +nothing. The browser sends no end of its own. The file arrives with the +`egress_ended` that Egress sends, which also completes the recording if +`room_finished` was lost. If `egress_ended` is lost, whether or not +`room_finished` arrived, the row is left to the sweeper below, which fails it as +`abandoned` once the bound for its state has passed. Consent withdrawal is not a normal end. The recording is not finished, it is abandoned: it goes to `failed` with reason `consent_withdrawn` and the file it @@ -742,9 +745,6 @@ allocated the number the caller is told. ### The snapshot -`GET /api/interviews/{id}/snapshot`, signed in, answering -`{"seq", "quotaExceeded", "events": [...]}`. - Nothing is stored to produce it and there is no cadence to configure. The four replaceable kinds already are the snapshot: the newest event of each is the whole state of that kind, so a snapshot is the replay with the superseded frames @@ -752,28 +752,12 @@ dropped, computed at the read. A periodic snapshot written to a second table would be a copy that can disagree with the events it was made from. A late join is therefore the snapshot plus everything after `seq`, concatenated. -The ceiling and the rows under it are read in one transaction, so a writer -landing between two statements cannot put an event in the snapshot that the -caller is about to ask for again. - -| Answer | When | -|---|---| -| `200` | the snapshot, and the `seq` to carry on from | -| `404 recording_not_found` | no such interview, not this account's, consent withdrawn, or this server records nothing | -| `410 replay_expired` | past the retention deadline, whether or not the sweeper has run | -| `410 recording_deleted` | the recording is a tombstone | - -`410` rather than `404` for the last two: the account owns the interview and is -owed the difference between "never yours" and "not any more". - -Authorization is the account that owns the interview, and nothing else. There is -no separate verified-identity gate here, because a replay is scoped by account -row rather than by handle: a self-declared account is its own row and sees its -own interviews. The verified-identity gate lives where identity decides who -receives a file, which is the start of a recording, not the read of a replay. - -An interview whose recording never started still has a replay and it is readable. -Expiry and deletion are read from the recording when there is one. +`GET /api/recordings/{id}/events` and the template's replay read, both below, +serve it, answering `{"seq", "quotaExceeded", "events": [...]}`; +`quotaExceeded` says the replay stopped growing at its quota, so its tail is +missing. The ceiling and the rows under it are read in one transaction, so a +writer landing between two statements cannot put an event in the snapshot that +the caller is about to ask for again. ### The template's replay read @@ -1523,7 +1507,7 @@ new reads and future ready transitions, then waits for the observer to close its writer and unlinks saved and partial files. A late capture finish cannot resurrect the record. Already downloaded copies cannot be recalled. Deleting saved audio does not cancel the separately agreed temporary AI transcription -and end-only suggestions; session termination stops the interview. +and end-only suggestions; cancelling the session stops the interview. Transcripts are separately selectable and withdrawable. When not selected, raw text exists only in bounded observer memory until the same session's diff --git a/src/accounts/peer/rounds.rs b/src/accounts/peer/rounds.rs index a4eab13d4..a21615bb0 100644 --- a/src/accounts/peer/rounds.rs +++ b/src/accounts/peer/rounds.rs @@ -28,21 +28,14 @@ pub(super) fn action( } if matches!( action, - "ready" | "start" | "advance" | "finish" | "terminate" | "cancel" | "invite" + "ready" | "start" | "advance" | "finish" | "cancel" | "invite" ) && let Err(e) = version(s, body) { return Ok(Err(e)); } let result = match action { - "cancel" | "terminate" => { - s.close_partial( - if action == "cancel" { - "cancelled" - } else { - "finalizing" - }, - now, - ); + "cancel" => { + s.close_partial("cancelled", now); c.execute("DELETE FROM peer_active_users WHERE session_id=?1", [&s.id])?; Ok(()) } diff --git a/src/recording/replay.rs b/src/recording/replay.rs index 67d722b52..7ca01397f 100644 --- a/src/recording/replay.rs +++ b/src/recording/replay.rs @@ -689,8 +689,10 @@ fn replay_view( return Ok(SnapshotView::NoInterview); } - // No recording row is not a refusal: an interview whose recording never - // started still has a replay, and it is this account's to read. + // No recording row is not a refusal, only nothing to check expiry or + // deletion against. The history events route and the template's replay + // read find the recording first, so through them the row is always + // there. let recording: Option<(String, Option, i64)> = transaction .query_row( " diff --git a/src/recording/store.rs b/src/recording/store.rs index 3ff08e95c..3765c4cbb 100644 --- a/src/recording/store.rs +++ b/src/recording/store.rs @@ -309,8 +309,8 @@ pub fn transition_within( } // Somebody else moved it first, so the state to report is theirs and - // not the one that was asked for. Reporting `next` here told `/end` - // that a recording was `finalizing` when it had already failed. + // not the one that was asked for. Reporting `next` here told the stop + // path that a recording was `finalizing` when it had already failed. let actual: String = connection.query_row( "SELECT state FROM recordings WHERE id = ?1", [recording_id], diff --git a/src/recording/sweeper.rs b/src/recording/sweeper.rs index 8b8b3decc..751951469 100644 --- a/src/recording/sweeper.rs +++ b/src/recording/sweeper.rs @@ -13,10 +13,11 @@ use super::{ /// Moves the row and then stops the provider, in that order. /// /// The order matters and is not obvious. Calling the provider first meant two -/// callers racing on one recording, `/end` and a `room_finished` webhook say, -/// both sent a stop, and a process that died between a successful stop and the -/// write left a row that stayed active forever. Moving first makes the row the -/// record of intent, and only the caller that moved it talks to the provider. +/// callers racing on one recording, a `room_finished` webhook and the sweeper +/// say, both sent a stop, and a process that died between a successful stop and +/// the write left a row that stayed active forever. Moving first makes the row +/// the record of intent, and only the caller that moved it talks to the +/// provider. /// /// A failed stop leaves the row where it was moved to and the job still /// running, which the sweeper finds once the row goes stale. That is the cost @@ -132,9 +133,9 @@ pub async fn start_and_record_egress( if stored { // A stop can land while the provider is still answering: consent - // withdrawn, the room finished, the candidate closed the tab. The row - // keeps the id whatever state it is in, and this is where a job that - // outlived its recording gets stopped. + // withdrawn or the room finished. The row keeps the id whatever state + // it is in, and this is where a job that outlived its recording gets + // stopped. settle_new_egress(accounts, recorder, &recording.id, &egress_id).await; } else { // Either the row already names another job, from the other caller diff --git a/src/web/interviews.rs b/src/web/interviews.rs index 36c9f9160..3b0216a1d 100644 --- a/src/web/interviews.rs +++ b/src/web/interviews.rs @@ -1,5 +1,5 @@ -//! The interview record itself: creating one, ending it, the consent that -//! gates recording, the replay events it accumulates, and the reports written +//! The interview record itself: creating one, the consent that gates +//! recording, the replay events it accumulates, and the reports written //! against it. use std::time::Instant; @@ -7,7 +7,7 @@ use std::time::Instant; use axum::body::Body; use axum::extract::{Path as UriPath, State}; use axum::http::{Request, StatusCode}; -use axum::response::{IntoResponse, Response}; +use axum::response::Response; use serde_json::{Value, json}; use crate::accounts::{ @@ -17,12 +17,8 @@ use crate::accounts::{ use crate::current_epoch_seconds_i64; use super::auth::Owner; -use super::recordings::finish_recording; use super::token::{read_body_or_refuse, read_body_with}; -use super::{ - AppState, MAX_BODY_BYTES, MAX_REPORT_BYTES, json_response, rate_limited_response, - replay_response, -}; +use super::{AppState, MAX_BODY_BYTES, MAX_REPORT_BYTES, json_response, rate_limited_response}; /// What one account posting replay events may spend in a window. /// @@ -221,43 +217,6 @@ pub(crate) async fn create_interview_handler( } } -/// The interview is over. -/// -/// One of the two ways a recording stops normally, and neither is optional: the -/// browser can be closed and the `room_finished` webhook can be lost, so the -/// pipeline has to survive either arriving alone and both arriving in any -/// order. -pub(crate) async fn end_interview_handler( - State(state): State, - UriPath(interview_id): UriPath, - Owner { accounts, user }: Owner, -) -> Response { - let Some(recorder) = state.recorder.clone() else { - return StatusCode::NO_CONTENT.into_response(); - }; - let found = { - let accounts = std::sync::Arc::clone(&accounts); - let interview_id = interview_id.clone(); - blocking(move || { - crate::recording::recording_for_interview(&accounts, &interview_id, user.id) - }) - .await - }; - match found { - // Nothing recorded, so there is nothing to stop. Not a 404: the - // interview ending is the candidate's news either way. - Ok(None) => StatusCode::NO_CONTENT.into_response(), - Ok(Some(recording)) => finish_recording(&accounts, &recorder, &recording).await, - Err(error) => { - eprintln!("could not read a recording while ending an interview: {error}"); - json_response( - StatusCode::INTERNAL_SERVER_ERROR, - json!({ "error": "Could not end the interview." }), - ) - } - } -} - /// The replay, arriving one batch at a time. /// /// Authenticated and owner-scoped like everything else about an interview, and @@ -381,34 +340,3 @@ pub(crate) async fn replay_events_handler( } } } - -/// Where a late join starts. -/// -/// The snapshot is the replay with the superseded frames dropped, and `seq` is -/// where the caller carries on from. Nothing is stored to produce it and there -/// is no cadence to configure. -pub(crate) async fn replay_snapshot_handler( - State(state): State, - UriPath(interview_id): UriPath, - Owner { accounts, user }: Owner, -) -> Response { - let missing = || { - json_response( - StatusCode::NOT_FOUND, - json!({ "code": "recording_not_found", "error": "No replay for that interview." }), - ) - }; - if state.recorder.is_none() { - return missing(); - } - let now = current_epoch_seconds_i64(); - let view = - blocking(move || crate::recording::replay_snapshot(&accounts, &interview_id, user.id, now)) - .await; - - // Gone rather than not-found on an expired or deleted replay: this account - // owns the interview and is owed the difference between "never yours" and - // "not any more". That distinction, and the two sentences carrying it, are - // `replay_response`'s, shared with the two recording routes. - replay_response(view, missing, "could not read a replay snapshot") -} diff --git a/src/web/mod.rs b/src/web/mod.rs index 03ae4e267..d25b7a796 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -578,12 +578,7 @@ pub(crate) fn web_router( "/api/interviews/{id}/recording", post(start_recording_handler).get(recording_status_handler), ) - .route("/api/interviews/{id}/end", post(end_interview_handler)) .route("/api/interviews/{id}/events", post(replay_events_handler)) - .route( - "/api/interviews/{id}/snapshot", - get(replay_snapshot_handler), - ) .route( crate::recording::WEBHOOK_ROUTE, post(recording_webhook_handler), @@ -1099,20 +1094,21 @@ fn forwarded_client(headers: &header::HeaderMap, peer: SocketAddr, hops: u32) -> .unwrap_or_else(|| peer.ip()) } -/// One answer for every replay read, so the three routes that take one cannot -/// drift apart. +/// One answer for every replay read, so the history events route and the +/// template's replay read cannot drift apart. /// /// They differ in two things and this takes both: what "no such replay" means /// to the caller, which is a recording id to one route and a room to another, /// and the sentence a read error is logged under. Everything else was written -/// out three times, including the two `410` bodies, and those are the retention -/// promise: a copy that said something slightly different would be a third -/// answer to a question the product gives one answer to. `gone_response` below -/// exists for the same reason on the route ahead of this one. +/// out three times before the fold, including the two `410` bodies, and those +/// are the retention promise: a copy that said something slightly different +/// would be a second answer to a question the product gives one answer to. +/// `recordings::gone_response` exists for the same reason on the route ahead of +/// this one. /// -/// A function pointer rather than a closure, because none of the three captures +/// A function pointer rather than a closure, because no route captures /// anything: what a route answers here is a constant, and a signature that -/// allowed a captured one would be inviting a fourth thing to differ. +/// allowed a captured one would be inviting another thing to differ. pub(crate) fn replay_response( view: rusqlite::Result, missing: fn() -> Response, @@ -1162,3 +1158,7 @@ fn replay_body(snapshot: &crate::recording::Snapshot) -> Value { .collect::>(), }) } + +#[cfg(test)] +#[path = "../../tests/unit/web.rs"] +mod tests; diff --git a/src/web/recordings/mod.rs b/src/web/recordings/mod.rs index 3e6936a48..1f15049b8 100644 --- a/src/web/recordings/mod.rs +++ b/src/web/recordings/mod.rs @@ -306,7 +306,7 @@ pub(crate) async fn recording_status_handler( /// Asks the provider to stop and moves the row to `finalizing`. /// /// Idempotent by way of the transition table: `finalizing` may become itself, -/// so the second of the two normal-end paths to arrive changes nothing. +/// so a second `room_finished` delivery changes nothing. pub(crate) async fn finish_recording( accounts: &Arc, recorder: &crate::recording::Recorder, diff --git a/tests/recording.rs b/tests/recording.rs index f335f8da7..a5945b433 100644 --- a/tests/recording.rs +++ b/tests/recording.rs @@ -918,11 +918,10 @@ pub(crate) mod lifecycle { vec!["EG_live@interview-abc12345".to_string()] ); - // The other normal-end path arriving second changes nothing, which is - // what lets a browser close and a webhook be lost independently. The - // provider is not asked again either: only the caller that moved the - // row talks to it, so `/end` racing a `room_finished` webhook sends one - // stop rather than two. + // A second stop arriving changes nothing, as when a `room_finished` + // webhook is delivered twice. The provider is not asked again either: + // only the caller that moved the row talks to it, so two deliveries + // send one stop rather than two. let recording = recording_by_id(&accounts, "rec-1").unwrap().unwrap(); let again = codetrial::recording::stop_recording( &accounts, diff --git a/tests/unit/accounts/peer/retention.rs b/tests/unit/accounts/peer/retention.rs index ef2156994..60be22ec5 100644 --- a/tests/unit/accounts/peer/retention.rs +++ b/tests/unit/accounts/peer/retention.rs @@ -112,7 +112,7 @@ fn rounds_snapshots_feedback_and_invites_go_with_their_session() { } #[test] -fn a_terminated_session_and_its_paired_lobby_entry_are_pruned() { +fn a_finalizing_session_and_its_paired_lobby_entry_are_pruned() { let a = fixture(); let now = 100 * DAY; let old = session(&a, 1, now - RETENTION_SECONDS - 1, "finalizing"); diff --git a/tests/unit/accounts/peer_settlement.rs b/tests/unit/accounts/peer_settlement.rs index faadeff90..8c30ea988 100644 --- a/tests/unit/accounts/peer_settlement.rs +++ b/tests/unit/accounts/peer_settlement.rs @@ -706,7 +706,7 @@ fn test_summary_text_is_kept_cut_at_its_limit_on_a_character_boundary() { #[test] fn ending_a_session_preserves_sealed_rounds_and_seals_unfinished_ones() { - for end in ["deadline", "cancel", "terminate"] { + for end in ["deadline", "cancel"] { let (accounts, mut session) = fixture(); activate(&mut session); let mut unfinished = session.rounds[0].clone(); @@ -739,23 +739,30 @@ fn ending_a_session_preserves_sealed_rounds_and_seals_unfinished_ones() { } #[test] -fn cancel_and_terminate_close_the_session_differently() { - for (name, status) in [("cancel", "cancelled"), ("terminate", "finalizing")] { - let (accounts, mut session) = fixture(); - activate(&mut session); - accounts - .with(|c| { - save(c, &session)?; - let body = json!({"expectedVersion":session.version}); - action(c, &mut session, 0, name, &body, 300)?.unwrap(); - assert_eq!(session.status, status); - assert_eq!(session.outcome.as_deref(), Some("partial")); - assert_eq!(session.rounds[0].sealed_at, Some(300)); - assert!(session.rounds[0].final_capture_incomplete); - Ok(()) - }) - .unwrap(); - } +fn cancel_closes_the_session_and_terminate_is_no_longer_an_action() { + let (accounts, mut session) = fixture(); + activate(&mut session); + accounts + .with(|c| { + save(c, &session)?; + let body = json!({"expectedVersion":session.version}); + let (status, version) = (session.status.clone(), session.version); + assert_eq!( + action(c, &mut session, 0, "terminate", &body, 300)?, + Err("invalid_action") + ); + assert_eq!( + (session.status.as_str(), session.version), + (status.as_str(), version) + ); + action(c, &mut session, 0, "cancel", &body, 300)?.unwrap(); + assert_eq!(session.status, "cancelled"); + assert_eq!(session.outcome.as_deref(), Some("partial")); + assert_eq!(session.rounds[0].sealed_at, Some(300)); + assert!(session.rounds[0].final_capture_incomplete); + Ok(()) + }) + .unwrap(); } #[test] diff --git a/tests/unit/web.rs b/tests/unit/web.rs new file mode 100644 index 000000000..94aef98f2 --- /dev/null +++ b/tests/unit/web.rs @@ -0,0 +1,45 @@ +use super::*; +use crate::recording::{Snapshot, SnapshotView}; + +fn missing() -> Response { + json_response( + StatusCode::NOT_FOUND, + json!({ "code": "recording_not_found" }), + ) +} + +async fn answer(view: SnapshotView) -> (StatusCode, Value) { + let response = replay_response(Ok(view), missing, "test"); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + (status, serde_json::from_slice(&bytes).unwrap()) +} + +/// The history route answers a deletion it can see before reading, so this arm +/// is reached only when the recording is deleted between that check and the +/// read. It still owes the same `410` the history route gives. +#[tokio::test] +async fn a_replay_deleted_under_the_read_is_gone_not_missing() { + let (status, body) = answer(SnapshotView::Deleted).await; + assert_eq!(status, StatusCode::GONE); + assert_eq!(body["code"], "recording_deleted"); +} + +#[tokio::test] +async fn the_replay_body_says_whether_the_replay_stopped_at_its_quota() { + for quota_exceeded in [false, true] { + let (status, body) = answer(SnapshotView::Ready(Snapshot { + seq: 4, + events: Vec::new(), + quota_exceeded, + })) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + body, + json!({ "seq": 4, "quotaExceeded": quota_exceeded, "events": [] }) + ); + } +} diff --git a/tests/web/peer_artifacts.rs b/tests/web/peer_artifacts.rs index e22aeb56b..258b25f37 100644 --- a/tests/web/peer_artifacts.rs +++ b/tests/web/peer_artifacts.rs @@ -106,7 +106,7 @@ async fn suggestions_are_end_only_and_each_member_sees_only_their_own() { ); let state = f.get(&path, 0).await; f.post( - &format!("{path}/terminate"), + &format!("{path}/cancel"), 0, json!({"expectedVersion":state["version"]}), ) diff --git a/tests/web/recording.rs b/tests/web/recording.rs index 96bc7d101..7418c7576 100644 --- a/tests/web/recording.rs +++ b/tests/web/recording.rs @@ -1993,6 +1993,56 @@ async fn a_replay_read_that_fails_is_not_reported_as_missing() { remove_database(path).await; } +/// The template is told when the replay it asks for has expired. +/// +/// This route has no `gone_response` ahead of it, so the `410` comes from the +/// shared replay answer alone. The recording template stops polling on it, +/// which makes it the status a recording past its deadline depends on. +#[tokio::test] +async fn the_recorder_is_told_when_the_replay_has_expired() { + let (base, server, path, client, cookie) = recorded_server("replay-room-expired").await; + let interview = start_interview(&client, &base, &cookie).await; + let room = "interview-abc12345"; + rusqlite::Connection::open(&path) + .unwrap() + .execute( + " + INSERT INTO recordings ( + id, account_id, interview_id, room_name, idempotency_key, + recipient_email, state, created_at, updated_at, expires_at + ) VALUES ('rec-expired', 1, ?1, ?2, ?1, 'one@example.test', 'ready', 10, 10, 1) + ", + [&interview, &room.to_string()], + ) + .unwrap(); + let token = codetrial::token::livekit_token(codetrial::token::LivekitTokenInput { + api_key: "devkey", + api_secret: "devsecret", + identity: "EG_recorder", + name: "recorder", + room, + metadata: "", + agent: false, + now_seconds: codetrial::current_epoch_seconds(), + }) + .unwrap(); + + let expired = client + .get(format!("{base}/api/recording/replay")) + .header("authorization", token) + .send() + .await + .unwrap(); + assert_eq!(expired.status(), 410); + assert_eq!( + expired.json::().await.unwrap()["code"], + "replay_expired" + ); + + server.shutdown().await; + remove_database(path).await; +} + /// The history a candidate reads about their own interviews. #[tokio::test] async fn history_lists_own_recordings_only() { @@ -2335,162 +2385,3 @@ async fn history_events_avatar_history_returns_every_state() { server.shutdown().await; remove_database(path).await; } - -/// A late join reads the snapshot, and only its own. -#[tokio::test] -async fn replay_snapshot_is_owner_scoped() { - let (base, server, path, client, cookie) = recorded_server("replay-snapshot").await; - let interview = start_interview(&client, &base, &cookie).await; - let event = |kind: &str, text: &str| envelope(kind, json!({ "text": text })); - let posted = client - .post(format!("{base}/api/interviews/{interview}/events")) - .header("cookie", cookie.clone()) - .json(&json!({ "events": [ - event("editor", "first draft"), - event("transcript", "hello"), - event("editor", "second draft"), - ] })) - .send() - .await - .unwrap(); - assert_eq!(posted.status(), 200); - - let snapshot = client - .get(format!("{base}/api/interviews/{interview}/snapshot")) - .header("cookie", cookie.clone()) - .send() - .await - .unwrap(); - assert_eq!(snapshot.status(), 200); - let body = snapshot.json::().await.unwrap(); - assert_eq!(body["seq"], 2, "the last event the snapshot accounts for"); - assert_eq!(body["quotaExceeded"], false); - assert_eq!( - body["events"] - .as_array() - .unwrap() - .iter() - .map(|event| ( - event["seq"].as_i64().unwrap(), - event["kind"].as_str().unwrap() - )) - .collect::>(), - vec![(1, "transcript"), (2, "editor")], - "the superseded editor snapshot is dropped and the transcript line is not" - ); - - { - let connection = rusqlite::Connection::open(&path).unwrap(); - connection - .execute_batch( - "INSERT INTO users (id, github_id, login, email, email_verified, created_at, updated_at) - VALUES (2, 202, 'two', 'two@example.test', 1, 1, 1); - INSERT INTO interviews (id, account_id, consent_version, consent_at) - VALUES ('int-theirs', 2, '2026-08-21', 1);", - ) - .unwrap(); - } - let theirs = client - .get(format!("{base}/api/interviews/int-theirs/snapshot")) - .header("cookie", cookie.clone()) - .send() - .await - .unwrap(); - assert_eq!(theirs.status(), 404); - - // Past the retention deadline the replay is gone rather than missing: this - // account owns the interview and is owed the difference. - rusqlite::Connection::open(&path) - .unwrap() - .execute( - " - INSERT INTO recordings ( - id, account_id, interview_id, room_name, idempotency_key, - recipient_email, state, expires_at, created_at, updated_at - ) VALUES ('rec-snap', 1, ?1, 'interview-abc12345', ?1, - 'one@example.test', 'ready', 1, 1, 1) - ", - [&interview], - ) - .unwrap(); - let expired = client - .get(format!("{base}/api/interviews/{interview}/snapshot")) - .header("cookie", cookie.clone()) - .send() - .await - .unwrap(); - assert_eq!(expired.status(), 410); - assert_eq!( - expired.json::().await.unwrap()["code"], - "replay_expired" - ); - - // And a deleted recording, which is the other half of the same promise and - // was asserted nowhere: this route has no `gone_response` ahead of it, so - // `SnapshotView::Deleted` reaches the response mapping directly here. The - // status was free to become a `404` without a test noticing, which is the - // difference between "taken away" and "never yours" going missing. - rusqlite::Connection::open(&path) - .unwrap() - .execute( - " - UPDATE recordings SET state = 'deleted', deleted_at = 5, expires_at = NULL, - room_name = NULL, recipient_email = NULL WHERE id = 'rec-snap' - ", - [], - ) - .unwrap(); - let deleted = client - .get(format!("{base}/api/interviews/{interview}/snapshot")) - .header("cookie", cookie) - .send() - .await - .unwrap(); - assert_eq!(deleted.status(), 410); - assert_eq!( - deleted.json::().await.unwrap()["code"], - "recording_deleted" - ); - - let signed_out = client - .get(format!("{base}/api/interviews/{interview}/snapshot")) - .send() - .await - .unwrap(); - assert_eq!(signed_out.status(), 401); - - server.shutdown().await; - remove_database(path).await; -} - -/// Ending an interview that recorded nothing says so, rather than failing. -/// -/// 204 and no body: the interview ending is the candidate's news whether or -/// not a recording was running, so there is nothing to report and nothing to -/// stop. A 404 would tell them the interview was never theirs. -#[tokio::test] -async fn ending_an_interview_without_a_recording_is_a_no_op() { - let (base, server, path, client, cookie) = recorded_server("end-no-recording").await; - let interview = start_interview(&client, &base, &cookie).await; - - let ended = client - .post(format!("{base}/api/interviews/{interview}/end")) - .header("cookie", cookie.clone()) - .send() - .await - .unwrap(); - assert_eq!(ended.status(), 204); - assert!(ended.bytes().await.unwrap().is_empty()); - - // Idempotent, because the browser sends this on unload and on the button. - let again = client - .post(format!("{base}/api/interviews/{interview}/end")) - .header("cookie", cookie) - .send() - .await - .unwrap(); - assert_eq!(again.status(), 204); - - server.shutdown().await; - remove_database(path).await; -} diff --git a/tests/web/routes.rs b/tests/web/routes.rs index ccbae9cf7..39d2cc257 100644 --- a/tests/web/routes.rs +++ b/tests/web/routes.rs @@ -346,9 +346,7 @@ fn router_routes_match_a_fixed_allowlist() { "/api/interviews", "/api/interviews/{id}/consent", "/api/interviews/{id}/recording", - "/api/interviews/{id}/end", "/api/interviews/{id}/events", - "/api/interviews/{id}/snapshot", "/api/recording/replay", "/api/recording/webhook", ]; @@ -399,9 +397,7 @@ async fn every_owner_scoped_route_refuses_an_anonymous_request() { (reqwest::Method::DELETE, "/api/interviews/{id}/consent"), (reqwest::Method::POST, "/api/interviews/{id}/recording"), (reqwest::Method::GET, "/api/interviews/{id}/recording"), - (reqwest::Method::POST, "/api/interviews/{id}/end"), (reqwest::Method::POST, "/api/interviews/{id}/events"), - (reqwest::Method::GET, "/api/interviews/{id}/snapshot"), (reqwest::Method::GET, "/api/recordings"), (reqwest::Method::GET, "/api/recordings/{id}"), (reqwest::Method::GET, "/api/recordings/{id}/events"),