Skip to main content

universal_exports/
held.rs

1//! Held briefs through Universal Exports: the briefs vetting held for an Operation, and an
2//! operator's release or refusal.
3//!
4//! Every route needs `mission.create` on the Operation, as approving a Mission proposal does:
5//! releasing a held brief admits work. A release returns the brief to the queue cleared of the
6//! kinds it was held for; a refusal files it as failed. Each is audited and recorded on the
7//! Operation's timeline with the brief's key, never its text.
8
9use std::sync::Arc;
10
11use ai6::directorates::registry::backend::*;
12use ai6::wire::held::RefuseRequest;
13use ai6::{AuditRecord, HeldBrief, TimelineEvent};
14use ai6_diptel::OperationId;
15use axum::Json;
16use axum::extract::{Path, State};
17use axum::http::HeaderMap;
18use serde::Serialize;
19use uuid::Uuid;
20
21use crate::{
22    ApiError, Gateway, GatewayError, authorize_operation_action, bearer,
23    ensure_operation_registered, resolve_user, unix_timestamp,
24};
25
26/// One held brief as the gateway lists it: its Registry key beside the record.
27#[non_exhaustive]
28#[derive(Debug, Clone, PartialEq, Serialize)]
29pub struct HeldBriefEntry {
30    /// The key the release and refuse routes take.
31    pub key: String,
32    /// The Operation, the brief, its vetting and when it was held.
33    #[serde(flatten)]
34    pub held: HeldBrief,
35}
36
37/// What became of a held brief.
38#[non_exhaustive]
39#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
40pub struct HeldBriefDecision {
41    /// The Operation.
42    pub operation_id: String,
43    /// The brief's Registry key.
44    pub key: String,
45    /// `queued` after a release, `refused` after a refusal.
46    pub state: &'static str,
47}
48
49fn registry_error(error: std::io::Error) -> ApiError {
50    match error.kind() {
51        std::io::ErrorKind::NotFound => ApiError::not_found(),
52        std::io::ErrorKind::AlreadyExists => ApiError::from(GatewayError::Conflict),
53        std::io::ErrorKind::InvalidInput => ApiError::bad_request(),
54        _ => ApiError::internal(),
55    }
56}
57
58fn valid_key(key: &str) -> Result<(), ApiError> {
59    if key.is_empty()
60        || key.len() > 256
61        || key
62            .chars()
63            .any(|character| character.is_control() || matches!(character, '/' | '\\'))
64    {
65        return Err(ApiError::bad_request());
66    }
67    Ok(())
68}
69
70/// Resolves the caller, checks `mission.create` on the Operation and that it exists.
71async fn authorized(
72    gateway: &Gateway,
73    headers: &HeaderMap,
74    operation_id: String,
75) -> Result<(ai6::Person, OperationId, Arc<dyn RegistryBackend>), ApiError> {
76    let person = resolve_user(gateway, bearer(headers)?).await?;
77    let operation = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
78    authorize_operation_action(gateway, person.clone(), &operation, "mission.create").await?;
79    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
80    ensure_operation_registered(&registry, &operation).await?;
81    Ok((person, operation, registry))
82}
83
84/// Audits a decision and adds it to the Operation's timeline. The audit record must be
85/// written; a timeline entry that fails is left out.
86async fn record(
87    registry: Arc<dyn RegistryBackend>,
88    person: &ai6::Person,
89    operation: &OperationId,
90    key: &str,
91    action: &'static str,
92    at: f64,
93) -> Result<(), ApiError> {
94    let audit = AuditRecord {
95        id: Uuid::new_v4().to_string(),
96        actor: crate::actor_of(person),
97        action: format!("mission.brief.{action}"),
98        operation: operation.to_string(),
99        resource: None,
100        target: key.to_owned(),
101        at,
102    };
103    let event = TimelineEvent::new("intake", action, operation.to_string(), at)
104        .mission(key)
105        .actor(person.id.clone());
106    tokio::task::spawn_blocking(move || {
107        registry.record_audit(&audit)?;
108        let _ = registry.record_event(&event);
109        Ok::<_, std::io::Error>(())
110    })
111    .await
112    .map_err(|_| ApiError::internal())?
113    .map_err(|_| ApiError::internal())
114}
115
116/// `GET /v1/user/operations/{operation_id}/held-briefs`: the briefs vetting holds, oldest
117/// first, each with its findings.
118pub(crate) async fn list(
119    State(gateway): State<Gateway>,
120    headers: HeaderMap,
121    Path(operation_id): Path<String>,
122) -> Result<Json<Vec<HeldBriefEntry>>, ApiError> {
123    let (_, operation, registry) = authorized(&gateway, &headers, operation_id).await?;
124    let operation = operation.to_string();
125    let held = tokio::task::spawn_blocking(move || {
126        registry.held_briefs(&operation, registry.limits().held.results.or_max())
127    })
128    .await
129    .map_err(|_| ApiError::internal())?
130    .map_err(registry_error)?;
131    Ok(Json(
132        held.into_iter()
133            .map(|held| HeldBriefEntry {
134                key: held.brief.key(),
135                held,
136            })
137            .collect(),
138    ))
139}
140
141/// `GET /v1/user/operations/{operation_id}/held-briefs/{key}/document`: a held brief as a
142/// document: its text is the body, why it is held and where it came from the frontmatter.
143/// Needs `mission.create`, as the list does.
144pub(crate) async fn document(
145    State(gateway): State<Gateway>,
146    headers: HeaderMap,
147    Path((operation_id, key)): Path<(String, String)>,
148) -> Result<axum::response::Response, ApiError> {
149    let key = crate::mission_key(&gateway, &key).await?;
150    valid_key(&key)?;
151    let (person, operation, registry) = authorized(&gateway, &headers, operation_id).await?;
152    let wanted = operation.to_string();
153    let held = tokio::task::spawn_blocking(move || {
154        registry.held_briefs(&wanted, registry.limits().held.results.or_max())
155    })
156    .await
157    .map_err(|_| ApiError::internal())?
158    .map_err(registry_error)?
159    .into_iter()
160    .find(|held| held.brief.key() == key)
161    .ok_or_else(ApiError::not_found)?;
162    let brief = &held.brief;
163    let findings: Vec<crate::documents::MetaValue> = held
164        .vetting
165        .findings
166        .iter()
167        .map(crate::documents::MetaValue::from_serialize)
168        .collect();
169    let mut draft = crate::documents::Draft::new("held_brief", Some(operation.as_str()))
170        .with("operation", operation.to_string())
171        .with("key", key)
172        .with("mission", brief.mission_id.clone())
173        .with("handle", brief.handle.clone())
174        .with("title", brief.title.clone())
175        .with("name", brief.name.clone())
176        .with("source", brief.source.clone())
177        .with("agent", brief.agent.clone())
178        .with("role", brief.role.clone())
179        .with("url", brief.url.clone())
180        .with("stations", brief.stations.clone())
181        .with("priority", brief.priority)
182        .with("created", brief.created.clone())
183        .with("held_at", held.held_at)
184        .with_serialized("verdict", &held.vetting.verdict)
185        .with("findings", findings);
186    if let Some(provenance) = brief.provenance.as_ref() {
187        let origin =
188            crate::documents::MetaValue::from_serialize(provenance).without_keys(&["digest"]);
189        draft = draft.with("origin", origin);
190    }
191    let body = if brief.body.trim().is_empty() {
192        brief.title.clone()
193    } else {
194        brief.body.clone()
195    };
196    let document = crate::documents::compose(&gateway, person, draft.body(body)).await?;
197    Ok(crate::documents::respond(&headers, document))
198}
199
200/// `POST /v1/user/operations/{operation_id}/held-briefs/{key}/release`: returns the brief to
201/// the queue, cleared of the kinds it was held for.
202pub(crate) async fn release(
203    State(gateway): State<Gateway>,
204    headers: HeaderMap,
205    Path((operation_id, key)): Path<(String, String)>,
206) -> Result<Json<HeldBriefDecision>, ApiError> {
207    let key = crate::mission_key(&gateway, &key).await?;
208    valid_key(&key)?;
209    let (person, operation, registry) = authorized(&gateway, &headers, operation_id).await?;
210    let now = unix_timestamp()?;
211    let store = registry.clone();
212    let (operation_key, brief_key, by) = (operation.to_string(), key.clone(), person.id.clone());
213    tokio::task::spawn_blocking(move || store.release_held(&operation_key, &brief_key, &by, now))
214        .await
215        .map_err(|_| ApiError::internal())?
216        .map_err(registry_error)?;
217    record(registry, &person, &operation, &key, "released", now).await?;
218    Ok(Json(HeldBriefDecision {
219        operation_id: operation.to_string(),
220        key,
221        state: "queued",
222    }))
223}
224
225/// `POST /v1/user/operations/{operation_id}/held-briefs/{key}/refuse`: files the brief as
226/// failed with a `refused` outcome; a Source still gets its report.
227pub(crate) async fn refuse(
228    State(gateway): State<Gateway>,
229    headers: HeaderMap,
230    Path((operation_id, key)): Path<(String, String)>,
231    Json(request): Json<RefuseRequest>,
232) -> Result<Json<HeldBriefDecision>, ApiError> {
233    let key = crate::mission_key(&gateway, &key).await?;
234    valid_key(&key)?;
235    let reason = request.reason.unwrap_or_default().trim().to_owned();
236    if !gateway
237        .config
238        .unex()
239        .text
240        .held_reason_chars
241        .allows(reason.chars().count())
242        || reason
243            .chars()
244            .any(|character| character.is_control() && character != '\n')
245    {
246        return Err(ApiError::bad_request());
247    }
248    let (person, operation, registry) = authorized(&gateway, &headers, operation_id).await?;
249    let now = unix_timestamp()?;
250    let store = registry.clone();
251    let (operation_key, brief_key, by) = (operation.to_string(), key.clone(), person.id.clone());
252    tokio::task::spawn_blocking(move || {
253        store.refuse_held(&operation_key, &brief_key, &by, &reason, now)
254    })
255    .await
256    .map_err(|_| ApiError::internal())?
257    .map_err(registry_error)?;
258    record(registry, &person, &operation, &key, "refused", now).await?;
259    Ok(Json(HeldBriefDecision {
260        operation_id: operation.to_string(),
261        key,
262        state: "refused",
263    }))
264}
265
266/// A brief withdrawn before any Station took it.
267#[non_exhaustive]
268#[derive(Debug, Clone, PartialEq, Serialize)]
269pub struct WithdrawnBrief {
270    /// The Operation.
271    pub operation_id: String,
272    /// The Mission's UID, its brief's key.
273    pub mission_id: String,
274    /// `withdrawn`.
275    pub state: &'static str,
276    /// The reason it was filed with: who withdrew it, and their note.
277    pub reason: String,
278}
279
280/// What a withdrawal filed.
281pub(crate) struct Withdrawn {
282    pub(crate) reason: String,
283    pub(crate) at: f64,
284}
285
286/// What became of a request to withdraw a brief.
287pub(crate) enum Withdrawal {
288    /// It was queued or held, and is filed as failed.
289    Done(Withdrawn),
290    /// The Operation has no such brief queued or held.
291    NotQueued,
292    /// A Station claimed it, or it finished.
293    Decided,
294}
295
296/// Withdraws the Operation's brief `key` when it is queued or held, audited as
297/// `mission.withdraw` and put on the Operation's timeline. The caller has checked
298/// `mission.control`.
299pub(crate) async fn withdraw_queued(
300    gateway: &Gateway,
301    person: &ai6::Person,
302    operation: &OperationId,
303    key: &str,
304    note: Option<String>,
305) -> Result<Withdrawal, ApiError> {
306    let note = note.unwrap_or_default().trim().to_owned();
307    if !gateway
308        .config
309        .unex()
310        .text
311        .held_reason_chars
312        .allows(note.chars().count())
313        || note
314            .chars()
315            .any(|character| character.is_control() && character != '\n')
316    {
317        return Err(ApiError::bad_request());
318    }
319    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
320    let at = unix_timestamp()?;
321    let (store, operation_key, brief_key, by) = (
322        registry.clone(),
323        operation.to_string(),
324        key.to_owned(),
325        person.id.clone(),
326    );
327    let withdrawn = tokio::task::spawn_blocking(move || {
328        store.withdraw_brief(&operation_key, &brief_key, &by, &note, at)
329    })
330    .await
331    .map_err(|_| ApiError::internal())?;
332    match withdrawn {
333        Ok(_) => {}
334        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
335            return Ok(Withdrawal::NotQueued);
336        }
337        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
338            return Ok(Withdrawal::Decided);
339        }
340        Err(error) => return Err(registry_error(error)),
341    }
342    let filed = registry.clone();
343    let brief_key = key.to_owned();
344    let reason = tokio::task::spawn_blocking(move || filed.filed_brief(&brief_key))
345        .await
346        .map_err(|_| ApiError::internal())?
347        .map_err(registry_error)?
348        .and_then(|filed| filed.outcome)
349        .and_then(|outcome| outcome.reason().map(str::to_owned))
350        .unwrap_or_else(|| format!("withdrawn by {}", person.id));
351    let audit = AuditRecord {
352        id: Uuid::new_v4().to_string(),
353        actor: crate::actor_of(person),
354        action: "mission.withdraw".to_owned(),
355        operation: operation.to_string(),
356        resource: None,
357        target: key.to_owned(),
358        at,
359    };
360    let event = TimelineEvent::new("intake", "withdrawn", operation.to_string(), at)
361        .mission(key)
362        .actor(person.id.clone());
363    tokio::task::spawn_blocking(move || {
364        registry.record_audit(&audit)?;
365        let _ = registry.record_event(&event);
366        Ok::<_, std::io::Error>(())
367    })
368    .await
369    .map_err(|_| ApiError::internal())?
370    .map_err(|_| ApiError::internal())?;
371    Ok(Withdrawal::Done(Withdrawn { reason, at }))
372}
373
374/// `POST /v1/user/operations/{operation_id}/missions/{mission_id}/withdraw`: files a brief no
375/// Station has taken, queued or held, as failed with who withdrew it and their note. Needs
376/// `mission.control`, as a cancel does.
377pub(crate) async fn withdraw(
378    State(gateway): State<Gateway>,
379    headers: HeaderMap,
380    Path((operation_id, mission_id)): Path<(String, String)>,
381    Json(request): Json<ai6::wire::notes::WithdrawNote>,
382) -> Result<Json<WithdrawnBrief>, ApiError> {
383    let key = crate::mission_key(&gateway, &mission_id).await?;
384    valid_key(&key)?;
385    let person = resolve_user(&gateway, bearer(&headers)?).await?;
386    let operation = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
387    authorize_operation_action(&gateway, person.clone(), &operation, "mission.control").await?;
388    let withdrawn = match withdraw_queued(&gateway, &person, &operation, &key, request.note).await?
389    {
390        Withdrawal::Done(withdrawn) => withdrawn,
391        Withdrawal::NotQueued => return Err(ApiError::not_found()),
392        Withdrawal::Decided => {
393            return Err(ApiError::refused(
394                axum::http::StatusCode::CONFLICT,
395                "a Station took the Mission, or it ended: use `mission cancel`".to_owned(),
396            ));
397        }
398    };
399    Ok(Json(WithdrawnBrief {
400        operation_id: operation.to_string(),
401        mission_id: key,
402        state: "withdrawn",
403        reason: withdrawn.reason,
404    }))
405}
406
407#[cfg(test)]
408mod tests {
409    use ai6::directorates::registry::backend::*;
410    use ai6::{Brief, Finding, FindingKind, Vetting};
411
412    use crate::controls::tests::{Served, served_with};
413
414    /// Operator 007 creates Missions in G; viewer 007 only reads them.
415    const ROLES: &str = r#"
416        [role.viewer]
417        actions = ["mission.read"]
418
419        [role.creator]
420        actions = ["mission.read", "mission.create"]
421
422        [[rule]]
423        subject = "person:viewer-007"
424        scope = "operation:G"
425        role = "viewer"
426
427        [[rule]]
428        subject = "person:operator-007"
429        scope = "operation:G"
430        role = "creator"
431    "#;
432
433    fn hold(served: &Served, id: &str) -> String {
434        let brief: Brief = serde_json::from_value(serde_json::json!({
435            "title": "Crash on save",
436            "body": "untrusted words",
437            "id": id,
438            "source": "source:github",
439            "operation": "G",
440        }))
441        .unwrap();
442        served.registry.submit_brief(&brief).unwrap();
443        let vetting = Vetting::from_findings(vec![
444            Finding::new(FindingKind::Duplicate, "the same title as other work")
445                .related("mission-g"),
446        ]);
447        served
448            .registry
449            .hold_brief("G", &brief.key(), &vetting, 1.0)
450            .unwrap()
451            .unwrap();
452        brief.key()
453    }
454
455    async fn call(
456        served: &Served,
457        token: &str,
458        method: reqwest::Method,
459        path: &str,
460        body: Option<serde_json::Value>,
461    ) -> reqwest::Response {
462        let mut request = reqwest::Client::new()
463            .request(method, format!("{}/v1/user/operations/{path}", served.base))
464            .bearer_auth(token);
465        if let Some(body) = body {
466            request = request.json(&body);
467        }
468        request.send().await.unwrap()
469    }
470
471    #[tokio::test]
472    async fn an_operator_lists_releases_and_refuses_held_briefs() {
473        let served = served_with(ROLES).await;
474        let released = hold(&served, "org/repo#1");
475        let refused = hold(&served, "org/repo#2");
476
477        let listed = call(
478            &served,
479            &served.operator,
480            reqwest::Method::GET,
481            "G/held-briefs",
482            None,
483        )
484        .await;
485        assert_eq!(listed.status(), 200);
486        let listed: serde_json::Value = listed.json().await.unwrap();
487        assert_eq!(listed.as_array().unwrap().len(), 2);
488        assert_eq!(listed[0]["key"], released.as_str());
489        assert_eq!(listed[0]["operation"], "G");
490        assert_eq!(listed[0]["vetting"]["verdict"], "hold");
491        assert_eq!(listed[0]["vetting"]["findings"][0]["kind"], "duplicate");
492
493        let path = format!("G/held-briefs/{released}/release");
494        let response = call(
495            &served,
496            &served.operator,
497            reqwest::Method::POST,
498            &path,
499            None,
500        )
501        .await;
502        assert_eq!(response.status(), 200);
503        let response: serde_json::Value = response.json().await.unwrap();
504        assert_eq!(response["state"], "queued");
505        assert_eq!(served.registry.list_new().unwrap()[0].key(), released);
506        let again = call(
507            &served,
508            &served.operator,
509            reqwest::Method::POST,
510            &path,
511            None,
512        )
513        .await;
514        assert_eq!(again.status(), 200, "releasing again changes nothing");
515        assert_eq!(served.registry.list_new().unwrap().len(), 1);
516        served
517            .registry
518            .claim_with_lease(
519                Some(&released),
520                "hq",
521                std::time::Duration::from_secs(60),
522                ai6::LeaseMeta::default(),
523            )
524            .unwrap()
525            .unwrap();
526        let claimed = call(
527            &served,
528            &served.operator,
529            reqwest::Method::POST,
530            &path,
531            None,
532        )
533        .await;
534        assert_eq!(claimed.status(), 409, "a placed brief is past releasing");
535
536        let path = format!("G/held-briefs/{refused}/refuse");
537        let body = serde_json::json!({ "reason": "a mirror of mission-g" });
538        let response = call(
539            &served,
540            &served.operator,
541            reqwest::Method::POST,
542            &path,
543            Some(body),
544        )
545        .await;
546        assert_eq!(response.status(), 200);
547        assert!(served.registry.held_briefs("G", 10).unwrap().is_empty());
548        let finished = served.registry.unreported_source_briefs().unwrap();
549        assert_eq!(finished[0].outcome.state(), "refused");
550        let ai6::MissionOutcome::Refused(outcome) = &finished[0].outcome else {
551            panic!("a refusal files a refused outcome");
552        };
553        assert_eq!(outcome.refused_by.as_deref(), Some("operator-007"));
554
555        let audit = served.registry.audit_records().unwrap();
556        for (action, key) in [
557            ("mission.brief.released", &released),
558            ("mission.brief.refused", &refused),
559        ] {
560            assert!(
561                audit.iter().any(|record| record.action == action
562                    && &record.target == key
563                    && record.actor == "operator-007"),
564                "{action}"
565            );
566        }
567        assert!(!format!("{audit:?}").contains("untrusted words"));
568        let actions: Vec<String> = served
569            .registry
570            .timeline_events("G")
571            .unwrap()
572            .into_iter()
573            .map(|event| event.action)
574            .collect();
575        // Each request the operator made is recorded, the repeated release too.
576        assert_eq!(actions, ["released", "released", "refused"]);
577    }
578
579    /// Operator 007 controls Missions in G; viewer 007 only reads them.
580    const CONTROL_ROLES: &str = r#"
581        [role.viewer]
582        actions = ["mission.read"]
583
584        [role.controller]
585        actions = ["mission.read", "mission.control"]
586
587        [[rule]]
588        subject = "person:viewer-007"
589        scope = "operation:G"
590        role = "viewer"
591
592        [[rule]]
593        subject = "person:operator-007"
594        scope = "operation:G"
595        role = "controller"
596    "#;
597
598    fn queue(served: &Served, id: &str) -> String {
599        let brief: Brief = serde_json::from_value(serde_json::json!({
600            "title": "Impossible work",
601            "id": id,
602            "source": "manual",
603            "operation": "G",
604            "stations": ["nowhere"],
605        }))
606        .unwrap();
607        served.registry.submit_brief(&brief).unwrap();
608        brief.key()
609    }
610
611    #[tokio::test]
612    async fn a_queued_brief_is_withdrawn_with_its_note_and_audited() {
613        let served = served_with(CONTROL_ROLES).await;
614        let key = queue(&served, "w-1");
615        let path = format!("G/missions/{key}/withdraw");
616        let body = serde_json::json!({"note": "it can never place"});
617        let viewer = call(
618            &served,
619            &served.viewer,
620            reqwest::Method::POST,
621            &path,
622            Some(body.clone()),
623        )
624        .await;
625        assert_eq!(viewer.status(), 403, "withdrawing needs mission.control");
626        let response = call(
627            &served,
628            &served.operator,
629            reqwest::Method::POST,
630            &path,
631            Some(body),
632        )
633        .await;
634        assert_eq!(response.status(), 200);
635        let response: serde_json::Value = response.json().await.unwrap();
636        assert_eq!(response["state"], "withdrawn");
637        assert_eq!(response["mission_id"], key.as_str());
638        assert_eq!(
639            response["reason"],
640            "withdrawn by operator-007: it can never place"
641        );
642        assert!(served.registry.list_new().unwrap().is_empty());
643        let filed = served.registry.filed_brief(&key).unwrap().unwrap();
644        assert_eq!(filed.state, "failed");
645        assert!(
646            served
647                .registry
648                .audit_records()
649                .unwrap()
650                .iter()
651                .any(|record| {
652                    record.action == "mission.withdraw"
653                        && record.target == key
654                        && record.actor == "operator-007"
655                })
656        );
657        let actions: Vec<String> = served
658            .registry
659            .timeline_events("G")
660            .unwrap()
661            .into_iter()
662            .map(|event| event.action)
663            .collect();
664        assert_eq!(actions, ["withdrawn"]);
665
666        let unknown = call(
667            &served,
668            &served.operator,
669            reqwest::Method::POST,
670            "G/missions/manual--nobody/withdraw",
671            Some(serde_json::json!({})),
672        )
673        .await;
674        assert_eq!(unknown.status(), 404);
675        let placed = queue(&served, "w-2");
676        served
677            .registry
678            .claim_with_lease(
679                Some(&placed),
680                "worker",
681                std::time::Duration::from_secs(60),
682                ai6::LeaseMeta::default(),
683            )
684            .unwrap()
685            .unwrap();
686        let taken = call(
687            &served,
688            &served.operator,
689            reqwest::Method::POST,
690            &format!("G/missions/{placed}/withdraw"),
691            Some(serde_json::json!({})),
692        )
693        .await;
694        assert_eq!(taken.status(), 409);
695        assert!(taken.text().await.unwrap().contains("`mission cancel`"));
696    }
697
698    /// A Mission whose brief is filed and which has no Run record: what the withdraw's refusal
699    /// sends an operator to must work, here through Headquarters.
700    #[tokio::test]
701    async fn a_cancel_of_a_mission_whose_brief_ended_reaches_a_station() {
702        let served = served_with(CONTROL_ROLES).await;
703        let key = ended(&served, "e-1");
704        let refused = call(
705            &served,
706            &served.operator,
707            reqwest::Method::POST,
708            &format!("G/missions/{key}/withdraw"),
709            Some(serde_json::json!({})),
710        )
711        .await;
712        assert_eq!(refused.status(), 409);
713        let asked = crate::controls::tests::ask(
714            &served,
715            &served.operator,
716            "G",
717            &key,
718            serde_json::json!({"action": "cancel", "idempotency_key": "e-1"}),
719        )
720        .await;
721        assert_eq!(asked.status(), 202);
722        let status: serde_json::Value = asked.json().await.unwrap();
723        assert_eq!(status["status"], "queued");
724        assert_eq!(status["station_id"], "hq");
725        let control = crate::controls::tests::take(&served, "hq").await.unwrap();
726        assert_eq!(control.action(), ai6_diptel::ControlAction::Cancel);
727
728        // Another Operation's cancel learns nothing of it.
729        let elsewhere = crate::controls::tests::ask(
730            &served,
731            &served.operator,
732            "L",
733            &key,
734            serde_json::json!({"action": "cancel", "idempotency_key": "e-2"}),
735        )
736        .await;
737        assert_ne!(elsewhere.status(), 202);
738    }
739
740    /// With no Station to ask, a Mission that already ended is settled by the gateway.
741    #[tokio::test]
742    async fn a_cancel_of_an_ended_mission_with_no_station_to_ask_is_settled_here() {
743        let served = served_with(CONTROL_ROLES).await;
744        let key = ended(&served, "e-3");
745        served
746            .registry
747            .elect("hq", std::time::Duration::from_nanos(1))
748            .unwrap();
749        std::thread::sleep(std::time::Duration::from_millis(20));
750        let asked = crate::controls::tests::ask(
751            &served,
752            &served.operator,
753            "G",
754            &key,
755            serde_json::json!({"action": "cancel", "idempotency_key": "e-3"}),
756        )
757        .await;
758        assert_eq!(asked.status(), 202);
759        let status: serde_json::Value = asked.json().await.unwrap();
760        assert_eq!(status["status"], "applied");
761        assert_eq!(status["state"], "failed");
762    }
763
764    /// Files `id`'s brief as failed, with no Run record and no lease left.
765    fn ended(served: &Served, id: &str) -> String {
766        let key = queue(served, id);
767        let claimed = served.registry.claim_new(Some(&key)).unwrap().unwrap();
768        served
769            .registry
770            .finish(
771                &claimed,
772                &ai6::MissionOutcome::failed("no"),
773                false,
774                None,
775                None,
776            )
777            .unwrap();
778        key
779    }
780
781    #[tokio::test]
782    async fn a_cancel_of_a_brief_no_station_took_withdraws_it_and_one_placed_is_recorded() {
783        let served = served_with(CONTROL_ROLES).await;
784        let key = queue(&served, "c-1");
785        let cancel = |idempotency: &str| serde_json::json!({"action": "cancel", "idempotency_key": idempotency});
786        let asked =
787            crate::controls::tests::ask(&served, &served.operator, "G", &key, cancel("c-1")).await;
788        assert_eq!(asked.status(), 202);
789        let status: serde_json::Value = asked.json().await.unwrap();
790        assert_eq!(status["status"], "applied");
791        assert_eq!(status["state"], "failed");
792        assert_eq!(status["reason"], "withdrawn by operator-007");
793        assert_eq!(
794            served.registry.filed_brief(&key).unwrap().unwrap().state,
795            "failed"
796        );
797        assert!(
798            crate::controls::tests::take(&served, "hq").await.is_none(),
799            "no Station is asked"
800        );
801        let replay =
802            crate::controls::tests::ask(&served, &served.operator, "G", &key, cancel("c-1")).await;
803        assert_eq!(
804            replay.status(),
805            200,
806            "the same key returns the same control"
807        );
808
809        // A placed brief: the cancel goes to its Station and the Registry keeps when it was asked.
810        let placed = queue(&served, "c-2");
811        served
812            .registry
813            .claim_with_lease(
814                Some(&placed),
815                "worker",
816                std::time::Duration::from_secs(60),
817                ai6::LeaseMeta {
818                    mission_id: Some((placed).to_string()),
819                    operation: Some(("G").to_string()),
820                    ..ai6::LeaseMeta::default()
821                },
822            )
823            .unwrap()
824            .unwrap();
825        let asked =
826            crate::controls::tests::ask(&served, &served.operator, "G", &placed, cancel("c-2"))
827                .await;
828        assert_eq!(asked.status(), 202);
829        let status: serde_json::Value = asked.json().await.unwrap();
830        assert_eq!(status["status"], "queued");
831        assert_eq!(status["station_id"], "worker");
832        let requests = served.registry.cancel_requests().unwrap();
833        assert!(requests.contains_key(&placed), "{requests:?}");
834    }
835
836    #[tokio::test]
837    async fn held_briefs_need_mission_create_on_their_operation() {
838        let served = served_with(ROLES).await;
839        let key = hold(&served, "org/repo#3");
840        for (method, path, body) in [
841            (reqwest::Method::GET, "G/held-briefs".to_owned(), None),
842            (
843                reqwest::Method::POST,
844                format!("G/held-briefs/{key}/release"),
845                None,
846            ),
847            (
848                reqwest::Method::POST,
849                format!("G/held-briefs/{key}/refuse"),
850                Some(serde_json::json!({})),
851            ),
852        ] {
853            let denied = call(&served, &served.viewer, method, &path, body).await;
854            assert_eq!(denied.status(), 403, "{path}");
855        }
856        let elsewhere = call(
857            &served,
858            &served.operator,
859            reqwest::Method::POST,
860            &format!("L/held-briefs/{key}/release"),
861            None,
862        )
863        .await;
864        assert_eq!(elsewhere.status(), 403, "mission.create is per Operation");
865        assert_eq!(served.registry.held_briefs("G", 10).unwrap().len(), 1);
866    }
867}