Skip to main content

universal_exports/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_debug_implementations)]
4#![warn(missing_docs)]
5
6mod access_admin;
7mod account_pins;
8mod accounts;
9mod agents;
10mod attention;
11#[cfg(test)]
12mod attention_tests;
13#[cfg(test)]
14mod board_tests;
15mod browser_link;
16mod charges;
17mod compartments;
18mod config_secrets;
19
20/// A record from a JSON value, for tests.
21#[cfg(test)]
22pub(crate) fn rec(value: serde_json::Value) -> ai6::StoredRecord {
23    ai6::StoredRecord::from_serde(&value).unwrap()
24}
25
26mod controls;
27mod documents;
28#[cfg(test)]
29mod documents_tests;
30mod factor_seal;
31#[cfg(test)]
32mod follow_up_tests;
33mod green_ink;
34mod held;
35mod issues;
36mod keys;
37pub mod liaison;
38mod libraries;
39#[cfg(all(test, feature = "cli"))]
40mod libraries_tests;
41mod login_limit;
42mod mcp_tools;
43#[cfg(test)]
44mod mcp_tools_tests;
45mod models;
46pub use browser_link::BrowserWebTransport;
47mod moneypenny;
48mod oo_preferences;
49#[cfg(test)]
50mod oo_preferences_tests;
51mod orders;
52mod page_access;
53mod pools;
54mod principals;
55#[cfg(test)]
56mod principals_tests;
57#[cfg(test)]
58mod profile_tests;
59mod providers;
60mod purge;
61#[cfg(test)]
62mod purge_tests;
63mod quarantines;
64mod refused;
65#[cfg(test)]
66mod rename_tests;
67mod reports;
68mod reviews;
69mod roster;
70mod run_attach;
71#[cfg(test)]
72mod run_attach_tests;
73mod search;
74#[cfg(test)]
75mod search_tests;
76mod second_factor;
77#[cfg(feature = "cli")]
78mod secrets;
79mod sign_in;
80mod sleepers;
81#[cfg(test)]
82mod sleepers_tests;
83mod source_facts;
84#[cfg(test)]
85mod source_facts_tests;
86mod source_reads;
87#[cfg(test)]
88mod source_reads_tests;
89mod station_auth;
90mod stations_pairing;
91#[cfg(test)]
92mod stations_pairing_tests;
93mod timeline;
94mod tls;
95mod totp_store;
96mod transcripts;
97mod tree;
98mod trials;
99mod unstarted;
100#[cfg(test)]
101mod unstarted_tests;
102mod verdicts;
103
104use ai6::TimelineDetailKey;
105use ai6::wire::login::{IssuedAccessToken, LoginRequest};
106use ai6::wire::missions::{
107    CreateMission, MissionCreated, NewMissionIssue, RenameMission, RenamedMission,
108};
109use core::future::Future;
110use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
111use std::fmt;
112use std::net::SocketAddr;
113use std::sync::Arc;
114use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
115
116use ai6::directorates::m::access::SignInContext;
117use ai6::directorates::registry::backend::*;
118use ai6::directorates::registry::mission_issues::{IssueLink, LinkRelation, LinkState};
119use ai6::{
120    AccessTokenRecord, AgentRole, Attempt, AuditRecord, Authenticator, AuthorizationRequest,
121    Authorizer, Brief, ConfigProvider, Directory, Lookup, MissionHandle, MissionProposal,
122    MissionUsage, Origin, Person, Provenance, Quarantine, SignInFactor, StationSettings, TimeLimit,
123    TimelineEvent, Verdict,
124};
125
126/// How a brief's provenance names the gateway as the place it was accepted.
127const GATEWAY_RECEIVER: &str = "universal-exports";
128use ai6_diptel::{
129    FrameReceiver, IncomingFrame, LifecycleEvent, MissionId, OperationId, RunId, RunState,
130    TerminalData, TerminalDirection, TerminalResize, lifecycle_frames, resize_frames,
131    terminal_frames,
132};
133use axum::Extension;
134use axum::body::{Body, Bytes};
135use axum::extract::ws::{CloseFrame, Message, WebSocketUpgrade};
136use axum::extract::{ConnectInfo, Path, Query, State};
137use axum::http::header::{AUTHORIZATION, COOKIE, ORIGIN, RETRY_AFTER, SET_COOKIE};
138use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};
139use axum::response::{IntoResponse, Response};
140use axum::routing::{get, post};
141use axum::{Json, Router};
142use coqui_peer::PeerId;
143use futures_util::{SinkExt, StreamExt};
144use guatiao::{Map, TryAsRef};
145use serde::{Deserialize, Serialize};
146use sha2::{Digest, Sha256};
147use subtle::ConstantTimeEq as _;
148use tokio::sync::{Mutex, broadcast, mpsc};
149use tree::{OperationTree, operation_request, resource_request};
150use uuid::Uuid;
151
152pub use access_admin::{EitherAuthorizer, LiveAccess};
153pub use agents::{AgentRoute, AgentView, RetirementNotice};
154use controls::ControlBook;
155pub use controls::ControlStatus;
156pub use factor_seal::{FactorSealer, SealError};
157pub use held::{HeldBriefDecision, HeldBriefEntry};
158pub use issues::{EntryView, IssueView, IssueWrite, MissionIssues, QuestionView, ReplyCounts};
159pub use keys::KeyProvider;
160use login_limit::LoginGuard;
161pub use login_limit::LoginLimits;
162pub use moneypenny::{AssistantConfig, PagesConfig, ViewLimits};
163pub use pools::{
164    BoardAccount, BoardClaim, BoardLogin, BoardLoginRequest, BoardUsageRead, BoardWindow, PoolBoard,
165};
166/// What is known of a Source instance, from its Operation ID, its name, its provider ID and its
167/// settings; `None` when nothing is, and the gateway falls back to the instance's own `labels`.
168pub type SourceFactsFn =
169    Arc<dyn Fn(&str, &str, &str, &ai6::ChosenSettings) -> Option<ai6::SourceFacts> + Send + Sync>;
170pub use source_facts::published_source_facts;
171
172pub use ai6::wire::{
173    BoardMission, BoardOperation, BoardPending, BoardQueueEntry, BoardRun, BoardStation,
174    BoardTheater, LaunchManifest, MissionRun, StationBoard,
175};
176pub use roster::{EffectiveOperation, RosterChange, RosterRecord, RosterRecords};
177pub use second_factor::{TOTP as TOTP_PROVIDER, totp_builder, totp_provider};
178pub use sign_in::{LiveSignIn, SignInLoader, nothing_offered};
179pub use station_auth::{DEFAULT_REPLAY_ENTRIES, SharedStationToken};
180pub use timeline::{TimelineItem, TimelinePage};
181pub use tls::tls_server_config;
182
183/// Bytes a frame's length field can grow by past an empty frame's.
184const LENGTH_GROWTH: usize = 10;
185
186/// Limits and trusted origin for one gateway instance.
187///
188/// The Station token is deliberately omitted from `Debug`; callers should load it
189/// from their scoped credential source and never log it.
190pub struct GatewayConfig {
191    public_origin: String,
192    station_token: String,
193    limits: GatewayLimits,
194    lifetimes: std::sync::RwLock<(Duration, Duration)>,
195    secret_limits: std::sync::RwLock<(usize, ai6::Limit)>,
196    login: LoginLimits,
197    unex: std::sync::RwLock<std::sync::Arc<ai6::UnexLimits>>,
198}
199
200/// Finite state, payload, fanout and input limits for one gateway.
201#[derive(Debug, Clone, Copy)]
202pub struct GatewayLimits {
203    /// Maximum number of live Runs.
204    pub max_runs: usize,
205    /// Maximum simultaneous browser connections to one Run.
206    pub max_clients_per_run: usize,
207    /// Number of value frames retained per Run.
208    pub scrollback_events: usize,
209    /// Maximum bytes in one guatiao WebSocket or ingress frame.
210    pub max_frame_bytes: usize,
211    /// Maximum browser input frames accepted per connection per second.
212    pub max_input_frames_per_second: u32,
213    /// Capacity of the bounded queue between the gateway and its Stations.
214    pub input_queue_capacity: usize,
215    /// Capacity of each per-Run viewer fanout queue.
216    pub fanout_capacity: usize,
217    /// Bytes the gateway may hold in buffers across every Run and connection; the
218    /// configuration is refused when its limits could exceed it.
219    pub buffer_budget_bytes: ai6::Limit,
220    /// Connections the gateway keeps slots for; the configuration is refused when its
221    /// Runs times connections per Run could exceed it.
222    pub client_slots: ai6::Limit,
223    /// The fewest bytes the Station token may hold.
224    pub station_token_min_bytes: usize,
225    /// The most bytes the public origin may hold.
226    pub origin_bytes: ai6::Limit,
227    /// Bytes the write buffer of a browser's socket holds at least.
228    pub socket_buffer_bytes: usize,
229}
230
231/// User identity providers used to authenticate and authorize Universal Exports requests.
232#[derive(Clone)]
233pub struct AccessProviders {
234    /// The people's sign-in providers, in the order they are asked a name and a password.
235    authenticators: Vec<Signer>,
236    /// The key provider, which answers bearer keys and nothing else.
237    keys: Option<KeyProvider>,
238    directory: Arc<dyn Directory>,
239    authorizer: Arc<dyn Authorizer>,
240    proxy_identity: Option<ProxyIdentity>,
241    /// Names the person asking for a page from the request itself; read only by the page
242    /// routes.
243    page_authenticator: Option<Arc<dyn Authenticator>>,
244    /// The ID a sign-in policy lists the page authenticator by.
245    page_authenticator_id: Option<String>,
246    /// Which methods a sign-in may use; none means each configured method alone is enough.
247    sign_in: Option<Arc<LiveSignIn>>,
248    /// Providers that check a code after an earlier step named the person; never asked for a
249    /// first factor.
250    second: Vec<Signer>,
251    /// Where a person's second factor is set up and reset, when a provider keeps one.
252    factors: Option<Arc<dyn ai6::Accounts>>,
253    /// The key one-time code secrets are sealed with; without it no factor is set up.
254    factor_sealer: Option<Arc<FactorSealer>>,
255}
256
257/// A sign-in provider and the ID a sign-in policy lists it by, when it has one.
258#[derive(Clone)]
259struct Signer {
260    id: Option<String>,
261    authenticator: Arc<dyn Authenticator>,
262}
263
264#[derive(Clone)]
265struct ProxyIdentity {
266    header: HeaderName,
267    lookup_by: String,
268    /// What the proxy sends in [`PROXY_SECRET_HEADER`]; without it no asserted identity counts.
269    secret: Option<String>,
270}
271
272/// The header in which the trusted reverse proxy proves it sent a request that asserts an
273/// identity: anything that reaches the gateway's port directly can set the identity header too.
274pub const PROXY_SECRET_HEADER: &str = "x-ai6-proxy-secret";
275
276impl AccessProviders {
277    /// The authorizer as configured, without compartments.
278    fn authorizer(&self) -> Arc<dyn Authorizer> {
279        Arc::new(ai6::KeyNarrowed::new(self.authorizer.clone()))
280    }
281
282    /// Combines the configured authentication, identity and authorization providers.
283    pub fn new(
284        authenticator: Arc<dyn Authenticator>,
285        directory: Arc<dyn Directory>,
286        authorizer: Arc<dyn Authorizer>,
287    ) -> Self {
288        Self {
289            authenticators: vec![Signer {
290                id: None,
291                authenticator,
292            }],
293            keys: None,
294            directory,
295            authorizer,
296            proxy_identity: None,
297            page_authenticator: None,
298            page_authenticator_id: None,
299            sign_in: None,
300            second: Vec::new(),
301            factors: None,
302            factor_sealer: None,
303        }
304    }
305
306    /// Adds a sign-in provider for people, asked after those already added: a name and a
307    /// password go to each in turn until one claims them. The directory stays the one given to
308    /// [`new`](Self::new).
309    #[must_use]
310    pub fn with_authenticator(mut self, authenticator: Arc<dyn Authenticator>) -> Self {
311        self.authenticators.push(Signer {
312            id: None,
313            authenticator,
314        });
315        self
316    }
317
318    /// Names the sign-in provider added last by `id`, the ID a sign-in policy lists it by.
319    /// A provider with no name is asked only when a policy lists none.
320    #[must_use]
321    pub fn named(mut self, id: impl Into<String>) -> Self {
322        if let Some(last) = self.authenticators.last_mut() {
323            last.id = Some(id.into());
324        }
325        self
326    }
327
328    /// Adds a provider that checks a one-time code once an earlier step named the person, listed
329    /// in a sign-in policy by `id`. It is never asked for a first factor. With `accounts`, people
330    /// set up and reset their factor through it.
331    #[must_use]
332    pub fn with_second_factor(
333        mut self,
334        id: impl Into<String>,
335        authenticator: Arc<dyn Authenticator>,
336        accounts: Option<Arc<dyn ai6::Accounts>>,
337    ) -> Self {
338        self.second.push(Signer {
339            id: Some(id.into()),
340            authenticator,
341        });
342        if self.factors.is_none() {
343            self.factors = accounts;
344        }
345        self
346    }
347
348    /// The key one-time code secrets are sealed with. Without a ready one setting up a factor is
349    /// refused.
350    #[must_use]
351    pub fn with_factor_sealer(mut self, sealer: Arc<FactorSealer>) -> Self {
352        self.factor_sealer = Some(sealer);
353        self
354    }
355
356    /// Lets `sign_in` decide which methods a sign-in may use. Without it each configured method
357    /// alone is enough, from anywhere. Bearer keys are outside it.
358    #[must_use]
359    pub fn with_sign_in(mut self, sign_in: Arc<LiveSignIn>) -> Self {
360        self.sign_in = Some(sign_in);
361        self
362    }
363
364    /// Lets `policy` decide which methods a sign-in may use, as it stands; no route changes it.
365    #[must_use]
366    pub fn with_sign_in_policy(
367        self,
368        policy: Arc<dyn ai6::directorates::m::access::SignInPolicy>,
369    ) -> Self {
370        self.with_sign_in(Arc::new(LiveSignIn::fixed(policy)))
371    }
372
373    /// Takes bearer keys from `keys`. A key is presented as the bearer of a request, never as a
374    /// password: the sign-in routes do not ask this provider.
375    #[must_use]
376    pub fn with_keys(mut self, keys: KeyProvider) -> Self {
377        self.keys = Some(keys);
378        self
379    }
380
381    /// Access for bearer keys alone: nobody signs in with a password. Add the key provider with
382    /// [`with_keys`](Self::with_keys).
383    pub fn keys_only(directory: Arc<dyn Directory>, authorizer: Arc<dyn Authorizer>) -> Self {
384        Self {
385            authenticators: Vec::new(),
386            keys: None,
387            directory,
388            authorizer,
389            proxy_identity: None,
390            page_authenticator: None,
391            page_authenticator_id: None,
392            sign_in: None,
393            second: Vec::new(),
394            factors: None,
395            factor_sealer: None,
396        }
397    }
398
399    /// Uses a sanitized identity header supplied by the trusted reverse proxy.
400    ///
401    /// The proxy must remove any client-provided value for this header and set
402    /// it only after authenticating the request. `lookup_by` selects the
403    /// Directory attribute used to resolve that identity (commonly `name` or
404    /// `email`).
405    pub fn from_reverse_proxy(
406        directory: Arc<dyn Directory>,
407        authorizer: Arc<dyn Authorizer>,
408        header: HeaderName,
409        lookup_by: impl Into<String>,
410    ) -> Self {
411        Self {
412            authenticators: Vec::new(),
413            keys: None,
414            directory,
415            authorizer,
416            proxy_identity: Some(ProxyIdentity {
417                header,
418                lookup_by: lookup_by.into(),
419                secret: None,
420            }),
421            page_authenticator: None,
422            page_authenticator_id: None,
423            sign_in: None,
424            second: Vec::new(),
425            factors: None,
426            factor_sealer: None,
427        }
428    }
429
430    /// Names the person asking for one of Moneypenny's pages by `authenticator`, a provider that
431    /// reads the request itself (`coqui_access_mtls`, `coqui_access_proxy`): it is given the
432    /// request's headers but cookies, its client's address, and the certificates the client
433    /// proved on [`Gateway::serve_tls`]. Only the page routes ask it; no `/v1` route does.
434    #[must_use]
435    pub fn with_page_authenticator(mut self, authenticator: Arc<dyn Authenticator>) -> Self {
436        self.page_authenticator = Some(authenticator);
437        self
438    }
439
440    /// Names the page authenticator by `id`, the ID a sign-in policy lists it by.
441    #[must_use]
442    pub fn with_page_authenticator_id(mut self, id: impl Into<String>) -> Self {
443        self.page_authenticator_id = Some(id.into());
444        self
445    }
446
447    /// Adds trusted reverse-proxy identity as a login method alongside password login.
448    pub fn with_proxy_identity(mut self, header: HeaderName, lookup_by: impl Into<String>) -> Self {
449        self.proxy_identity = Some(ProxyIdentity {
450            header,
451            lookup_by: lookup_by.into(),
452            secret: None,
453        });
454        self
455    }
456
457    /// The secret the reverse proxy sends in [`PROXY_SECRET_HEADER`] with every request; an
458    /// asserted identity is accepted only beside it, so a client that reaches the gateway's port
459    /// without the proxy (a local process among them) cannot assert one. Without a secret no
460    /// asserted identity is accepted.
461    ///
462    /// # Errors
463    ///
464    /// A message when `secret` is shorter than `min_bytes` or there is no proxy
465    /// identity to guard.
466    pub fn with_proxy_secret(
467        mut self,
468        secret: impl Into<String>,
469        min_bytes: usize,
470    ) -> Result<Self, String> {
471        let secret = secret.into();
472        if secret.len() < min_bytes {
473            return Err(format!(
474                "the proxy secret must be at least {min_bytes} characters"
475            ));
476        }
477        let proxy = self
478            .proxy_identity
479            .as_mut()
480            .ok_or("a proxy secret needs a proxy identity header")?;
481        proxy.secret = Some(secret);
482        Ok(self)
483    }
484}
485
486impl fmt::Debug for AccessProviders {
487    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
488        formatter.write_str("AccessProviders([REDACTED])")
489    }
490}
491
492impl Default for GatewayLimits {
493    fn default() -> Self {
494        Self::from(&ai6::UnexGatewayLimits::default())
495    }
496}
497
498impl From<&ai6::UnexGatewayLimits> for GatewayLimits {
499    /// The record's `[gateway]` table, an absent bound being as large as the type holds.
500    fn from(table: &ai6::UnexGatewayLimits) -> Self {
501        Self {
502            max_runs: table.runs.or_max(),
503            max_clients_per_run: table.clients_per_run.or_max(),
504            scrollback_events: table.scrollback_events.or_max(),
505            max_frame_bytes: table.frame_bytes.or_max(),
506            max_input_frames_per_second: table
507                .input_frames_per_second
508                .get()
509                .map_or(u32::MAX, |rate| u32::try_from(rate).unwrap_or(u32::MAX)),
510            input_queue_capacity: usize::try_from(table.input_queue).unwrap_or(usize::MAX),
511            fanout_capacity: usize::try_from(table.fanout).unwrap_or(usize::MAX),
512            buffer_budget_bytes: table.buffer_budget_bytes,
513            client_slots: table.client_slots,
514            socket_buffer_bytes: table.socket_buffer_bytes.or_max(),
515            station_token_min_bytes: usize::try_from(table.station_token_min_bytes)
516                .unwrap_or(usize::MAX),
517            origin_bytes: table.origin_bytes,
518        }
519    }
520}
521
522impl GatewayConfig {
523    /// Creates a gateway config and rejects limits that cannot work together: a zero where
524    /// nothing could pass, and Runs, connections and frames that could hold more than
525    /// `buffer_budget_bytes` or `client_slots` allow.
526    pub fn new(
527        public_origin: impl Into<String>,
528        station_token: impl Into<String>,
529        limits: GatewayLimits,
530        attach_token_ttl: Duration,
531        write_lease_ttl: Duration,
532    ) -> Result<Self, GatewayError> {
533        let public_origin = public_origin.into();
534        let station_token = station_token.into();
535        let authority = public_origin.strip_prefix("https://").unwrap_or_default();
536        let retained_bytes = limits.scrollback_events.checked_mul(limits.max_frame_bytes);
537        let fanout_bytes = limits.fanout_capacity.checked_mul(limits.max_frame_bytes);
538        let input_bytes = limits
539            .input_queue_capacity
540            .checked_mul(limits.max_frame_bytes);
541        let history_budget = limits
542            .max_runs
543            .checked_mul(retained_bytes.unwrap_or(usize::MAX));
544        let fanout_budget = limits
545            .max_runs
546            .checked_mul(fanout_bytes.unwrap_or(usize::MAX));
547        let socket_buffer = limits
548            .max_frame_bytes
549            .checked_mul(2)
550            .map(|bytes| bytes.max(limits.socket_buffer_bytes));
551        let socket_budget =
552            client_slots_or_max(limits).checked_mul(socket_buffer.unwrap_or(usize::MAX));
553        let over_budget = |bytes: Option<usize>| match limits.buffer_budget_bytes.get() {
554            Some(budget) => bytes.is_none_or(|bytes| bytes as u64 > budget),
555            None => false,
556        };
557        let over_slots = |slots: Option<usize>| match limits.client_slots.get() {
558            Some(budget) => slots.is_none_or(|slots| slots as u64 > budget),
559            None => false,
560        };
561        let total_buffers = history_budget
562            .and_then(|history| fanout_budget.and_then(|fanout| history.checked_add(fanout)))
563            .and_then(|buffers| buffers.checked_add(input_bytes.unwrap_or(usize::MAX)))
564            .and_then(|buffers| socket_budget.and_then(|sockets| buffers.checked_add(sockets)));
565        let client_slots = limits.max_runs.checked_mul(limits.max_clients_per_run);
566        if authority.is_empty()
567            || authority.contains(['/', '?', '#', '@'])
568            || !limits.origin_bytes.allows(public_origin.len())
569            || station_token.len() < limits.station_token_min_bytes
570            || limits.max_runs == 0
571            || limits.max_clients_per_run == 0
572            || limits.scrollback_events == 0
573            || limits.max_frame_bytes == 0
574            || limits.max_input_frames_per_second == 0
575            || limits.input_queue_capacity == 0
576            || limits.fanout_capacity == 0
577            || over_slots(client_slots)
578            || over_budget(total_buffers)
579            || attach_token_ttl.is_zero()
580            || write_lease_ttl.is_zero()
581        {
582            return Err(GatewayError::InvalidConfiguration);
583        }
584        Ok(Self {
585            public_origin: public_origin.trim_end_matches('/').to_owned(),
586            station_token,
587            limits,
588            lifetimes: std::sync::RwLock::new((attach_token_ttl, write_lease_ttl)),
589            secret_limits: std::sync::RwLock::new((
590                limits.station_token_min_bytes,
591                limits.origin_bytes,
592            )),
593            login: LoginLimits::default(),
594            unex: std::sync::RwLock::new(std::sync::Arc::default()),
595        })
596    }
597
598    /// Replaces the default `[controls]`, `[timeline]` and `[text]` limits (and `[login]`'s
599    /// pace) with the `unex` record's; the `[gateway]` table is `limits` of [`GatewayConfig::new`].
600    #[must_use]
601    pub fn with_unex_limits(self, limits: ai6::UnexLimits) -> Self {
602        self.set_unex_limits(limits);
603        self
604    }
605
606    /// Makes the gateway run by `limits` from the next request on: the `[controls]`, `[timeline]`,
607    /// `[search]`, `[attach]` and `[text]` tables, and the `[gateway]` keys read per request. What
608    /// the gateway sized when it started (queues, slots, token lifetimes, `[login]`) keeps its size.
609    pub fn set_unex_limits(&self, limits: ai6::UnexLimits) {
610        *self
611            .unex
612            .write()
613            .unwrap_or_else(std::sync::PoisonError::into_inner) = std::sync::Arc::new(limits);
614    }
615
616    /// The `unex` record's limit tables this gateway runs by now.
617    pub fn unex(&self) -> std::sync::Arc<ai6::UnexLimits> {
618        self.unex
619            .read()
620            .unwrap_or_else(std::sync::PoisonError::into_inner)
621            .clone()
622    }
623
624    /// Replaces the default limits on password and key tries at the login route.
625    #[must_use]
626    pub fn with_login_limits(mut self, login: LoginLimits) -> Self {
627        self.login = login;
628        self
629    }
630
631    /// How long an attach token lasts.
632    pub fn attach_token_ttl(&self) -> Duration {
633        self.lifetimes
634            .read()
635            .unwrap_or_else(std::sync::PoisonError::into_inner)
636            .0
637    }
638
639    /// How long a write lease lasts.
640    pub fn write_lease_ttl(&self) -> Duration {
641        self.lifetimes
642            .read()
643            .unwrap_or_else(std::sync::PoisonError::into_inner)
644            .1
645    }
646
647    /// Makes the attach tokens and write leases issued from now on last the given times; those
648    /// already issued keep theirs. A zero lifetime is refused and changes nothing.
649    pub fn set_lifetimes(
650        &self,
651        attach_token_ttl: Duration,
652        write_lease_ttl: Duration,
653    ) -> Result<(), GatewayError> {
654        if attach_token_ttl.is_zero() || write_lease_ttl.is_zero() {
655            return Err(GatewayError::InvalidConfiguration);
656        }
657        *self
658            .lifetimes
659            .write()
660            .unwrap_or_else(std::sync::PoisonError::into_inner) =
661            (attach_token_ttl, write_lease_ttl);
662        Ok(())
663    }
664
665    /// Holds the public origin and the Station token to `station_token_min_bytes` and
666    /// `origin_bytes` from now on. Both are fixed while the gateway runs, so a value they no
667    /// longer satisfy is refused and the earlier ones stay.
668    pub fn set_secret_limits(
669        &self,
670        station_token_min_bytes: usize,
671        origin_bytes: ai6::Limit,
672    ) -> Result<(), GatewayError> {
673        if self.station_token.len() < station_token_min_bytes
674            || !origin_bytes.allows(self.public_origin.len())
675        {
676            return Err(GatewayError::InvalidConfiguration);
677        }
678        *self
679            .secret_limits
680            .write()
681            .unwrap_or_else(std::sync::PoisonError::into_inner) =
682            (station_token_min_bytes, origin_bytes);
683        Ok(())
684    }
685
686    /// The `station_token_min_bytes` and `origin_bytes` the gateway holds its token and origin to.
687    pub fn secret_limits(&self) -> (usize, ai6::Limit) {
688        *self
689            .secret_limits
690            .read()
691            .unwrap_or_else(std::sync::PoisonError::into_inner)
692    }
693
694    /// The origin browser requests must match exactly.
695    pub fn public_origin(&self) -> &str {
696        &self.public_origin
697    }
698}
699
700impl fmt::Debug for GatewayConfig {
701    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702        f.debug_struct("GatewayConfig")
703            .field("public_origin", &self.public_origin)
704            .field("station_token", &"[REDACTED]")
705            .field("limits", &self.limits)
706            .field("attach_token_ttl", &self.attach_token_ttl())
707            .field("write_lease_ttl", &self.write_lease_ttl())
708            .field("login", &self.login)
709            .field("unex", &self.unex())
710            .finish()
711    }
712}
713
714/// Whether an attachment may only charge or may send terminal input.
715#[derive(Debug, Clone, Copy, PartialEq, Eq)]
716#[non_exhaustive]
717pub enum AttachMode {
718    /// Observe board state and terminal output.
719    Read,
720    /// Observe output and request terminal input through an expiring lease.
721    Write,
722}
723
724/// An authorization grant scoped to one Station, Mission, Run and mode.
725#[derive(Debug, Clone, PartialEq, Eq)]
726pub struct AttachGrant {
727    /// The project that owns this work.
728    pub operation_id: OperationId,
729    /// The unit of work that groups Runs.
730    pub mission_id: MissionId,
731    /// The provider-issued resumable operation.
732    pub run_id: RunId,
733    /// Read or write rights granted by M.
734    pub mode: AttachMode,
735}
736
737/// A queued terminal input frame sent by an attached viewer.
738#[derive(Clone, PartialEq, Eq)]
739pub struct AgentInput {
740    /// The Operation containing the Mission.
741    pub operation_id: OperationId,
742    /// The unit of work that groups Runs.
743    pub mission_id: MissionId,
744    /// The provider-issued Agent Run receiving input.
745    pub run_id: RunId,
746    /// Validated guatiao channel frame, kept as bytes.
747    pub frame: Vec<u8>,
748}
749
750impl fmt::Debug for AgentInput {
751    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
752        f.debug_struct("AgentInput")
753            .field("operation_id", &self.operation_id)
754            .field("mission_id", &self.mission_id)
755            .field("run_id", &self.run_id)
756            .field(
757                "frame",
758                &format_args!("[REDACTED; {} bytes]", self.frame.len()),
759            )
760            .finish()
761    }
762}
763
764/// A successfully consumed viewer attachment.
765pub struct Attachment {
766    /// Read or write access for this connection.
767    pub mode: AttachMode,
768    /// Schema frames and scrollback frames to send before live fanout.
769    pub replay: Vec<Vec<u8>>,
770    /// Live event stream. A lagged receiver must be disconnected.
771    pub events: broadcast::Receiver<Vec<u8>>,
772    run_id: RunId,
773    connection_id: String,
774    expires: Instant,
775}
776
777impl fmt::Debug for Attachment {
778    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
779        f.debug_struct("Attachment")
780            .field("mode", &self.mode)
781            .field("replay_frames", &self.replay.len())
782            .field("run_id", &self.run_id)
783            .field("connection_id", &"[REDACTED]")
784            .field("expires", &self.expires)
785            .finish()
786    }
787}
788
789/// Failures returned by gateway policy and bounded-state operations.
790#[derive(Debug, Clone, Copy, PartialEq, Eq)]
791#[non_exhaustive]
792pub enum GatewayError {
793    /// A required setting is absent or outside its accepted bound.
794    InvalidConfiguration,
795    /// The caller did not authenticate as a Station.
796    Unauthorized,
797    /// A grant does not match the registered Station, Mission or Run.
798    Forbidden,
799    /// A requested Mission or Run has not been registered.
800    NotFound,
801    /// A viewer, writer or prior event already occupies this bounded slot.
802    Conflict,
803    /// A frame or history event exceeded a configured bound.
804    TooLarge,
805    /// Guatiao rejected a malformed or schema-invalid frame.
806    InvalidFrame,
807    /// The one bounded queue for agent input has no capacity.
808    Backpressure,
809    /// An attachment credential is unknown, expired or already consumed.
810    InvalidCredential,
811}
812
813impl fmt::Display for GatewayError {
814    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
815        let message = match self {
816            Self::InvalidConfiguration => "gateway configuration is invalid",
817            Self::Unauthorized => "Station authentication is required",
818            Self::Forbidden => "the grant does not authorize this Station and Run",
819            Self::NotFound => "the Station or Run was not found",
820            Self::Conflict => "a bounded gateway resource is already occupied",
821            Self::TooLarge => "the frame exceeds the configured bound",
822            Self::InvalidFrame => "the guatiao frame is invalid",
823            Self::Backpressure => "the bounded input queue is full",
824            Self::InvalidCredential => "the attachment credential is invalid or expired",
825        };
826        f.write_str(message)
827    }
828}
829
830impl std::error::Error for GatewayError {}
831
832/// Gateway state shared by the HTTP handler and the Station channel.
833#[derive(Clone)]
834pub struct Gateway {
835    config: std::sync::Arc<GatewayConfig>,
836    inner: std::sync::Arc<Mutex<Inner>>,
837    input_tx: mpsc::Sender<AgentInput>,
838    input_rx: std::sync::Arc<Mutex<mpsc::Receiver<AgentInput>>>,
839    registry: Option<Arc<dyn RegistryBackend>>,
840    /// How a Station proves itself on `/v1/station/*` (see [`station_auth`]).
841    station_auth: std::sync::Arc<station_auth::StationAuth>,
842    #[cfg(feature = "cli")]
843    /// The key that signs the secret requests this gateway leaves for the Stations, and how long
844    /// each stays valid in seconds.
845    secret_requester: Option<(ai6::directorates::q::sealing::Signer, f64)>,
846    #[cfg(feature = "cli")]
847    /// The roots this gateway verifies scope-key records, Station certificates and answers against.
848    secret_trust: ai6::directorates::q::sealing::Trust,
849    access: Option<AccessProviders>,
850    roster: Option<Arc<dyn ConfigProvider>>,
851    source_facts: Option<SourceFactsFn>,
852    access_admin: Option<Arc<access_admin::LiveAccess>>,
853    compartment_reads: compartments::AuditMemory,
854    accounts: Option<Arc<dyn ai6::Accounts>>,
855    login_guard: std::sync::Arc<std::sync::RwLock<std::sync::Arc<LoginGuard>>>,
856    /// Refused resumes, apart from `login_guard` so they cost nobody a try at their password.
857    resume_guard: std::sync::Arc<std::sync::RwLock<std::sync::Arc<LoginGuard>>>,
858    controls: Arc<std::sync::Mutex<ControlBook>>,
859    control_ready: Arc<tokio::sync::Notify>,
860    assistant: Option<Arc<moneypenny::Assistant>>,
861    job_poll_max_wait: Duration,
862    pages: Option<Arc<moneypenny::pages::PageStore>>,
863    pages_config: Option<PagesConfig>,
864    /// The person each live [`StandIn`] reads as, by the SHA-256 of its bearer.
865    stand_ins: Arc<std::sync::Mutex<HashMap<String, String>>>,
866    /// Live tracker reads waiting for the Headquarters Station.
867    source_reads: Arc<source_reads::SourceReads>,
868    /// Requests for an MCP server's tools waiting for a Station.
869    mcp_tools: Arc<mcp_tools::McpTools>,
870    /// Peer-pairing requests queued for a Station, and callers waiting for answers.
871    pairing: Arc<stations_pairing::StationPairing>,
872    /// The people attached to Runs, and what waits for their Stations.
873    attach: Arc<run_attach::Relay>,
874    /// The images people send Moneypenny, kept beside the pages.
875    images: Option<Arc<moneypenny::images::ImageStore>>,
876    /// The peers Liaison serves A2A to, on links and on `/v1/a2a`.
877    liaison: Option<Arc<liaison::LiaisonConfig>>,
878    /// The key, codes and live connections of the links to people's own agents; without it
879    /// those routes answer 503.
880    agent_links: Option<Arc<moneypenny::links::Links>>,
881    browser_links: Option<Arc<browser_link::BrowserLinks>>,
882    /// The providers this gateway process has loaded, reported beside each Station's.
883    own_providers: Arc<Vec<ai6::providers::ProviderEntry>>,
884    /// What keeps this gateway from being whole while it serves: the stored records it left out
885    /// because they cannot be read, and the parts of its settings file it refused.
886    degraded: Arc<Vec<ai6::Degradation>>,
887    /// What was last written for each person seen signing in.
888    sightings: Arc<principals::Sightings>,
889    /// Sign-ins that have waited for a next step, which paces the sweep of stale ones.
890    pending_begun: Arc<std::sync::atomic::AtomicU64>,
891}
892
893/// A bearer the gateway makes for itself to read, in this process, as a person who proved who
894/// they are some other way (a page's viewer). It is never stored or sent anywhere, and it stops
895/// working when dropped.
896pub(crate) struct StandIn {
897    token: String,
898    digest: String,
899    stand_ins: Arc<std::sync::Mutex<HashMap<String, String>>>,
900}
901
902impl StandIn {
903    pub(crate) fn token(&self) -> &str {
904        &self.token
905    }
906}
907
908impl Drop for StandIn {
909    fn drop(&mut self) {
910        self.stand_ins
911            .lock()
912            .unwrap_or_else(std::sync::PoisonError::into_inner)
913            .remove(&self.digest);
914    }
915}
916
917impl fmt::Debug for Gateway {
918    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
919        f.debug_struct("Gateway")
920            .field("config", &self.config)
921            .field("state", &"[REDACTED]")
922            .finish()
923    }
924}
925
926#[derive(Default)]
927struct Inner {
928    runs: HashMap<RunId, RunRecord>,
929    missions: HashMap<(OperationId, MissionId), LaunchManifest>,
930    attach_tokens: HashMap<String, TimedGrant>,
931    connection_tickets: HashMap<String, TimedGrant>,
932    connections: HashMap<String, ActiveConnection>,
933}
934
935struct TimedGrant {
936    grant: AttachGrant,
937    expires: Instant,
938}
939
940struct ActiveConnection {
941    run_id: RunId,
942    mode: AttachMode,
943    expires: Instant,
944    input_window_started: Instant,
945    input_window_count: u32,
946    last_input_sequence: u64,
947}
948
949struct RunRecord {
950    operation_id: OperationId,
951    mission_id: MissionId,
952    lifecycle_state: Option<String>,
953    lifecycle_reason: Option<String>,
954    lifecycle_sequence: u64,
955    lifecycle_at: Option<f64>,
956    history: VecDeque<(u64, Vec<u8>)>,
957    schemas: HashMap<u64, Vec<u8>>,
958    last_sequence: u64,
959    events: broadcast::Sender<Vec<u8>>,
960    lease: Option<WriteLease>,
961    active_clients: usize,
962}
963
964struct WriteLease {
965    connection_id: String,
966    expires: Instant,
967}
968
969/// The routes that write secrets, which need a build with the Station's sealing (`cli`).
970#[cfg(feature = "cli")]
971fn secret_routes() -> Router<Gateway> {
972    Router::new()
973        .route("/v1/user/secrets", get(secrets::list))
974        .route("/v1/user/secrets/requests", post(secrets::request))
975        .route("/v1/user/secrets/requests/{id}", get(secrets::answer))
976}
977
978#[cfg(not(feature = "cli"))]
979fn secret_routes() -> Router<Gateway> {
980    Router::new()
981}
982
983impl Gateway {
984    pub(crate) fn login_guard(&self) -> std::sync::Arc<LoginGuard> {
985        self.login_guard
986            .read()
987            .unwrap_or_else(std::sync::PoisonError::into_inner)
988            .clone()
989    }
990
991    pub(crate) fn resume_guard(&self) -> std::sync::Arc<LoginGuard> {
992        self.resume_guard
993            .read()
994            .unwrap_or_else(std::sync::PoisonError::into_inner)
995            .clone()
996    }
997
998    /// Makes the login and resume routes count tries by `limits` from now on. The counts held
999    /// so far start over, so an address or name that was being held off is let through once.
1000    pub fn set_login_limits(&self, limits: &LoginLimits) {
1001        for guard in [&self.login_guard, &self.resume_guard] {
1002            *guard
1003                .write()
1004                .unwrap_or_else(std::sync::PoisonError::into_inner) =
1005                std::sync::Arc::new(LoginGuard::new(limits));
1006        }
1007    }
1008
1009    /// Creates the bounded gateway state and the one authenticated Station input queue.
1010    pub fn new(config: GatewayConfig) -> Self {
1011        let (input_tx, input_rx) = mpsc::channel(config.limits.input_queue_capacity);
1012        let login_guard = std::sync::Arc::new(std::sync::RwLock::new(std::sync::Arc::new(
1013            LoginGuard::new(&config.login),
1014        )));
1015        let resume_guard = std::sync::Arc::new(std::sync::RwLock::new(std::sync::Arc::new(
1016            LoginGuard::new(&config.login),
1017        )));
1018        let controls = ControlBook::new(config.unex().controls.clone());
1019        Self {
1020            config: std::sync::Arc::new(config),
1021            inner: std::sync::Arc::new(Mutex::new(Inner::default())),
1022            input_tx,
1023            input_rx: std::sync::Arc::new(Mutex::new(input_rx)),
1024            registry: None,
1025            station_auth: std::sync::Arc::default(),
1026            #[cfg(feature = "cli")]
1027            secret_requester: None,
1028            #[cfg(feature = "cli")]
1029            secret_trust: ai6::directorates::q::sealing::Trust::default(),
1030            access: None,
1031            roster: None,
1032            source_facts: None,
1033            access_admin: None,
1034            compartment_reads: Default::default(),
1035            accounts: None,
1036            login_guard,
1037            resume_guard,
1038            controls: Arc::new(std::sync::Mutex::new(controls)),
1039            control_ready: Arc::default(),
1040            assistant: None,
1041            job_poll_max_wait: ai6::AssistantGatewayLimits::default().max_wait.0,
1042            pages: None,
1043            pages_config: None,
1044            stand_ins: Arc::default(),
1045            source_reads: Arc::default(),
1046            mcp_tools: Arc::default(),
1047            pairing: Arc::default(),
1048            attach: Arc::default(),
1049            images: None,
1050            liaison: None,
1051            agent_links: None,
1052            browser_links: None,
1053            own_providers: Arc::default(),
1054            degraded: Arc::default(),
1055            sightings: Arc::default(),
1056            pending_begun: Arc::default(),
1057        }
1058    }
1059
1060    /// A [`StandIn`] reading as `person_id` until it is dropped.
1061    pub(crate) fn stand_in(&self, person_id: &str) -> StandIn {
1062        let token = new_secret();
1063        let digest = access_token_digest(&token);
1064        self.stand_ins
1065            .lock()
1066            .unwrap_or_else(std::sync::PoisonError::into_inner)
1067            .insert(digest.clone(), person_id.to_owned());
1068        StandIn {
1069            token,
1070            digest,
1071            stand_ins: self.stand_ins.clone(),
1072        }
1073    }
1074
1075    #[cfg(feature = "cli")]
1076    /// Signs the secret requests this gateway leaves with `signer`, each valid for `lifetime`
1077    /// seconds. Without one they are unsigned, and only a Station told to accept that acts on them.
1078    #[must_use]
1079    pub fn with_secret_requester(
1080        mut self,
1081        signer: ai6::directorates::q::sealing::Signer,
1082        lifetime: f64,
1083    ) -> Self {
1084        self.secret_requester = Some((signer, lifetime));
1085        self
1086    }
1087
1088    #[cfg(feature = "cli")]
1089    /// Verifies the scope-key records it plans from, the Station certificates it seals to and the
1090    /// answers it reports against `trust`. The default pins no root, so every secret request is
1091    /// refused until one is set.
1092    #[must_use]
1093    pub fn with_secret_trust(mut self, trust: ai6::directorates::q::sealing::Trust) -> Self {
1094        self.secret_trust = trust;
1095        self
1096    }
1097
1098    /// Creates a gateway backed by the shared Registry for user access tokens.
1099    pub fn with_registry(config: GatewayConfig, registry: Arc<dyn RegistryBackend>) -> Self {
1100        let mut gateway = Self::new(config);
1101        gateway.registry = Some(registry);
1102        gateway
1103    }
1104
1105    /// Creates a gateway backed by the shared Registry and configured user access providers.
1106    pub fn with_access(
1107        config: GatewayConfig,
1108        registry: Arc<dyn RegistryBackend>,
1109        access: AccessProviders,
1110    ) -> Self {
1111        let mut gateway = Self::with_registry(config, registry);
1112        gateway.access = Some(access);
1113        gateway
1114    }
1115
1116    /// Serves A2A to `config`'s peers: on the HTTP JSON-RPC binding at `/v1/a2a` to a person
1117    /// signed in as a peer's principal, and on links through [`Gateway::liaison`] and a
1118    /// [`liaison::LinkListener`]. Without it `/v1/a2a` answers 404.
1119    #[must_use]
1120    pub fn with_liaison(mut self, config: liaison::LiaisonConfig) -> Self {
1121        self.liaison = Some(Arc::new(config));
1122        self
1123    }
1124
1125    /// Serves the links to people's own agents: the WebSocket a relay dials at
1126    /// `/v1/assistant/agent-link` and the routes that ask for its codes and list and revoke its
1127    /// links, proving the gateway by the key kept at `identity` (made the first time, by Noise).
1128    ///
1129    /// # Errors
1130    ///
1131    /// [`GatewayError::InvalidConfiguration`] when the key cannot be read or made.
1132    pub fn with_agent_links(
1133        mut self,
1134        identity: impl AsRef<std::path::Path>,
1135    ) -> Result<Self, GatewayError> {
1136        let links = moneypenny::links::Links::open(identity.as_ref())
1137            .map_err(|_| GatewayError::InvalidConfiguration)?;
1138        self.agent_links = Some(Arc::new(links));
1139        Ok(self)
1140    }
1141
1142    /// Liaison's A2A agent over this gateway, when [`Gateway::with_liaison`] set one up.
1143    pub fn liaison(&self) -> Option<liaison::Liaison> {
1144        let config = self.liaison.clone()?;
1145        Some(liaison::Liaison::shared(self.clone(), config))
1146    }
1147
1148    /// Serves roster administration (`/v1/user/roster/...`) from `source`, the roster every
1149    /// Station reads. Edits need a source that takes changes, such as a SQL roster; without a
1150    /// source those routes answer 503.
1151    #[must_use]
1152    pub fn with_roster(mut self, source: Arc<dyn ConfigProvider>) -> Self {
1153        self.roster = Some(source);
1154        self
1155    }
1156
1157    /// Reads what is known of a Source instance (its web page, intake labels) through `facts`;
1158    /// [`published_source_facts`] reads what the Stations publish at check-in, since this gateway
1159    /// loads no Source provider. An instance `facts` knows nothing of lists no page, and takes
1160    /// intake labels from its own `labels`.
1161    #[must_use]
1162    pub fn with_source_facts(mut self, facts: SourceFactsFn) -> Self {
1163        self.source_facts = Some(facts);
1164        self
1165    }
1166
1167    /// What the Source providers say of each instance of `operation`, by the provider's ID.
1168    pub(crate) fn instance_facts(
1169        &self,
1170        operation: &ai6::Operation,
1171    ) -> Vec<(String, ai6::SourceFacts)> {
1172        operation
1173            .sources
1174            .iter()
1175            .map(|(name, instance)| {
1176                let provider = instance.provider.clone().unwrap_or_else(|| name.clone());
1177                let known = self.source_facts.as_ref().and_then(|facts| {
1178                    facts(operation.id.as_str(), name, &provider, &instance.settings)
1179                });
1180                let facts = match known {
1181                    Some(facts) => facts,
1182                    None => ai6::SourceFacts {
1183                        intake_labels: instance
1184                            .settings
1185                            .get("labels")
1186                            .and_then(|labels| <&[guatiao::Value]>::try_from(labels).ok())
1187                            .map(|labels| {
1188                                labels
1189                                    .iter()
1190                                    .filter_map(|label| <&str>::try_from(label).ok())
1191                                    .map(str::to_owned)
1192                                    .collect()
1193                            })
1194                            .unwrap_or_default(),
1195                        ..ai6::SourceFacts::default()
1196                    },
1197                };
1198                (provider, facts)
1199            })
1200            .collect()
1201    }
1202
1203    /// What this request is allowed: the access policy with what compartments add, what they
1204    /// add read once, and each read they alone allow written to the audit log.
1205    fn authorizer(&self) -> Result<Arc<compartments::CompartmentAccess>, ApiError> {
1206        let every = self.config.unex().gateway.compartment_audit.0.as_secs_f64();
1207        self.compartment_access(Some(every))
1208    }
1209
1210    /// [`authorizer`](Self::authorizer) for what only tells a person what they could read,
1211    /// which reads nothing and writes nothing.
1212    fn probing_authorizer(&self) -> Result<Arc<compartments::CompartmentAccess>, ApiError> {
1213        self.compartment_access(None)
1214    }
1215
1216    fn compartment_access(
1217        &self,
1218        audit_every: Option<f64>,
1219    ) -> Result<Arc<compartments::CompartmentAccess>, ApiError> {
1220        let access = self.access.as_ref().ok_or_else(ApiError::unavailable)?;
1221        Ok(Arc::new(compartments::CompartmentAccess::new(
1222            access.authorizer(),
1223            self.roster.clone(),
1224            self.registry.clone(),
1225            self.compartment_reads.clone(),
1226            audit_every,
1227        )))
1228    }
1229
1230    /// Serves the access administration routes (`/v1/user/access`, an Operation's `access`) over
1231    /// `access`, the policy in force.
1232    #[must_use]
1233    pub fn with_access_admin(mut self, access: Arc<access_admin::LiveAccess>) -> Self {
1234        self.access_admin = Some(access);
1235        self
1236    }
1237
1238    /// Reports the providers this gateway has loaded (its sign-in, directory and authorizer
1239    /// providers) under the host name `gateway`.
1240    #[must_use]
1241    pub fn with_own_providers(mut self, providers: Vec<ai6::providers::ProviderEntry>) -> Self {
1242        self.own_providers = Arc::new(providers);
1243        self
1244    }
1245
1246    /// Reports what keeps this gateway from being whole, on `/v1/stations` to a person who reads a
1247    /// Station.
1248    #[must_use]
1249    pub fn with_degraded(mut self, degraded: Vec<ai6::Degradation>) -> Self {
1250        self.degraded = Arc::new(degraded);
1251        self
1252    }
1253
1254    /// Serves the account routes (`/v1/user/accounts`) over `accounts`, the provider that keeps
1255    /// the accounts people sign in with.
1256    #[must_use]
1257    pub fn with_accounts(mut self, accounts: Arc<dyn ai6::Accounts>) -> Self {
1258        self.accounts = Some(accounts);
1259        self
1260    }
1261
1262    /// Moneypenny when she is on: the same handle the gateway runs her by, so a change reaches
1263    /// the next conversation or turn.
1264    pub(crate) fn assistant(&self) -> Option<Arc<moneypenny::Assistant>> {
1265        self.assistant
1266            .clone()
1267            .filter(|assistant| assistant.enabled())
1268    }
1269
1270    /// The roster Agent that is Moneypenny while she is on, as a conversation or turn that starts
1271    /// now would find her.
1272    pub fn assistant_agent(&self) -> Option<String> {
1273        self.assistant()
1274            .map(|assistant| assistant.config().agent_id().to_owned())
1275    }
1276
1277    /// Turns Moneypenny on or off and gives the conversations and turns that start from now on
1278    /// `config` (when there is one to give); a turn already running finishes as it began. A
1279    /// gateway built without [`Gateway::with_assistant`] has no one to change.
1280    pub fn set_assistant(&self, enabled: bool, config: Option<AssistantConfig>) {
1281        if let Some(assistant) = &self.assistant {
1282            if let Some(config) = config {
1283                assistant.set_config(config);
1284            }
1285            assistant.set_enabled(enabled);
1286        }
1287    }
1288
1289    /// The limits and trusted origin this gateway runs by.
1290    pub fn config(&self) -> &std::sync::Arc<GatewayConfig> {
1291        &self.config
1292    }
1293
1294    /// Serves Moneypenny, the operator's assistant: the app's conversation socket, her tools'
1295    /// MCP endpoint and the Stations' assistant routes. Her model runs on a Station as the
1296    /// roster Agent the config names. Without it the socket answers 503.
1297    #[must_use]
1298    pub fn with_assistant(mut self, config: AssistantConfig) -> Self {
1299        self.assistant = Some(Arc::new(moneypenny::Assistant::new(config)));
1300        self
1301    }
1302
1303    /// How long a Station's assistant job poll is held while Moneypenny is not served
1304    /// (`[assistant.gateway] max_wait`); once she is, her config decides.
1305    #[must_use]
1306    pub fn with_job_poll_max_wait(mut self, max_wait: Duration) -> Self {
1307        self.job_poll_max_wait = max_wait;
1308        self
1309    }
1310
1311    /// Keeps the pages Moneypenny publishes in `config.dir` and serves them: under `/pages/` on
1312    /// the API's own origin, or, with `config.origin`, only on the pages' own listener
1313    /// ([`Gateway::pages_router`]). Needs [`Gateway::with_assistant`] to publish anything.
1314    ///
1315    /// # Errors
1316    ///
1317    /// The directory cannot be made or read, or the origin is not an origin.
1318    pub fn with_pages(mut self, config: PagesConfig) -> Result<Self, GatewayError> {
1319        if let Some(origin) = &config.origin {
1320            let plain = origin.trim_end_matches('/');
1321            if !(plain.starts_with("https://") || plain.starts_with("http://"))
1322                || plain.contains(['?', '#'])
1323                || plain.matches('/').count() != 2
1324            {
1325                return Err(GatewayError::InvalidConfiguration);
1326            }
1327        }
1328        let store = moneypenny::pages::PageStore::open(config.dir.clone())
1329            .map_err(|_| GatewayError::InvalidConfiguration)?;
1330        let images = moneypenny::images::ImageStore::open(config.dir.join(".images"))
1331            .map_err(|_| GatewayError::InvalidConfiguration)?;
1332        self.images = Some(Arc::new(images));
1333        self.pages = Some(Arc::new(store));
1334        self.pages_config = Some(config);
1335        Ok(self)
1336    }
1337
1338    /// The router of the pages' own listener: page routes only, no `/v1`. `None` unless
1339    /// [`Gateway::with_pages`] gave an origin.
1340    pub fn pages_router(&self) -> Option<Router> {
1341        self.pages_config.as_ref()?.origin.as_ref()?;
1342        self.start_sweeper();
1343        Some(
1344            moneypenny::pages::pages_router()
1345                .layer(axum::extract::DefaultBodyLimit::max(0))
1346                .with_state(self.clone()),
1347        )
1348    }
1349
1350    /// Serves the pages' own listener on `address` until `shutdown`.
1351    ///
1352    /// # Errors
1353    ///
1354    /// The address cannot be bound, or there is no pages origin.
1355    pub async fn serve_pages<F>(
1356        self,
1357        address: SocketAddr,
1358        shutdown: F,
1359    ) -> Result<(), std::io::Error>
1360    where
1361        F: Future<Output = ()> + Send + 'static,
1362    {
1363        let router = self
1364            .pages_router()
1365            .ok_or_else(|| std::io::Error::other("pages have no origin of their own"))?;
1366        let listener = tokio::net::TcpListener::bind(address).await?;
1367        axum::serve(
1368            listener,
1369            router.into_make_service_with_connect_info::<SocketAddr>(),
1370        )
1371        .with_graceful_shutdown(shutdown)
1372        .await
1373    }
1374
1375    /// Starts the page sweeper once, when a runtime runs.
1376    fn start_sweeper(&self) {
1377        let Some(store) = &self.pages else {
1378            return;
1379        };
1380        if store.start_sweeper()
1381            && let Ok(runtime) = tokio::runtime::Handle::try_current()
1382        {
1383            runtime.spawn(moneypenny::page_tools::sweeper(self.clone()));
1384        }
1385    }
1386
1387    /// Checks whether a presented secret is the configured Station channel credential.
1388    pub fn authenticate_station(&self, presented: &str) -> Result<(), GatewayError> {
1389        if constant_time_eq(self.config.station_token.as_bytes(), presented.as_bytes()) {
1390            Ok(())
1391        } else {
1392            Err(GatewayError::Unauthorized)
1393        }
1394    }
1395
1396    /// Registers one active Run after authenticating the Station.
1397    pub async fn register_run(
1398        &self,
1399        station_token: &str,
1400        operation_id: OperationId,
1401        mission_id: MissionId,
1402        run_id: RunId,
1403    ) -> Result<(), GatewayError> {
1404        self.authenticate_station(station_token)?;
1405        let mut inner = self.inner.lock().await;
1406        if let Some(record) = inner.runs.get(&run_id) {
1407            if record.operation_id == operation_id && record.mission_id == mission_id {
1408                return Ok(());
1409            }
1410            return Err(GatewayError::Conflict);
1411        }
1412        if inner.runs.len() >= self.config.limits.max_runs {
1413            return Err(GatewayError::Conflict);
1414        }
1415        let (events, _) = broadcast::channel(self.config.limits.fanout_capacity);
1416        inner.runs.insert(
1417            run_id.clone(),
1418            RunRecord {
1419                operation_id,
1420                mission_id,
1421                lifecycle_state: None,
1422                lifecycle_reason: None,
1423                lifecycle_sequence: 0,
1424                lifecycle_at: None,
1425                history: VecDeque::new(),
1426                schemas: HashMap::new(),
1427                last_sequence: 0,
1428                events,
1429                lease: None,
1430                active_clients: 0,
1431            },
1432        );
1433        Ok(())
1434    }
1435
1436    /// Returns the next event cursor for an authenticated registered Run.
1437    pub async fn next_sequence(
1438        &self,
1439        station_token: &str,
1440        run_id: &RunId,
1441    ) -> Result<u64, GatewayError> {
1442        self.authenticate_station(station_token)?;
1443        let inner = self.inner.lock().await;
1444        let run = inner.runs.get(run_id).ok_or(GatewayError::NotFound)?;
1445        run.last_sequence
1446            .checked_add(1)
1447            .ok_or(GatewayError::Conflict)
1448    }
1449
1450    /// Returns the Runs, their latest lifecycle states and the Agent of each one's
1451    /// Mission.
1452    ///
1453    /// The Registry's Run records say what ended or is waiting to be checked, which no
1454    /// Station sends again after the gateway restarts; the lifecycle frames received since say
1455    /// what is happening now and win while their sequence is above zero, unless the record has
1456    /// closed. Records past `[gateway] board_runs`, the least recently updated, are left out.
1457    pub async fn board_runs(&self) -> Vec<BoardRun> {
1458        let (mut live, briefs) = {
1459            let inner = self.inner.lock().await;
1460            let briefs: HashMap<(String, String), String> = inner
1461                .missions
1462                .iter()
1463                .filter_map(|((operation, mission), brief)| {
1464                    Some((
1465                        (operation.to_string(), mission.to_string()),
1466                        brief.agent_id.clone()?,
1467                    ))
1468                })
1469                .collect();
1470            let live: BTreeMap<String, BoardRun> = inner
1471                .runs
1472                .iter()
1473                .map(|(run_id, run)| {
1474                    let operation_id = run.operation_id.to_string();
1475                    let mission_id = run.mission_id.to_string();
1476                    let agent = briefs
1477                        .get(&(operation_id.clone(), mission_id.clone()))
1478                        .cloned();
1479                    (
1480                        run_id.to_string(),
1481                        BoardRun {
1482                            operation_id,
1483                            mission_id,
1484                            run_id: run_id.to_string(),
1485                            state: run.lifecycle_state.clone(),
1486                            reason: run.lifecycle_reason.clone(),
1487                            sequence: run.lifecycle_sequence,
1488                            updated_at: run.lifecycle_at,
1489                            exposure: Vec::new(),
1490                            station_id: None,
1491                            agent,
1492                        },
1493                    )
1494                })
1495                .collect();
1496            (live, briefs)
1497        };
1498        let keep = self.config.unex().gateway.board_runs.or_max();
1499        let recorded = match self.registry.clone() {
1500            Some(registry) => tokio::task::spawn_blocking(move || registry.runs())
1501                .await
1502                .ok()
1503                .and_then(Result::ok)
1504                .unwrap_or_default(),
1505            None => Vec::new(),
1506        };
1507        // A Mission is listed once, by its latest Run: a Run a later one supersedes (a resume or
1508        // a redispatch) is history, whatever state it last reported, and its live frames are
1509        // dropped with it.
1510        let mut latest = HashMap::<String, (ai6::RunRecord, String)>::new();
1511        let mut superseded = HashSet::<String>::new();
1512        for record in recorded {
1513            let Some(provider) = record.provider_id.clone() else {
1514                continue;
1515            };
1516            match latest.get_mut(&record.mission_id) {
1517                Some(held) if held.0.number > record.number => {
1518                    superseded.insert(provider);
1519                }
1520                Some(held) => {
1521                    superseded.insert(std::mem::replace(held, (record, provider)).1);
1522                }
1523                None => {
1524                    latest.insert(record.mission_id.clone(), (record, provider));
1525                }
1526            }
1527        }
1528        for (_, provider) in latest.values() {
1529            superseded.remove(provider);
1530        }
1531        live.retain(|provider, _| !superseded.contains(provider));
1532        let mut recorded: Vec<(ai6::RunRecord, String)> = latest.into_values().collect();
1533        recorded.sort_by(|(left, _), (right, _)| {
1534            record_updated_at(right)
1535                .partial_cmp(&record_updated_at(left))
1536                .unwrap_or(std::cmp::Ordering::Equal)
1537                .then_with(|| left.id.cmp(&right.id))
1538        });
1539        let mut runs = Vec::new();
1540        for (record, provider) in recorded {
1541            let overlaid = live.remove(&provider);
1542            if runs.len() >= keep && overlaid.is_none() {
1543                continue;
1544            }
1545            let Some(operation_id) = record
1546                .operation
1547                .clone()
1548                .or_else(|| overlaid.as_ref().map(|live| live.operation_id.clone()))
1549                .or_else(|| {
1550                    briefs
1551                        .keys()
1552                        .find(|(_, mission)| *mission == record.mission_id)
1553                        .map(|(operation, _)| operation.clone())
1554                })
1555            else {
1556                continue;
1557            };
1558            let agent = briefs
1559                .get(&(operation_id.clone(), record.mission_id.clone()))
1560                .cloned();
1561            let from_record = board_run_from_record(&record, operation_id, agent);
1562            runs.push(match overlaid {
1563                Some(frames) if frames.sequence > 0 && !record.status.is_closed() => BoardRun {
1564                    exposure: from_record.exposure,
1565                    station_id: from_record.station_id,
1566                    ..frames
1567                },
1568                _ => from_record,
1569            });
1570        }
1571        // Runs the Registry has not recorded (yet), or has no Registry for.
1572        runs.extend(live.into_values());
1573        runs.sort_by(|left, right| {
1574            (&left.operation_id, &left.mission_id, &left.run_id).cmp(&(
1575                &right.operation_id,
1576                &right.mission_id,
1577                &right.run_id,
1578            ))
1579        });
1580        runs
1581    }
1582
1583    /// Returns registered Missions grouped by Station with their Runs.
1584    pub async fn board_missions(&self) -> Vec<BoardMission> {
1585        self.enrich_missions(group_missions(self.board_runs().await))
1586            .await
1587    }
1588
1589    /// Forgets the live Runs and the published brief of a Mission whose records were deleted, so
1590    /// the board stops listing them.
1591    pub(crate) async fn forget_mission(&self, operation: &str, mission: &str) {
1592        let mut inner = self.inner.lock().await;
1593        inner.runs.retain(|_, run| {
1594            run.operation_id.as_str() != operation || run.mission_id.as_str() != mission
1595        });
1596        inner
1597            .missions
1598            .retain(|(station, id), _| station.as_str() != operation || id.as_str() != mission);
1599    }
1600
1601    async fn publish_mission_brief(
1602        &self,
1603        station_token: &str,
1604        operation_id: OperationId,
1605        mission_id: MissionId,
1606        brief: LaunchManifest,
1607    ) -> Result<(), GatewayError> {
1608        self.authenticate_station(station_token)?;
1609        let mut inner = self.inner.lock().await;
1610        // AI6 is authoritative: a resumed operation can publish a refreshed manifest.
1611        inner.missions.insert((operation_id, mission_id), brief);
1612        Ok(())
1613    }
1614
1615    async fn enrich_missions(&self, mut missions: Vec<BoardMission>) -> Vec<BoardMission> {
1616        if let Some(registry) = self.registry.clone() {
1617            missions = tokio::task::spawn_blocking(move || {
1618                let mut attempts = registry.runs().map(runs_by_mission).unwrap_or_default();
1619                for mission in &mut missions {
1620                    mission.usage = registry
1621                        .mission_usage(Some(&mission.operation_id), &mission.mission_id)
1622                        .ok()
1623                        .flatten();
1624                    mission.history = attempts.remove(&mission.mission_id).unwrap_or_default();
1625                    mission.conversation_tokens =
1626                        conversation_tokens(&mission.history, mission.usage.as_ref());
1627                    if let Ok(Some(found)) = registry.resolve_mission(&mission.mission_id)
1628                        && found.mission_id == mission.mission_id
1629                    {
1630                        mission.handle = found.handle;
1631                    }
1632                }
1633                missions
1634            })
1635            .await
1636            .unwrap_or_default();
1637        }
1638        let inner = self.inner.lock().await;
1639        for mission in &mut missions {
1640            mission.brief = inner.missions.iter().find_map(|((station, id), brief)| {
1641                (station.as_str() == mission.operation_id && id.as_str() == mission.mission_id)
1642                    .then(|| brief.clone())
1643            });
1644        }
1645        missions
1646    }
1647
1648    /// Encodes and publishes one lifecycle event for a registered Run.
1649    pub async fn publish_lifecycle(
1650        &self,
1651        station_token: &str,
1652        event: LifecycleEvent,
1653    ) -> Result<(), GatewayError> {
1654        let (schema, value) = lifecycle_frames(&event).map_err(|_| GatewayError::InvalidFrame)?;
1655        self.ingest(station_token, &event.run_id, 0, schema).await?;
1656        self.ingest(station_token, &event.run_id, event.sequence, value)
1657            .await
1658    }
1659
1660    /// Encodes and publishes raw terminal output without requiring the Station to encode guatiao.
1661    pub async fn publish_terminal_output(
1662        &self,
1663        station_token: &str,
1664        run_id: RunId,
1665        sequence: u64,
1666        bytes: Vec<u8>,
1667    ) -> Result<(), GatewayError> {
1668        let terminal =
1669            TerminalData::new(run_id.clone(), sequence, TerminalDirection::Output, bytes)
1670                .map_err(|_| GatewayError::TooLarge)?;
1671        let (schema, value) = terminal_frames(&terminal).map_err(|_| GatewayError::InvalidFrame)?;
1672        self.ingest(station_token, &run_id, 0, schema).await?;
1673        self.ingest(station_token, &run_id, sequence, value).await
1674    }
1675
1676    /// The most terminal output that fits one frame of `run_id` at any sequence, and that the
1677    /// wire contract allows: what a Station is told, so that it splits longer output itself.
1678    pub fn terminal_bytes(&self, run_id: &RunId) -> usize {
1679        let header = TerminalData::new(
1680            run_id.clone(),
1681            u64::MAX,
1682            TerminalDirection::Output,
1683            Vec::new(),
1684        )
1685        .ok()
1686        .and_then(|empty| terminal_frames(&empty).ok())
1687        .map_or(usize::MAX, |(_, frame)| {
1688            frame.len().saturating_add(LENGTH_GROWTH)
1689        });
1690        self.config
1691            .limits
1692            .max_frame_bytes
1693            .saturating_sub(header)
1694            .min(ai6_diptel::MAX_TERMINAL_BYTES)
1695    }
1696
1697    /// Mints an opaque, short-lived, single-use token for an existing Run.
1698    pub async fn issue_attach_token(
1699        &self,
1700        station_token: &str,
1701        grant: AttachGrant,
1702    ) -> Result<String, GatewayError> {
1703        self.authenticate_station(station_token)?;
1704        self.store_attach_token(grant).await
1705    }
1706
1707    async fn store_attach_token(&self, grant: AttachGrant) -> Result<String, GatewayError> {
1708        let mut inner = self.inner.lock().await;
1709        let run = inner
1710            .runs
1711            .get(&grant.run_id)
1712            .ok_or(GatewayError::NotFound)?;
1713        if run.operation_id != grant.operation_id || run.mission_id != grant.mission_id {
1714            return Err(GatewayError::Forbidden);
1715        }
1716        prune_expired(&mut inner);
1717        if inner.attach_tokens.len() + inner.connection_tickets.len()
1718            >= pending_credential_capacity(&self.config)
1719        {
1720            return Err(GatewayError::Conflict);
1721        }
1722        let token = Uuid::new_v4().simple().to_string();
1723        inner.attach_tokens.insert(
1724            token.clone(),
1725            TimedGrant {
1726                grant,
1727                expires: Instant::now() + self.config.attach_token_ttl(),
1728            },
1729        );
1730        Ok(token)
1731    }
1732
1733    /// Exchanges an attach token for a cookie-only, one-connection ticket.
1734    pub async fn exchange_attach_token(&self, token: &str) -> Result<String, GatewayError> {
1735        let mut inner = self.inner.lock().await;
1736        prune_expired(&mut inner);
1737        if inner.attach_tokens.len() + inner.connection_tickets.len()
1738            >= pending_credential_capacity(&self.config)
1739        {
1740            return Err(GatewayError::Conflict);
1741        }
1742        let timed = inner
1743            .attach_tokens
1744            .remove(token)
1745            .ok_or(GatewayError::InvalidCredential)?;
1746        let ticket = Uuid::new_v4().simple().to_string();
1747        inner.connection_tickets.insert(ticket.clone(), timed);
1748        Ok(ticket)
1749    }
1750
1751    /// Consumes a connection ticket and grants one bounded viewer slot.
1752    ///
1753    /// The returned replay starts with the latest schema announcement for each
1754    /// channel, followed by scrollback newer than `after_sequence`. Where that scrollback starts
1755    /// later than `after_sequence` or skips a sequence, a [`TerminalGap`](ai6_diptel::TerminalGap)
1756    /// says so, ahead of the frame after it.
1757    pub async fn attach(
1758        &self,
1759        run_id: &RunId,
1760        ticket: &str,
1761        after_sequence: u64,
1762    ) -> Result<Attachment, GatewayError> {
1763        let mut inner = self.inner.lock().await;
1764        prune_expired(&mut inner);
1765        let timed = inner
1766            .connection_tickets
1767            .remove(ticket)
1768            .ok_or(GatewayError::InvalidCredential)?;
1769        if &timed.grant.run_id != run_id {
1770            return Err(GatewayError::Forbidden);
1771        }
1772        self.activate_attachment(&mut inner, timed, after_sequence)
1773    }
1774
1775    fn activate_attachment(
1776        &self,
1777        inner: &mut Inner,
1778        timed: TimedGrant,
1779        after_sequence: u64,
1780    ) -> Result<Attachment, GatewayError> {
1781        let run_id = &timed.grant.run_id;
1782        let run = inner.runs.get_mut(run_id).ok_or(GatewayError::NotFound)?;
1783        if run.operation_id != timed.grant.operation_id || run.mission_id != timed.grant.mission_id
1784        {
1785            return Err(GatewayError::Forbidden);
1786        }
1787        if run.active_clients >= self.config.limits.max_clients_per_run {
1788            return Err(GatewayError::Conflict);
1789        }
1790        let now = Instant::now();
1791        if timed.grant.mode == AttachMode::Write
1792            && run.lease.as_ref().is_some_and(|lease| lease.expires > now)
1793        {
1794            return Err(GatewayError::Conflict);
1795        }
1796        let connection_id = Uuid::new_v4().simple().to_string();
1797        let connection_expires = timed.expires;
1798        let lease_expires = (now + self.config.write_lease_ttl()).min(connection_expires);
1799        if timed.grant.mode == AttachMode::Write {
1800            run.lease = Some(WriteLease {
1801                connection_id: connection_id.clone(),
1802                expires: lease_expires,
1803            });
1804        }
1805        let mut replay: Vec<_> = run.schemas.values().cloned().collect();
1806        let mut position = after_sequence;
1807        for (sequence, frame) in run
1808            .history
1809            .iter()
1810            .filter(|(sequence, _)| *sequence > after_sequence)
1811        {
1812            if let Some([schema, gap]) = gap_between(run_id, position, *sequence)? {
1813                replay.extend([schema, gap]);
1814            }
1815            replay.push(frame.clone());
1816            position = *sequence;
1817        }
1818        let events = run.events.subscribe();
1819        run.active_clients += 1;
1820        inner.connections.insert(
1821            connection_id.clone(),
1822            ActiveConnection {
1823                run_id: run_id.clone(),
1824                mode: timed.grant.mode,
1825                expires: connection_expires,
1826                input_window_started: now,
1827                input_window_count: 0,
1828                last_input_sequence: 0,
1829            },
1830        );
1831        Ok(Attachment {
1832            mode: timed.grant.mode,
1833            replay,
1834            events,
1835            run_id: run_id.clone(),
1836            connection_id,
1837            expires: connection_expires,
1838        })
1839    }
1840
1841    /// Validates and records a Station-originated guatiao frame, then fans it out.
1842    pub async fn ingest(
1843        &self,
1844        station_token: &str,
1845        run_id: &RunId,
1846        sequence: u64,
1847        frame: Vec<u8>,
1848    ) -> Result<(), GatewayError> {
1849        self.authenticate_station(station_token)?;
1850        if frame.len() > self.config.limits.max_frame_bytes {
1851            return Err(GatewayError::TooLarge);
1852        }
1853        let mut inner = self.inner.lock().await;
1854        let transition = self.ingest_locked(&mut inner, run_id, sequence, frame)?;
1855        drop(inner);
1856        if let Some(transition) = transition {
1857            timeline::record_transition(self, transition).await;
1858        }
1859        Ok(())
1860    }
1861
1862    /// Validates, records and fans out one frame; returns the lifecycle transition it made.
1863    fn ingest_locked(
1864        &self,
1865        inner: &mut Inner,
1866        run_id: &RunId,
1867        sequence: u64,
1868        frame: Vec<u8>,
1869    ) -> Result<Option<timeline::Transition>, GatewayError> {
1870        let run = inner.runs.get_mut(run_id).ok_or(GatewayError::NotFound)?;
1871        let mut receiver = guatiao::value::wire::channel::Receiver::new();
1872        for schema in run.schemas.values() {
1873            receiver
1874                .accept(schema)
1875                .map_err(|_| GatewayError::InvalidFrame)?;
1876        }
1877        let received = receiver
1878            .accept(&frame)
1879            .map_err(|_| GatewayError::InvalidFrame)?;
1880        let channel = match received {
1881            guatiao::value::wire::channel::Received::Schema(channel) => channel,
1882            guatiao::value::wire::channel::Received::Value { channel, .. } => channel,
1883            guatiao::value::wire::channel::Received::Closed(channel) => channel,
1884        };
1885        if !matches!(channel, 1 | 2) {
1886            return Err(GatewayError::InvalidFrame);
1887        }
1888        let is_value = matches!(
1889            &received,
1890            guatiao::value::wire::channel::Received::Value { .. }
1891        );
1892        if (is_value && (sequence == 0 || sequence <= run.last_sequence))
1893            || (!is_value && sequence != 0)
1894        {
1895            return Err(GatewayError::Conflict);
1896        }
1897        if matches!(
1898            &received,
1899            guatiao::value::wire::channel::Received::Schema(_)
1900        ) && run.schemas.get(&channel) == Some(&frame)
1901        {
1902            return Ok(None);
1903        }
1904        match &received {
1905            guatiao::value::wire::channel::Received::Value { channel: 1, value } => {
1906                validate_lifecycle_value(
1907                    value,
1908                    &run.operation_id,
1909                    &run.mission_id,
1910                    run_id,
1911                    sequence,
1912                )?
1913            }
1914            guatiao::value::wire::channel::Received::Value { channel: 2, value } => {
1915                validate_terminal_output(
1916                    value,
1917                    run_id,
1918                    sequence,
1919                    self.config.limits.max_frame_bytes,
1920                )?
1921            }
1922            _ => {}
1923        }
1924        let lifecycle_state = match &received {
1925            guatiao::value::wire::channel::Received::Value { channel: 1, value } => {
1926                let map: &Map = value.try_as_ref().ok_or(GatewayError::InvalidFrame)?;
1927                let reason = match map.get("reason") {
1928                    Some(reason) => Some(
1929                        <&str>::try_from(reason)
1930                            .ok()
1931                            .filter(|reason| ai6_diptel::valid_reason(reason))
1932                            .ok_or(GatewayError::InvalidFrame)?
1933                            .to_owned(),
1934                    ),
1935                    None => None,
1936                };
1937                Some((read_text(map, "state")?.to_owned(), reason))
1938            }
1939            _ => None,
1940        };
1941        match received {
1942            guatiao::value::wire::channel::Received::Schema(_) => {
1943                run.schemas.insert(channel, frame.clone());
1944            }
1945            guatiao::value::wire::channel::Received::Closed(_) => {
1946                run.schemas.remove(&channel);
1947            }
1948            guatiao::value::wire::channel::Received::Value { .. } => {}
1949        }
1950        let mut transition = None;
1951        if is_value {
1952            // A viewer that is past the gap's start ignores it, so there is no need to know here
1953            // what each has seen.
1954            if let Some(frames) = gap_between(run_id, run.last_sequence, sequence)? {
1955                for frame in frames {
1956                    let _ = run.events.send(frame);
1957                }
1958            }
1959            run.last_sequence = sequence;
1960            if let Some((state, reason)) = lifecycle_state {
1961                let at = SystemTime::now()
1962                    .duration_since(UNIX_EPOCH)
1963                    .map_or(0.0, |elapsed| elapsed.as_secs_f64());
1964                // A repeated state is a re-publication, not a transition.
1965                if run.lifecycle_state.as_deref() != Some(state.as_str()) {
1966                    transition = Some(timeline::Transition {
1967                        operation: run.operation_id.to_string(),
1968                        mission: run.mission_id.to_string(),
1969                        run: run_id.to_string(),
1970                        state: state.clone(),
1971                        station: None,
1972                        at,
1973                    });
1974                }
1975                run.lifecycle_state = Some(state);
1976                run.lifecycle_reason = reason;
1977                run.lifecycle_sequence = sequence;
1978                run.lifecycle_at = Some(at);
1979            }
1980            run.history.push_back((sequence, frame.clone()));
1981            while run.history.len() > self.config.limits.scrollback_events {
1982                run.history.pop_front();
1983            }
1984        }
1985        let _ = run.events.send(frame);
1986        if let Some(transition) = &mut transition {
1987            transition.station = inner
1988                .missions
1989                .iter()
1990                .find(|((operation, mission), _)| {
1991                    operation.as_str() == transition.operation
1992                        && mission.as_str() == transition.mission
1993                })
1994                .map(|(_, brief)| brief.station_id.clone());
1995        }
1996        Ok(transition)
1997    }
1998
1999    /// Queues one browser frame for the Station after confirming an active write lease.
2000    pub async fn submit_input(
2001        &self,
2002        run_id: &RunId,
2003        connection_id: &str,
2004        frame: Vec<u8>,
2005    ) -> Result<(), GatewayError> {
2006        if frame.len() > self.config.limits.max_frame_bytes {
2007            return Err(GatewayError::TooLarge);
2008        }
2009        let input_sequence = validate_input_frame(run_id, &frame)?;
2010        let mut inner = self.inner.lock().await;
2011        let now = Instant::now();
2012        let connection = inner
2013            .connections
2014            .get(connection_id)
2015            .ok_or(GatewayError::InvalidCredential)?;
2016        if &connection.run_id != run_id
2017            || connection.mode != AttachMode::Write
2018            || connection.expires <= now
2019        {
2020            return Err(GatewayError::Forbidden);
2021        }
2022        if input_sequence <= connection.last_input_sequence {
2023            return Err(GatewayError::Conflict);
2024        }
2025        if let Some(run) = inner.runs.get(run_id)
2026            && !run
2027                .lease
2028                .as_ref()
2029                .is_some_and(|lease| lease.connection_id == connection_id && lease.expires > now)
2030        {
2031            return Err(GatewayError::Forbidden);
2032        }
2033        let connection = inner
2034            .connections
2035            .get_mut(connection_id)
2036            .ok_or(GatewayError::InvalidCredential)?;
2037        if now.duration_since(connection.input_window_started) >= Duration::from_secs(1) {
2038            connection.input_window_started = now;
2039            connection.input_window_count = 0;
2040        }
2041        if connection.input_window_count >= self.config.limits.max_input_frames_per_second {
2042            return Err(GatewayError::Backpressure);
2043        }
2044        connection.input_window_count += 1;
2045        connection.last_input_sequence = input_sequence;
2046        let run = inner.runs.get(run_id).ok_or(GatewayError::NotFound)?;
2047        let input = AgentInput {
2048            operation_id: run.operation_id.clone(),
2049            mission_id: run.mission_id.clone(),
2050            run_id: run_id.clone(),
2051            frame,
2052        };
2053        self.input_tx
2054            .try_send(input)
2055            .map_err(|_| GatewayError::Backpressure)
2056    }
2057
2058    /// Releases a viewer slot and its write lease when a socket closes.
2059    pub async fn disconnect(&self, attachment: Attachment) {
2060        self.disconnect_connection(&attachment.run_id, &attachment.connection_id)
2061            .await;
2062    }
2063
2064    /// Releases an active connection by its non-secret internal handle.
2065    pub async fn disconnect_connection(&self, run_id: &RunId, connection_id: &str) {
2066        let mut inner = self.inner.lock().await;
2067        if inner.connections.remove(connection_id).is_none() {
2068            return;
2069        }
2070        if let Some(run) = inner.runs.get_mut(run_id) {
2071            run.active_clients = run.active_clients.saturating_sub(1);
2072            if run
2073                .lease
2074                .as_ref()
2075                .is_some_and(|lease| lease.connection_id == connection_id)
2076            {
2077                run.lease = None;
2078            }
2079        }
2080    }
2081
2082    /// Waits for the next terminal input from an authenticated Station connection.
2083    pub async fn receive_agent_input(&self) -> Option<AgentInput> {
2084        self.input_rx.lock().await.recv().await
2085    }
2086
2087    /// Waits at most `wait` for the next input; `None` when none came.
2088    pub async fn receive_agent_input_within(&self, wait: Duration) -> Option<AgentInput> {
2089        tokio::time::timeout(wait, self.receive_agent_input())
2090            .await
2091            .ok()
2092            .flatten()
2093    }
2094
2095    /// Returns the configured public HTTPS origin for same-origin checks.
2096    pub fn public_origin(&self) -> &str {
2097        self.config.public_origin()
2098    }
2099
2100    /// Returns the Axum service for the Station channel, browser attach and terminal sockets.
2101    pub fn router(self) -> Router {
2102        let max_frame_bytes = self.config.limits.max_frame_bytes;
2103        self.start_sweeper();
2104        if let (Some(assistant), Some(registry)) = (&self.assistant, &self.registry) {
2105            assistant.start_log(registry.clone());
2106        }
2107        let own_origin = self
2108            .pages_config
2109            .as_ref()
2110            .is_some_and(|config| config.origin.is_some());
2111        let pages = (self.pages.is_some() && !own_origin)
2112            .then(|| Router::new().nest("/pages", moneypenny::pages::pages_router()));
2113        let base = Router::new()
2114            .route(
2115                "/v1/station/assistant/pages/{digest}/{*path}",
2116                axum::routing::put(moneypenny::page_tools::upload)
2117                    .layer(axum::extract::DefaultBodyLimit::disable()),
2118            )
2119            .route(
2120                "/v1/station/assistant/pages/{digest}/done",
2121                post(moneypenny::page_tools::done),
2122            )
2123            .route("/v1/user/pages", get(moneypenny::page_tools::list))
2124            .route(
2125                "/v1/user/pages/{id}",
2126                axum::routing::delete(moneypenny::page_tools::delete),
2127            )
2128            .route(
2129                "/v1/user/pages/{id}/open",
2130                post(moneypenny::page_tools::open),
2131            )
2132            .route(
2133                "/v1/user/pages/{id}/surface",
2134                get(moneypenny::page_tools::surface),
2135            )
2136            .route(
2137                "/v1/user/pages/{id}/feeds/allow",
2138                post(moneypenny::page_tools::allow_feeds),
2139            )
2140            .route(
2141                "/v1/user/pages/{id}/feeds/{name}",
2142                get(moneypenny::page_tools::feed),
2143            )
2144            .route(
2145                "/v1/user/pages/{id}/remember",
2146                post(moneypenny::page_tools::remember),
2147            )
2148            .route(
2149                "/v1/user/pages/{id}/replacement",
2150                post(moneypenny::page_tools::replacement),
2151            )
2152            .route(
2153                "/v1/user/pages/{id}/shares",
2154                axum::routing::put(moneypenny::page_tools::share),
2155            )
2156            .route(
2157                "/v1/user/pages/{id}/public",
2158                axum::routing::put(moneypenny::page_tools::public),
2159            );
2160        let router = Router::new()
2161            .route("/health", get(health))
2162            .route("/v1/board", get(board))
2163            .route("/v1/stations", get(stations))
2164            .route(
2165                "/v1/user/stations/{station_id}/settings",
2166                get(get_user_station_settings).put(put_user_station_settings),
2167            )
2168            .route("/v1/missions", get(missions))
2169            .route("/v1/runs/{run_id}", get(filed_run))
2170            .route("/v1/missions/search", get(search::search))
2171            .route(
2172                "/v1/user/operations/{operation_id}/missions/backfill",
2173                post(backfill_missions),
2174            )
2175            .route(
2176                "/v1/missions/{id}/products",
2177                get(compartments::mission_products),
2178            )
2179            .route("/v1/missions/{id}/reports", get(reports::of_mission))
2180            .route("/v1/reports", get(reports::list).post(reports::file))
2181            .route("/v1/reports/clearances", get(reports::clearances))
2182            .route(
2183                "/v1/reports/clearances/{subject}",
2184                axum::routing::put(reports::grant).delete(reports::revoke),
2185            )
2186            .route("/v1/reports/sources/{key}", get(reports::source))
2187            .route(
2188                "/v1/reports/{id}",
2189                get(reports::show)
2190                    .put(reports::change)
2191                    .delete(reports::forget),
2192            )
2193            .route("/v1/reports/{id}/versions", get(reports::versions))
2194            .route("/v1/reports/{id}/document", get(reports::document))
2195            .route("/v1/reports/import", post(reports::import))
2196            .route(
2197                "/v1/reports/{id}/reopen",
2198                post(reports::reopen),
2199            )
2200            .route(
2201                "/v1/reports/{id}/markings",
2202                axum::routing::put(reports::mark),
2203            )
2204            .route(
2205                "/v1/reports/{id}/assessment",
2206                axum::routing::put(reports::assess),
2207            )
2208            .route(
2209                "/v1/user/operations/{operation_id}/missions",
2210                post(create_user_mission),
2211            )
2212            .route(
2213                "/v1/user/operations/{operation_id}/mission-proposals",
2214                get(list_user_mission_proposals),
2215            )
2216            .route(
2217                "/v1/user/operations/{operation_id}/placement-preview",
2218                get(placement_preview),
2219            )
2220            .route(
2221                "/v1/user/operations/{operation_id}/mission-proposals/{proposal_id}/approve",
2222                post(approve_user_mission_proposal),
2223            )
2224            .route(
2225                "/v1/user/operations/{operation_id}/mission-proposals/{proposal_id}/reject",
2226                post(reject_user_mission_proposal),
2227            )
2228            .route(
2229                "/v1/user/operations/{operation_id}/source-item",
2230                get(source_reads::item),
2231            )
2232            .route(
2233                "/v1/user/operations/{operation_id}/source-items",
2234                get(source_reads::items),
2235            )
2236            .route(
2237                "/v1/user/operations/{operation_id}/missions/{mission_id}/issues",
2238                get(issues::list).post(issues::link),
2239            )
2240            .route(
2241                "/v1/user/operations/{operation_id}/missions/{mission_id}/issues/{reference}",
2242                axum::routing::delete(issues::unlink),
2243            )
2244            .route(
2245                "/v1/user/operations/{operation_id}/missions/{mission_id}/issues/{reference}/accept",
2246                post(issues::accept),
2247            )
2248            .route(
2249                "/v1/user/operations/{operation_id}/missions/{mission_id}/issues/{reference}/comments",
2250                post(issues::comment),
2251            )
2252            .route(
2253                "/v1/user/operations/{operation_id}/missions/{mission_id}/issues/{reference}/update",
2254                post(issues::update),
2255            )
2256            .route(
2257                "/v1/user/operations/{operation_id}/issues",
2258                post(issues::create),
2259            )
2260            .route(
2261                "/v1/user/operations/{operation_id}/issue-proposals",
2262                get(issues::proposals),
2263            )
2264            .route(
2265                "/v1/user/operations/{operation_id}/issue-proposals/{id}",
2266                get(issues::proposal),
2267            )
2268            .route(
2269                "/v1/user/operations/{operation_id}/issue-proposals/{id}/approve",
2270                post(issues::approve),
2271            )
2272            .route(
2273                "/v1/user/operations/{operation_id}/issue-proposals/{id}/reject",
2274                post(issues::reject),
2275            )
2276            .route(
2277                "/v1/user/operations/{operation_id}/held-briefs",
2278                get(held::list),
2279            )
2280            .route(
2281                "/v1/user/operations/{operation_id}/held-briefs/{key}/release",
2282                post(held::release),
2283            )
2284            .route(
2285                "/v1/user/operations/{operation_id}/held-briefs/{key}/refuse",
2286                post(held::refuse),
2287            )
2288            .route(
2289                "/v1/user/operations/{operation_id}/missions/{mission_id}/reviews",
2290                get(reviews::list),
2291            )
2292            .route(
2293                "/v1/user/operations/{operation_id}/missions/{mission_id}/reviews/{gate}/overrule",
2294                post(reviews::overrule),
2295            )
2296            .route(
2297                "/v1/user/operations/{operation_id}/missions/{mission_id}/reviews/document",
2298                get(reviews::document),
2299            )
2300            .route(
2301                "/v1/user/operations/{operation_id}/missions/{mission_id}/brief",
2302                get(documents::brief),
2303            )
2304            .route(
2305                "/v1/user/operations/{operation_id}/missions/{mission_id}/runs/{run_id}/document",
2306                get(documents::run_report),
2307            )
2308            .route(
2309                "/v1/user/operations/{operation_id}/held-briefs/{key}/document",
2310                get(held::document),
2311            )
2312            .route(
2313                "/v1/user/operations/{operation_id}/green-ink/{request_id}/document",
2314                get(green_ink::document),
2315            )
2316            .route(
2317                "/v1/user/operations/{operation_id}/agent-roles",
2318                get(list_user_agent_roles),
2319            )
2320            .route(
2321                "/v1/user/operations/{operation_id}/agent-role-form",
2322                get(user_agent_role_form),
2323            )
2324            .route(
2325                "/v1/user/operations/{operation_id}/agent-roles/{role_id}",
2326                axum::routing::put(put_user_agent_role).delete(delete_user_agent_role),
2327            )
2328            .route(
2329                "/v1/user/operations/{operation_id}/agents",
2330                get(agents::list),
2331            )
2332            .route(
2333                "/v1/user/operations/{operation_id}/agents/scorecard",
2334                get(agents::scorecard),
2335            )
2336            .route(
2337                "/v1/user/operations/{operation_id}/trial-suites",
2338                get(trials::list).post(trials::put),
2339            )
2340            .route(
2341                "/v1/user/operations/{operation_id}/trials",
2342                post(trials::queue),
2343            )
2344            .route(
2345                "/v1/user/operations/{operation_id}/agents/{agent}/hold",
2346                axum::routing::delete(agents::lift_hold),
2347            )
2348            .route(
2349                "/v1/user/operations/{operation_id}/agents/{agent}/clearance",
2350                axum::routing::put(agents::lower).delete(agents::restore),
2351            )
2352            .route(
2353                "/v1/user/operations/{operation_id}/quarantine",
2354                get(list_user_quarantines),
2355            )
2356            .route(
2357                "/v1/user/operations/{operation_id}/quarantine/{agent_id}",
2358                post(quarantine_user_agent),
2359            )
2360            .route(
2361                "/v1/user/operations/{operation_id}/quarantine/{agent_id}/release",
2362                post(quarantines::release_operation),
2363            )
2364            .route("/v1/user/quarantine", get(quarantines::list_all))
2365            .route(
2366                "/v1/user/quarantine/{agent_id}/release",
2367                post(quarantines::release_all),
2368            )
2369            .route(
2370                "/v1/user/operations/{operation_id}/missions/{mission_id}",
2371                axum::routing::delete(purge::delete_mission),
2372            )
2373            .route(
2374                "/v1/user/operations/{operation_id}/missions/delete",
2375                post(purge::delete_missions),
2376            )
2377            .route(
2378                "/v1/user/operations/{operation_id}/missions/purge",
2379                post(purge::purge_missions),
2380            )
2381            .route("/v1/user/runs/{run_id}", axum::routing::delete(purge::delete_run))
2382            .route(
2383                "/v1/operations/{operation_id}/missions/{mission_id}",
2384                get(mission_detail),
2385            )
2386            .route(
2387                "/v1/user/operations/{operation_id}/missions/{mission_id}/actions",
2388                post(controls::request_control),
2389            )
2390            .route(
2391                "/v1/user/operations/{operation_id}/missions/{mission_id}/settle",
2392                post(orders::settle),
2393            )
2394            .route(
2395                "/v1/user/operations/{operation_id}/sleepers",
2396                get(sleepers::list_sleepers),
2397            )
2398            .route(
2399                "/v1/user/operations/{operation_id}/sleepers/{name}/authorize",
2400                post(sleepers::authorize_sleeper),
2401            )
2402            .route(
2403                "/v1/user/operations/{operation_id}/sleepers/{name}/revoke",
2404                post(sleepers::revoke_sleeper),
2405            )
2406            .route(
2407                "/v1/user/operations/{operation_id}/sleepers/{name}/fire",
2408                post(sleepers::fire_sleeper),
2409            )
2410            .route(
2411                "/v1/user/operations/{operation_id}/sleepers/{name}/disable",
2412                post(orders::disable_sleeper),
2413            )
2414            .route(
2415                "/v1/user/operations/{operation_id}/sleepers/{name}/enable",
2416                post(orders::enable_sleeper),
2417            )
2418            .route(
2419                "/v1/user/operations/{operation_id}/missions/{mission_id}/withdraw",
2420                post(held::withdraw),
2421            )
2422            .route(
2423                "/v1/user/operations/{operation_id}/missions/{mission_id}/verdict",
2424                post(verdicts::give),
2425            )
2426            .route(
2427                "/v1/user/operations/{operation_id}/missions/{mission_id}/verify",
2428                post(verdicts::verify),
2429            )
2430            .route(
2431                "/v1/user/operations/{operation_id}/missions/{mission_id}/probe",
2432                post(verdicts::probe),
2433            )
2434            .route(
2435                "/v1/user/operations/{operation_id}/missions/{mission_id}/rename",
2436                post(rename_user_mission),
2437            )
2438            .route(
2439                "/v1/user/operations/{operation_id}/missions/{mission_id}/actions/{control_id}",
2440                get(controls::control_status),
2441            )
2442            .route(
2443                "/v1/user/operations/{operation_id}/timeline",
2444                get(timeline::operation_timeline),
2445            )
2446            .route("/v1/user/assistant/pools", get(pools::assistant_pools))
2447            .route(
2448                "/v1/user/assistant/pools/{pool}/{account}/clear-limit",
2449                post(pools::clear_assistant_limit),
2450            )
2451            .route(
2452                "/v1/user/operations/{operation_id}/pools",
2453                get(pools::operation_pools),
2454            )
2455            .route(
2456                "/v1/user/operations/{operation_id}/pools/{pool}/{account}/clear-limit",
2457                post(pools::clear_limit),
2458            )
2459            .route(
2460                "/v1/user/operations/{operation_id}/pools/{pool}/{account}/usage",
2461                post(pools::read_usage),
2462            )
2463            .route(
2464                "/v1/user/operations/{operation_id}/pools/{pool}/{account}/login",
2465                axum::routing::delete(pools::forget_login),
2466            )
2467            .route(
2468                "/v1/user/operations/{operation_id}/pools/{pool}/{account}/login/stations",
2469                post(pools::add_login_station),
2470            )
2471            .route(
2472                "/v1/user/operations/{operation_id}/pools/{pool}/{account}/login/stations/{station}",
2473                axum::routing::delete(pools::remove_login_station),
2474            )
2475            .route("/v1/user/access", get(access_admin::read_global_policy))
2476            .route("/v1/user/access/forms/{kind}", get(access_admin::global_form))
2477            .route(
2478                "/v1/user/access/roles/{role}",
2479                axum::routing::put(access_admin::put_role).delete(access_admin::delete_role),
2480            )
2481            .route(
2482                "/v1/user/access/rules",
2483                axum::routing::put(access_admin::put_rules),
2484            )
2485            .route(
2486                "/v1/user/access/delegable",
2487                axum::routing::put(access_admin::put_delegable),
2488            )
2489            .route(
2490                "/v1/user/access/chief",
2491                axum::routing::put(access_admin::put_chief),
2492            )
2493            .route("/v1/user/access/check", get(access_admin::check))
2494            .route(
2495                "/v1/user/access/sign-in",
2496                get(sign_in::read_policy)
2497                    .put(sign_in::put_policy)
2498                    .delete(sign_in::remove_policy),
2499            )
2500            .route(
2501                "/v1/user/operations/{operation_id}/access",
2502                get(access_admin::read_operation_policy),
2503            )
2504            .route(
2505                "/v1/user/operations/{operation_id}/access/forms/{kind}",
2506                get(access_admin::operation_form),
2507            )
2508            .route(
2509                "/v1/user/operations/{operation_id}/access/roles/{role}",
2510                axum::routing::put(access_admin::put_operation_role)
2511                    .delete(access_admin::delete_operation_role),
2512            )
2513            .route(
2514                "/v1/user/operations/{operation_id}/access/rules",
2515                axum::routing::put(access_admin::put_operation_rules),
2516            )
2517            .route("/v1/user/compartments", get(compartments::list))
2518            .route("/v1/user/compartment-form", get(compartments::form))
2519            .route(
2520                "/v1/user/compartments/{id}",
2521                get(compartments::show)
2522                    .put(compartments::put)
2523                    .delete(compartments::remove),
2524            )
2525            .route(
2526                "/v1/user/compartments/{id}/covers/{resource}",
2527                axum::routing::put(compartments::put_cover).delete(compartments::remove_cover),
2528            )
2529            .route(
2530                "/v1/user/compartments/{id}/read-in/{subject}",
2531                axum::routing::put(compartments::put_read_in)
2532                    .delete(compartments::remove_read_in),
2533            )
2534            .route("/v1/user/keys", get(keys::list).post(keys::create))
2535            .route("/v1/user/keys/{id}", axum::routing::delete(keys::revoke))
2536            .route("/v1/user/accounts", get(accounts::list))
2537            .route("/v1/user/account-forms/{kind}", get(accounts::form))
2538            .route("/v1/user/models", get(models::list))
2539            .route(
2540                "/v1/user/accounts/{name}",
2541                axum::routing::put(accounts::put_account),
2542            )
2543            .route(
2544                "/v1/user/accounts/{name}/secret",
2545                post(accounts::reset_secret),
2546            )
2547            .route(
2548                "/v1/user/accounts/{name}/pins",
2549                get(account_pins::pins_of).post(account_pins::change_pins),
2550            )
2551            .route("/v1/user/providers", get(providers::all))
2552            .route(
2553                "/v1/user/stations/{station_id}/providers",
2554                get(providers::of_host),
2555            )
2556            .route(
2557                "/v1/user/stations/{station_id}/libraries",
2558                get(libraries::of_host),
2559            )
2560            .route(
2561                "/v1/user/stations/{station_id}/libraries/approve",
2562                post(libraries::approve),
2563            )
2564            .route("/v1/user/resources", get(roster::resources))
2565            .route("/v1/user/resources/apply", post(roster::apply))
2566            .route("/v1/user/roster/{kind}", get(roster::records))
2567            .route(
2568                "/v1/user/roster/operation/{id}/effective",
2569                get(roster::effective),
2570            )
2571            .route(
2572                "/v1/user/roster/{kind}/schema",
2573                get(roster::form)
2574                    .put(roster::put_record_keyed_schema)
2575                    .delete(roster::remove_record_keyed_schema),
2576            )
2577            .route(
2578                "/v1/user/roster/{kind}/{key}",
2579                axum::routing::put(roster::put_record).delete(roster::remove_record),
2580            )
2581            .route(
2582                "/v1/user/operations/{operation_id}/green-ink",
2583                get(green_ink::pending),
2584            )
2585            .route(
2586                "/v1/user/operations/{operation_id}/green-ink/expired",
2587                get(green_ink::expired),
2588            )
2589            .route(
2590                "/v1/user/operations/{operation_id}/green-ink/rejected",
2591                get(green_ink::rejected),
2592            )
2593            .route(
2594                "/v1/user/operations/{operation_id}/green-ink/sources",
2595                get(green_ink::sources),
2596            )
2597            .route(
2598                "/v1/user/operations/{operation_id}/green-ink/questions",
2599                get(green_ink::questions),
2600            )
2601            .route(
2602                "/v1/user/operations/{operation_id}/green-ink/{request_id}/rearm",
2603                post(green_ink::rearm),
2604            )
2605            .route(
2606                "/v1/user/operations/{operation_id}/green-ink/{request_id}/approve",
2607                post(green_ink::approve),
2608            )
2609            .route(
2610                "/v1/user/operations/{operation_id}/green-ink/{request_id}/answer",
2611                post(green_ink::answer),
2612            )
2613            .route(
2614                "/v1/user/operations/{operation_id}/green-ink/{request_id}/reject",
2615                post(green_ink::reject),
2616            )
2617            .route(
2618                "/v1/user/operations/{operation_id}/green-ink/{request_id}/rework",
2619                post(green_ink::rework),
2620            )
2621            .route(
2622                "/v1/user/operations/{operation_id}/green-ink/{request_id}/say",
2623                post(green_ink::say),
2624            )
2625            .route(
2626                "/v1/user/operations/{operation_id}/green-ink/{request_id}/revoke",
2627                post(green_ink::revoke),
2628            )
2629            .route(
2630                "/v1/user/operations/{operation_id}/class-authorizations",
2631                get(green_ink::list_classes).post(green_ink::create_class),
2632            )
2633            .route(
2634                "/v1/user/operations/{operation_id}/class-authorizations/{id}",
2635                axum::routing::delete(green_ink::revoke_class),
2636            )
2637            .route("/v1/user/attach-grants", post(issue_user_attach_token))
2638            .route("/v1/user/moneypenny", get(moneypenny::socket))
2639            .route("/v1/auth/link-keys", post(browser_link::pair))
2640            .route("/v1/socket/browser/link", get(browser_link::socket))
2641            .route("/v1/user/moneypenny/commands", get(moneypenny::commands::list))
2642            .route(
2643                "/v1/user/assistant/agent-links",
2644                post(moneypenny::links::create).get(moneypenny::links::list),
2645            )
2646            .route(
2647                "/v1/user/assistant/agent-links/{id}",
2648                axum::routing::delete(moneypenny::links::revoke),
2649            )
2650            .route(
2651                "/v1/user/assistant/agent-links/{id}/confirm",
2652                post(moneypenny::links::confirm),
2653            )
2654            .route("/v1/assistant/agent-link", get(moneypenny::links::socket))
2655            .route(
2656                "/v1/user/assistant/mcp-tokens",
2657                post(moneypenny::mcp_tokens::mint),
2658            )
2659            .route(
2660                "/v1/user/assistant/mcp-tokens/{id}",
2661                axum::routing::delete(moneypenny::mcp_tokens::revoke),
2662            )
2663            .route(
2664                "/v1/user/moneypenny/images/{sha256}",
2665                get(moneypenny::user_image),
2666            )
2667            .route(
2668                "/v1/station/assistant/images/{sha256}",
2669                get(moneypenny::station_image),
2670            )
2671            .route("/v1/moneypenny/mcp", post(moneypenny::mcp::endpoint))
2672            .route("/v1/user/charges", get(charges::list))
2673            .route("/v1/user/charges/{scope}", get(charges::show))
2674            .route("/v1/user/charges/{scope}/document", get(charges::document))
2675            .route(
2676                "/v1/user/charges/{scope}/acknowledge",
2677                post(charges::acknowledge),
2678            )
2679            .route("/v1/user/charges/{scope}/wake", post(charges::wake))
2680            .route("/v1/user/charges/{scope}/restart", post(charges::restart))
2681            .route("/v1/socket/attach", get(run_attach::socket))
2682            .route("/v1/station/hub/next", get(run_attach::next))
2683            .route("/v1/station/hub/frames", post(run_attach::frames))
2684            .route("/v1/station/assistant/next", get(moneypenny::next))
2685            .route("/v1/station/assistant/reports", post(moneypenny::reports))
2686            .route(
2687                "/v1/station/assistant/cables",
2688                get(moneypenny::cable_standing),
2689            )
2690            .route("/v1/auth/methods", get(auth_methods))
2691            .route("/v1/auth/login", post(login))
2692            .route("/v1/auth/enrol", post(second_factor::begin_first))
2693            .route("/v1/auth/enrol/confirm", post(second_factor::confirm_first))
2694            .route("/v1/user/factors", get(second_factor::state))
2695            .route(
2696                "/v1/user/factors/totp",
2697                post(second_factor::begin_enrolment),
2698            )
2699            .route(
2700                "/v1/user/factors/totp/confirm",
2701                post(second_factor::confirm_enrolment),
2702            )
2703            .route(
2704                "/v1/user/access/factors/{person}",
2705                axum::routing::delete(second_factor::reset),
2706            )
2707            .route("/v1/auth/logout", post(logout))
2708            .route("/v1/auth/renew", post(renew))
2709            .route("/v1/auth/resume", post(resume))
2710            .route("/v1/auth/session", get(access_session))
2711            .route("/v1/user/attention", get(attention::read))
2712            .route("/v1/user/reports/unassessed", get(reports::unassessed))
2713            .route("/v1/user/profile", get(user_profile))
2714            .route(
2715                "/v1/user/oo-preferences",
2716                get(oo_preferences::read).put(oo_preferences::write),
2717            )
2718            .route("/v1/user/audit", get(user_audit))
2719            .route(
2720                "/v1/user/principals",
2721                get(principals::search).post(principals::lookup),
2722            )
2723            .route(
2724                "/v1/user/operations/{operation_id}/runs/{run_id}/context",
2725                get(transcripts::mission_context),
2726            )
2727            .route(
2728                "/v1/user/operations/{operation_id}/missions/{mission_id}/ledger",
2729                get(transcripts::mission_ledger),
2730            )
2731            .route(
2732                "/v1/user/assistant/conversations",
2733                get(transcripts::conversations),
2734            )
2735            .route(
2736                "/v1/user/assistant/conversations/{id}/log",
2737                get(transcripts::conversation_log),
2738            )
2739            .route(
2740                "/v1/user/assistant/conversations/{id}/context",
2741                get(transcripts::conversation_context),
2742            )
2743            .route(
2744                "/v1/user/assistant/conversations/{id}/transcript",
2745                get(transcripts::conversation_transcript),
2746            )
2747            .route("/v1/user/mcp/{name}/tools", post(mcp_tools::tools))
2748            .route("/v1/user/overlays", get(mcp_tools::overlays))
2749            .route(
2750                "/v1/user/stations/pairing",
2751                get(stations_pairing::status),
2752            )
2753            .route(
2754                "/v1/user/stations/pairing/invite",
2755                post(stations_pairing::invite),
2756            )
2757            .route(
2758                "/v1/user/stations/pairing/pin",
2759                post(stations_pairing::show_pin).delete(stations_pairing::clear_pin),
2760            )
2761            .route(
2762                "/v1/user/stations/pairing/submit",
2763                post(stations_pairing::submit),
2764            )
2765            .route(
2766                "/v1/user/stations/pairing/devices/inspect",
2767                post(stations_pairing::device),
2768            )
2769            .route(
2770                "/v1/user/stations/pairing/devices/approve",
2771                post(stations_pairing::approve),
2772            )
2773            .route(
2774                "/v1/user/stations/pairing/devices/deny",
2775                post(stations_pairing::deny),
2776            )
2777            .route("/v1/station/mcp-tools/next", get(mcp_tools::next))
2778            .route(
2779                "/v1/station/mcp-tools/{id}/result",
2780                post(mcp_tools::result),
2781            )
2782            .route("/v1/station/credential", get(station_auth::credential))
2783            .route("/v1/station/pairing/next", get(stations_pairing::next))
2784            .route(
2785                "/v1/station/pairing/{id}/result",
2786                post(stations_pairing::result),
2787            )
2788            .route("/v1/station/source-reads/next", get(source_reads::next))
2789            .route(
2790                "/v1/station/source-reads/{id}/result",
2791                post(source_reads::result),
2792            )
2793            .route("/v1/station/runs", post(register_run))
2794            .route(
2795                "/v1/station/runs/{run_id}/lifecycle/{sequence}",
2796                post(publish_lifecycle),
2797            )
2798            .route(
2799                "/v1/station/runs/{run_id}/terminal/{sequence}",
2800                post(publish_terminal_output),
2801            )
2802            .route(
2803                "/v1/station/runs/{run_id}/events/{sequence}",
2804                post(ingest_event),
2805            )
2806            .route("/v1/station/attach-grants", post(issue_attach_token))
2807            .route("/v1/station/access-tokens", post(issue_access_token))
2808            .route(
2809                "/v1/station/access-tokens/{token_id}",
2810                axum::routing::delete(revoke_access_token),
2811            )
2812            .route("/v1/station/inputs/next", get(next_agent_input))
2813            .route(
2814                "/v1/station/controls/next",
2815                get(controls::next_station_control),
2816            )
2817            .route(
2818                "/v1/station/controls/{control_id}/result",
2819                post(controls::report_station_control),
2820            )
2821            .route("/v1/attach", post(exchange_attach_token))
2822            .route("/v1/socket/{run_id}", get(websocket_attach))
2823            .merge(liaison::routes())
2824            .merge(secret_routes())
2825            .layer(axum::extract::DefaultBodyLimit::max(max_frame_bytes))
2826            .merge(base)
2827            .with_state(self.clone())
2828            .layer(axum::middleware::from_fn_with_state(
2829                self.clone(),
2830                station_auth::station_guard,
2831            ));
2832        match pages {
2833            Some(pages) => router.merge(pages.with_state(self)),
2834            None => router,
2835        }
2836    }
2837
2838    /// Serves the gateway on loopback so browsers reach it only through the
2839    /// configured HTTPS reverse proxy. Once `shutdown` resolves and the open requests end, it
2840    /// waits up to `[assistant.gateway] log_flush_timeout` for Moneypenny's conversation log.
2841    pub async fn serve_loopback<F>(self, port: u16, shutdown: F) -> Result<(), std::io::Error>
2842    where
2843        F: Future<Output = ()> + Send + 'static,
2844    {
2845        let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;
2846        let assistant = self.assistant.clone();
2847        let served = axum::serve(
2848            listener,
2849            self.router()
2850                .into_make_service_with_connect_info::<SocketAddr>(),
2851        )
2852        .with_graceful_shutdown(shutdown)
2853        .await;
2854        if let Some(assistant) = assistant {
2855            assistant.flush_log().await;
2856        }
2857        served
2858    }
2859}
2860
2861async fn board(
2862    State(gateway): State<Gateway>,
2863    headers: HeaderMap,
2864) -> Result<Json<Vec<BoardRun>>, ApiError> {
2865    Ok(Json(authorized_board_runs(&gateway, &headers).await?))
2866}
2867
2868async fn stations(
2869    State(gateway): State<Gateway>,
2870    headers: HeaderMap,
2871) -> Result<Json<StationBoard>, ApiError> {
2872    let person = resolve_user(&gateway, bearer(&headers)?).await?;
2873    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
2874    let authorizer = gateway.authorizer()?;
2875    let (station_records, headquarters, dark) = tokio::task::spawn_blocking(move || {
2876        let stations = registry
2877            .stations(Duration::MAX)
2878            .map_err(|_| ApiError::internal())?;
2879        let headquarters = registry.headquarters().map_err(|_| ApiError::internal())?;
2880        let dark = registry.limits().stations.gone_dark_after.0;
2881        Ok::<_, ApiError>((stations, headquarters, dark))
2882    })
2883    .await
2884    .map_err(|_| ApiError::internal())??;
2885    let now = SystemTime::now()
2886        .duration_since(UNIX_EPOCH)
2887        .map_err(|_| ApiError::internal())?
2888        .as_secs_f64();
2889    let tree = OperationTree::from_check_ins(&station_records);
2890    let degraded = gateway.degraded.clone();
2891    let gateway_settings_status = gateway
2892        .config
2893        .unex()
2894        .weakenings()
2895        .into_iter()
2896        .map(ai6::station::settings_status::SettingsNotice::configured)
2897        .chain(
2898            gateway
2899                .station_auth_weakenings()
2900                .into_iter()
2901                .map(ai6::station::settings_status::SettingsNotice::risk),
2902        )
2903        .map(|notice| notice.in_context("Universal Exports"))
2904        .collect();
2905    let visible = tokio::task::spawn_blocking(move || {
2906        let mut stations = Vec::new();
2907        // The gateway is read as a Station is: by a rule that reads Stations at `*`, which holds
2908        // when no Station has checked in.
2909        let mut reads_any_station = authorizer
2910            .authorize(AuthorizationRequest {
2911                person: person.clone(),
2912                action: "station.read".to_owned(),
2913                resource: "station:gateway".to_owned(),
2914                ancestors: Vec::new(),
2915            })
2916            .map_err(|_| ApiError::internal())?
2917            .allowed;
2918        let mut readable = BTreeSet::new();
2919        for station in station_records {
2920            let reads_station = authorizer
2921                .authorize(AuthorizationRequest {
2922                    person: person.clone(),
2923                    action: "station.read".to_owned(),
2924                    resource: format!("station:{}", station.station()),
2925                    ancestors: Vec::new(),
2926                })
2927                .map_err(|_| ApiError::internal())?
2928                .allowed;
2929            let mut operations = Vec::new();
2930            for operation_id in &station.check_in().common.operations {
2931                let Ok(operation_id) = OperationId::new(operation_id.clone()) else {
2932                    continue;
2933                };
2934                let allowed = authorizer
2935                    .authorize(operation_request(
2936                        person.clone(),
2937                        "mission.read",
2938                        operation_id.as_str(),
2939                        &tree,
2940                    ))
2941                    .map_err(|_| ApiError::internal())?
2942                    .allowed;
2943                if allowed {
2944                    operations.push(operation_id.to_string());
2945                }
2946            }
2947            // A control Station holds no checkout, so an Operation alone would never show it.
2948            if operations.is_empty() && !reads_station {
2949                continue;
2950            }
2951            operations.sort();
2952            operations.dedup();
2953            reads_any_station |= reads_station;
2954            let mut board = board_station(station, &operations, now, headquarters.as_ref(), dark);
2955            // The report covers every Operation on the Station: it is the Station's to read.
2956            if !reads_station {
2957                board.head_of_station = None;
2958                board.degraded.clear();
2959                board.peers_weakened.clear();
2960                board.settings_status.clear();
2961                board.bootstrap_weakened.clear();
2962                board.tls_weakened.clear();
2963                board.agents_weakened.clear();
2964                board.plugins_weakened.clear();
2965                board.assistant_weakened.clear();
2966                board.cables_weakened.clear();
2967                board.secrets_weakened.clear();
2968            }
2969            stations.push(board);
2970        }
2971        stations.sort_by(|left: &BoardStation, right| left.station_id.cmp(&right.station_id));
2972        // The tree's Operations the person may read, each under its nearest readable ancestor.
2973        let named: BTreeSet<String> = stations
2974            .iter()
2975            .flat_map(|station| station.operations.iter().cloned())
2976            .chain(tree.operations().map(str::to_owned))
2977            .collect();
2978        for operation in named {
2979            if authorizer
2980                .authorize(operation_request(
2981                    person.clone(),
2982                    "mission.read",
2983                    &operation,
2984                    &tree,
2985                ))
2986                .map_err(|_| ApiError::internal())?
2987                .allowed
2988            {
2989                readable.insert(operation);
2990            }
2991        }
2992        let operations = readable
2993            .iter()
2994            .map(|operation| BoardOperation {
2995                operation_id: operation.clone(),
2996                name: tree.name(operation),
2997                parent: tree.visible_parent(operation, |id| readable.contains(id)),
2998            })
2999            .collect();
3000        let headquarters_station = headquarters
3001            .filter(|lease| {
3002                lease.expires() > now
3003                    && stations
3004                        .iter()
3005                        .any(|station| station.station_id == lease.station())
3006            })
3007            .map(|lease| lease.station().to_owned());
3008        let gateway_degraded = if reads_any_station {
3009            degraded.as_ref().clone()
3010        } else {
3011            Vec::new()
3012        };
3013        Ok::<_, ApiError>(StationBoard {
3014            stations,
3015            headquarters_station,
3016            gateway_degraded,
3017            gateway_settings_status: if reads_any_station {
3018                gateway_settings_status
3019            } else {
3020                Vec::new()
3021            },
3022            operations,
3023        })
3024    })
3025    .await
3026    .map_err(|_| ApiError::internal())??;
3027    Ok(Json(visible))
3028}
3029
3030fn board_station(
3031    record: ai6::StationRecord,
3032    operations: &[String],
3033    now: f64,
3034    headquarters: Option<&ai6::HeadquartersLease>,
3035    gone_dark_after: Duration,
3036) -> BoardStation {
3037    let station_id = record.station().to_owned();
3038    let seen = record.seen();
3039    let check_in = record.into_check_in();
3040    let common = check_in.common;
3041    BoardStation {
3042        healthy: now - seen <= gone_dark_after.as_secs_f64(),
3043        headquarters: headquarters
3044            .is_some_and(|lease| lease.station() == station_id && lease.expires() > now),
3045        station_id,
3046        seen,
3047        roles: common.roles,
3048        handlers: common.handlers.unwrap_or_default(),
3049        running: common.running,
3050        capacity: common.capacity,
3051        operations: operations.to_vec(),
3052        theaters: station_theaters(check_in.theaters),
3053        resources: check_in.resources,
3054        config: check_in.config,
3055        issues_weakened: common
3056            .issues_weakened
3057            .into_iter()
3058            .filter(|line| {
3059                operations
3060                    .iter()
3061                    .any(|operation| line.starts_with(&format!("Operation {operation:?} ")))
3062            })
3063            .collect(),
3064        peers_weakened: common.peers_weakened,
3065        settings_status: check_in
3066            .settings_status
3067            .into_iter()
3068            .filter(|notice| {
3069                notice
3070                    .operation
3071                    .as_ref()
3072                    .is_none_or(|operation| operations.contains(operation))
3073            })
3074            .collect(),
3075        bootstrap_weakened: common.bootstrap_weakened,
3076        tls_weakened: common.tls_weakened,
3077        agents_weakened: common.agents_weakened,
3078        plugins_weakened: common.plugins_weakened,
3079        assistant_weakened: common.assistant_weakened,
3080        cables_weakened: common.cables_weakened,
3081        secrets_weakened: common.secrets_weakened,
3082        head_of_station: check_in.head_of_station,
3083        degraded: check_in.degraded,
3084        queue: check_in
3085            .queue
3086            .into_iter()
3087            .filter(|entry| operations.contains(&entry.operation_id))
3088            .collect(),
3089    }
3090}
3091
3092/// The Theaters a Station published; one without the key reaches only its own host.
3093fn station_theaters(published: Option<Vec<ai6::TheaterSummary>>) -> Vec<BoardTheater> {
3094    published
3095        .unwrap_or_else(|| vec![ai6::TheaterSummary::local()])
3096        .into_iter()
3097        .map(|theater| BoardTheater {
3098            id: theater.id,
3099            access: theater.access.as_str().to_owned(),
3100            host: theater.host,
3101            provider: theater.provider,
3102            labels: theater.labels,
3103            capabilities: theater.capabilities,
3104            agents: theater.agents.as_str().to_owned(),
3105            egress: theater.egress.as_str().to_owned(),
3106            harnesses: theater.harnesses,
3107            workdir: theater.workdir,
3108            unavailable: theater.unavailable,
3109            settings_status: theater
3110                .weakened
3111                .iter()
3112                .map(|line| ai6::station::settings_status::SettingsNotice::theater(line))
3113                .collect(),
3114            weakened: theater.weakened,
3115            requires: theater.requires,
3116            report: theater.report,
3117            made_for: theater.made_for,
3118            resources: theater.resources,
3119            runs: theater.runs,
3120        })
3121        .collect()
3122}
3123
3124/// `GET /v1/missions` filters: one Operation, or with `subtree` that Operation and every
3125/// Operation under it.
3126#[derive(Debug, Default, Deserialize)]
3127struct MissionsQuery {
3128    operation: Option<String>,
3129    #[serde(default)]
3130    subtree: bool,
3131    /// What one compartment covers, of what the person may read.
3132    compartment: Option<String>,
3133    /// One Mission: its UID or any handle it had.
3134    mission: Option<String>,
3135}
3136
3137async fn missions(
3138    State(gateway): State<Gateway>,
3139    headers: HeaderMap,
3140    Query(query): Query<MissionsQuery>,
3141) -> Result<Json<Vec<BoardMission>>, ApiError> {
3142    let mut runs = authorized_board_runs(&gateway, &headers).await?;
3143    // Missions no Run has been recorded for are listed beside the others, unless a
3144    // compartment narrows the list: it covers Missions by what they are, which these are not yet.
3145    let mut unstarted = if query.compartment.is_some() {
3146        Vec::new()
3147    } else {
3148        let person = resolve_user(&gateway, bearer(&headers)?).await?;
3149        unstarted::unstarted_missions(&gateway, person).await?
3150    };
3151    if let Some(mission) = &query.mission {
3152        let uid = mission_key(&gateway, mission).await?;
3153        runs.retain(|run| run.mission_id == uid);
3154        unstarted.retain(|pending| pending.mission_id == uid);
3155    }
3156    if let Some(operation) = &query.operation {
3157        let tree = if query.subtree {
3158            operation_tree(&gateway).await?
3159        } else {
3160            OperationTree::default()
3161        };
3162        runs.retain(|run| tree.in_subtree(&run.operation_id, operation));
3163        unstarted.retain(|pending| tree.in_subtree(&pending.operation_id, operation));
3164    }
3165    if let Some(compartment) = query.compartment {
3166        let person = resolve_user(&gateway, bearer(&headers)?).await?;
3167        let access = gateway.probing_authorizer()?;
3168        runs = tokio::task::spawn_blocking(move || {
3169            let compiled = access.compiled();
3170            let readable = access
3171                .authorize(AuthorizationRequest {
3172                    person: person.clone(),
3173                    action: "compartment.read".to_owned(),
3174                    resource: format!("compartment:{compartment}"),
3175                    ancestors: Vec::new(),
3176                })
3177                .is_ok_and(|decision| decision.allowed);
3178            let holds =
3179                compiled.is_some_and(|compiled| compiled.person_holds(&compartment, &person));
3180            match compiled.filter(|_| readable || holds) {
3181                Some(compiled) => runs
3182                    .into_iter()
3183                    .filter(|run| {
3184                        compartments::in_compartment(
3185                            compiled,
3186                            &compartment,
3187                            &run.operation_id,
3188                            &run.mission_id,
3189                        )
3190                    })
3191                    .collect(),
3192                None => Vec::new(),
3193            }
3194        })
3195        .await
3196        .map_err(|_| ApiError::internal())?;
3197    }
3198    let mut missions = group_missions(runs);
3199    let started: BTreeSet<_> = missions
3200        .iter()
3201        .map(|mission| (mission.operation_id.clone(), mission.mission_id.clone()))
3202        .collect();
3203    missions.extend(unstarted.into_iter().filter(|pending| {
3204        !started.contains(&(pending.operation_id.clone(), pending.mission_id.clone()))
3205    }));
3206    Ok(Json(gateway.enrich_missions(missions).await))
3207}
3208
3209async fn mission_detail(
3210    State(gateway): State<Gateway>,
3211    headers: HeaderMap,
3212    Path((operation_id, mission_id)): Path<(String, String)>,
3213) -> Result<Json<BoardMission>, ApiError> {
3214    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::not_found())?;
3215    let named = named_mission(&gateway, &mission_id).await?;
3216    let mission_id = MissionId::new(named.mission_id).map_err(|_| ApiError::not_found())?;
3217    let visible = authorized_board_runs(&gateway, &headers).await?;
3218    let runs = visible
3219        .into_iter()
3220        .filter(|run| {
3221            run.operation_id == operation_id.as_str() && run.mission_id == mission_id.as_str()
3222        })
3223        .collect::<Vec<_>>();
3224    let mut mission = match group_missions(runs).into_iter().next() {
3225        Some(mission) => mission,
3226        // A Mission nobody has started has no Run to find it by.
3227        None => {
3228            let person = resolve_user(&gateway, bearer(&headers)?).await?;
3229            let queued = unstarted::unstarted_missions(&gateway, person.clone())
3230                .await?
3231                .into_iter()
3232                .find(|pending| {
3233                    pending.operation_id == operation_id.as_str()
3234                        && pending.mission_id == mission_id.as_str()
3235                });
3236            match queued {
3237                Some(queued) => queued,
3238                // A historical Mission can be past the board's window or have no Run record.
3239                None => unstarted::filed_mission(
3240                    &gateway,
3241                    person,
3242                    operation_id.as_str(),
3243                    mission_id.as_str(),
3244                )
3245                .await?
3246                .ok_or_else(ApiError::not_found)?,
3247            }
3248        }
3249    };
3250    mission.handle = named.handle;
3251    mission.brief = gateway
3252        .inner
3253        .lock()
3254        .await
3255        .missions
3256        .get(&(operation_id, mission_id))
3257        .cloned();
3258    if let Some(registry) = gateway.registry.clone() {
3259        let (operation, mission_id) = (mission.operation_id.clone(), mission.mission_id.clone());
3260        let (usage, mut attempts) = tokio::task::spawn_blocking(move || {
3261            let records = registry
3262                .runs()?
3263                .into_iter()
3264                .filter(|record| {
3265                    record.mission_id == mission_id
3266                        && record
3267                            .operation
3268                            .as_deref()
3269                            .is_none_or(|scope| scope == operation)
3270                })
3271                .collect();
3272            let mut attempts = runs_by_mission(records);
3273            for attempt in attempts.get_mut(&mission_id).into_iter().flatten() {
3274                attempt.final_report = registry
3275                    .final_report(&attempt.run_id)?
3276                    .map(|report| report.text);
3277            }
3278            Ok::<_, std::io::Error>((
3279                registry.mission_usage(Some(&operation), &mission_id)?,
3280                attempts,
3281            ))
3282        })
3283        .await
3284        .map_err(|_| ApiError::internal())?
3285        .map_err(|_| ApiError::internal())?;
3286        mission.usage = usage;
3287        mission.history = attempts.remove(&mission.mission_id).unwrap_or_default();
3288        mission.conversation_tokens = conversation_tokens(&mission.history, mission.usage.as_ref());
3289        let (registry, uid) = (gateway.registry.clone(), mission.mission_id.clone());
3290        mission.revision = tokio::task::spawn_blocking(move || {
3291            registry.and_then(|registry| registry.mission_revision(&uid).ok().flatten())
3292        })
3293        .await
3294        .map_err(|_| ApiError::internal())?;
3295    }
3296    Ok(Json(mission))
3297}
3298
3299/// What the conversation of the latest run's provider session holds: the tokens each run of the
3300/// session added, summed back along the runs that resumed it. None before a Run has a provider ID.
3301fn conversation_tokens(history: &[MissionRun], usage: Option<&MissionUsage>) -> Option<u64> {
3302    let mut current = history.iter().max_by_key(|run| run.number)?;
3303    current.provider_id.as_ref()?;
3304    let mut total = 0_u64;
3305    let mut seen = std::collections::BTreeSet::new();
3306    while seen.insert(current.run_id.as_str()) {
3307        total = total.saturating_add(
3308            usage
3309                .and_then(|usage| usage.runs.get(&current.run_id))
3310                .map_or(0, ai6::UsageTotals::tokens),
3311        );
3312        let Some(previous) = current
3313            .predecessor
3314            .as_deref()
3315            .and_then(|id| history.iter().find(|run| run.run_id == id))
3316            .filter(|previous| previous.provider_id == current.provider_id)
3317        else {
3318            break;
3319        };
3320        current = previous;
3321    }
3322    Some(total)
3323}
3324
3325/// Whether a title and instructions are written, and within `[text]`.
3326fn mission_text_fits(title: &str, prompt: &str, limits: &ai6::TextLimits) -> bool {
3327    !title.trim().is_empty()
3328        && limits.mission_title_chars.allows(title.chars().count())
3329        && !prompt.trim().is_empty()
3330        && limits.mission_prompt_bytes.allows(prompt.len())
3331}
3332
3333/// How many audit records a request gets: what it asks for, within `[timeline]`.
3334fn audit_page(asked: Option<usize>, pages: &ai6::UnexTimelineLimits) -> Option<usize> {
3335    let limit = asked.unwrap_or(usize::try_from(pages.audit_page).unwrap_or(usize::MAX));
3336    (limit != 0 && pages.max_audit_page.allows(limit)).then_some(limit)
3337}
3338
3339async fn create_user_mission(
3340    State(gateway): State<Gateway>,
3341    headers: HeaderMap,
3342    Path(operation_id): Path<String>,
3343    Json(request): Json<CreateMission>,
3344) -> Result<(StatusCode, Json<MissionCreated>), ApiError> {
3345    let person = resolve_user(&gateway, bearer(&headers)?).await?;
3346    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
3347    if !mission_text_fits(&request.title, &request.prompt, &gateway.config.unex().text)
3348        || request
3349            .agent_id
3350            .as_ref()
3351            .is_some_and(|value| value.trim().is_empty() || value.len() > 256)
3352        || request
3353            .role
3354            .as_ref()
3355            .is_some_and(|value| value.trim().is_empty() || value.len() > 128)
3356        || request.tags.len() > 32
3357        || request
3358            .tags
3359            .iter()
3360            .any(|tag| tag.trim().is_empty() || tag.len() > 64)
3361        || !valid_station_list(&request.stations)
3362    {
3363        return Err(ApiError::bad_request());
3364    }
3365    let authorizer = gateway.authorizer()?;
3366    let actor_id = person.id.clone();
3367    let check = operation_request(
3368        person.clone(),
3369        "mission.create",
3370        operation_id.as_str(),
3371        &operation_tree(&gateway).await?,
3372    );
3373    let decision = tokio::task::spawn_blocking(move || authorizer.authorize(check))
3374        .await
3375        .map_err(|_| ApiError::internal())?
3376        .map_err(|_| ApiError::internal())?;
3377    if !decision.allowed {
3378        return Err(ApiError::forbidden());
3379    }
3380    // A person's naming may weaken a review, so it takes the action that decides over reviews.
3381    if let Some(review) = &request.review {
3382        if review
3383            .named()
3384            .chain(
3385                review
3386                    .plan
3387                    .iter()
3388                    .chain(review.output.iter())
3389                    .map(String::as_str),
3390            )
3391            .any(|name| name.trim().is_empty() || name.len() > 128)
3392        {
3393            return Err(ApiError::bad_request());
3394        }
3395        authorize_operation_action(&gateway, person.clone(), &operation_id, "mission.review")
3396            .await?;
3397    }
3398    if request.deliverables.len() > 32 || request.deliverables.iter().any(|text| text.len() > 512) {
3399        return Err(ApiError::bad_request());
3400    }
3401    if let Err(invalid) = ai6::directorates::m::deliverables::parse_all(&request.deliverables) {
3402        return Err(ApiError::invalid(invalid.to_string()));
3403    }
3404    let reference = |text: &str| {
3405        !text.trim().is_empty() && text.len() <= 256 && !text.chars().any(char::is_control)
3406    };
3407    if (request.issue.is_some() && request.create_issue.is_some())
3408        || (request.handle.is_some() && (request.issue.is_some() || request.create_issue.is_some()))
3409        || request
3410            .issue
3411            .as_ref()
3412            .is_some_and(|issue| !reference(&issue.tracker) || !reference(&issue.item))
3413    {
3414        return Err(ApiError::bad_request());
3415    }
3416
3417    let created = utc_timestamp()?;
3418    let received_at = unix_timestamp()? as i64;
3419    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
3420    if !request.stations.is_empty() {
3421        let (lookup, named, operation) = (
3422            registry.clone(),
3423            request.stations.clone(),
3424            operation_id.to_string(),
3425        );
3426        tokio::task::spawn_blocking(move || {
3427            let records = lookup
3428                .stations(Duration::MAX)
3429                .map_err(|_| ApiError::internal())?;
3430            let headquarters = lookup.headquarters().map_err(|_| ApiError::internal())?;
3431            let policy = published_policy(
3432                &records,
3433                headquarters.as_ref().map(|lease| lease.station()),
3434                &operation,
3435            )
3436            .map(|(_, policy)| policy);
3437            match station_pin_refusal(&named, &records, policy.as_ref(), &operation) {
3438                Some(refusal) => Err(ApiError::invalid(refusal)),
3439                None => Ok(()),
3440            }
3441        })
3442        .await
3443        .map_err(|_| ApiError::internal())??;
3444    }
3445    let mut data = ai6::BriefData {
3446        review: request.review.clone(),
3447        ..ai6::BriefData::default()
3448    };
3449    if !request.deliverables.is_empty() {
3450        data.deliverables = Some(request.deliverables.clone());
3451    }
3452    if let Some(issue) = &request.issue {
3453        data.follow_up = Some(ai6::FollowUp {
3454            item: issue.item.clone(),
3455            tracker: issue.tracker.clone(),
3456        });
3457    }
3458    let mut brief = Brief {
3459        title: request.title,
3460        body: request.prompt,
3461        id: ai6::new_uid(),
3462        mission_id: None,
3463        handle: None,
3464        name: None,
3465        source: "universal-exports".to_owned(),
3466        operation: Some(operation_id.to_string()),
3467        agent: request.agent_id,
3468        role: request.role,
3469        tags: request.tags,
3470        stations: request.stations,
3471        priority: 0,
3472        url: None,
3473        data,
3474        created,
3475        version: 1,
3476        provenance: None,
3477    };
3478    if let Some(create) = request.create_issue {
3479        return create_with_issue(&gateway, registry, (&person, &operation_id), create, brief)
3480            .await;
3481    }
3482    let book = registry.clone();
3483    let entry = match &request.issue {
3484        Some(issue) => MissionEntry::follow_up(operation_id.as_str(), &issue.tracker, &issue.item),
3485        None => match &request.handle {
3486            Some(handle) => MissionEntry::person_named(Some(operation_id.as_str()), handle),
3487            None => MissionEntry::person(Some(operation_id.as_str())),
3488        },
3489    };
3490    let entered = tokio::task::spawn_blocking(move || book.allot_mission_id(&entry))
3491        .await
3492        .map_err(|_| ApiError::internal())?
3493        .map_err(|error| match (&request.issue, error.kind()) {
3494            _ if request.handle.is_some() && error.kind() == std::io::ErrorKind::InvalidInput => {
3495                ApiError::invalid(error.to_string())
3496            }
3497            _ if request.handle.is_some() && error.kind() == std::io::ErrorKind::AlreadyExists => {
3498                ApiError::refused(StatusCode::CONFLICT, error.to_string())
3499            }
3500            (Some(issue), std::io::ErrorKind::NotFound) => ApiError::invalid(format!(
3501                "item {:?} of {:?} has no Mission in Operation {operation_id}: only an item AI6 \
3502                 has taken in can be followed up",
3503                issue.item, issue.tracker
3504            )),
3505            _ => ApiError::internal(),
3506        })?;
3507    brief.id = entered.mission_id.clone();
3508    brief.mission_id = Some(entered.mission_id);
3509    brief.handle = Some(entered.handle.clone());
3510    brief.provenance = Some(
3511        Provenance::new(Origin::Operator, &brief, GATEWAY_RECEIVER, received_at)
3512            .with_principal(actor_id.clone()),
3513    );
3514    let mission_id = MissionId::new(brief.key()).map_err(|_| ApiError::internal())?;
3515    let audit = AuditRecord {
3516        id: Uuid::new_v4().to_string(),
3517        actor: actor_id,
3518        action: "mission.create.requested".to_owned(),
3519        operation: operation_id.to_string(),
3520        resource: None,
3521        target: mission_id.to_string(),
3522        at: unix_timestamp()?,
3523    };
3524    let audit_registry = registry.clone();
3525    tokio::task::spawn_blocking(move || audit_registry.record_audit(&audit))
3526        .await
3527        .map_err(|_| ApiError::internal())?
3528        .map_err(|_| ApiError::internal())?;
3529    let followed = request.issue.map(|issue| IssueLink {
3530        operation: operation_id.to_string(),
3531        mission_id: mission_id.to_string(),
3532        tracker: issue.tracker,
3533        item: issue.item,
3534        url: None,
3535        relation: LinkRelation::Related,
3536        state: LinkState::Active,
3537        linked_by: format!("person:{}", person.id),
3538        linked_at: received_at as f64,
3539        status_comment: None,
3540        phase: None,
3541        snapshot: None,
3542        branch: None,
3543    });
3544    tokio::task::spawn_blocking(move || {
3545        registry.submit_brief(&brief)?;
3546        if let Some(link) = followed {
3547            registry.link_issue(&link)?;
3548        }
3549        Ok::<_, std::io::Error>(())
3550    })
3551    .await
3552    .map_err(|_| ApiError::internal())?
3553    .map_err(|_| ApiError::internal())?;
3554    Ok((
3555        StatusCode::ACCEPTED,
3556        Json(MissionCreated {
3557            operation_id: operation_id.to_string(),
3558            mission_id: Some(mission_id.to_string()),
3559            handle: Some(entered.handle),
3560            proposal: None,
3561            state: "queued".to_owned(),
3562        }),
3563    ))
3564}
3565
3566/// The rest of a Mission create that asks for its issue: the issue goes to the Headquarters
3567/// Station as an approved creation carrying the brief, and the Mission enters, numbered by the
3568/// issue, once it exists. Needs `issue.create` as well.
3569async fn create_with_issue(
3570    gateway: &Gateway,
3571    registry: Arc<dyn RegistryBackend>,
3572    (person, operation_id): (&Person, &OperationId),
3573    create: NewMissionIssue,
3574    mut brief: Brief,
3575) -> Result<(StatusCode, Json<MissionCreated>), ApiError> {
3576    if create.tracker.trim().is_empty() || create.tracker.len() > 256 {
3577        return Err(ApiError::bad_request());
3578    }
3579    authorize_operation_action(gateway, person.clone(), operation_id, "issue.create").await?;
3580    let received_at = unix_timestamp()?;
3581    brief.provenance = Some(
3582        Provenance::new(
3583            Origin::Operator,
3584            &brief,
3585            GATEWAY_RECEIVER,
3586            received_at as i64,
3587        )
3588        .with_principal(person.id.clone()),
3589    );
3590    let title = create.title.unwrap_or_else(|| brief.title.clone());
3591    let body = create.body.unwrap_or_else(|| brief.body.clone());
3592    let proposal = issues::create_for_mission(
3593        gateway,
3594        &registry,
3595        (person, operation_id),
3596        (&create.tracker, &title, &body),
3597        brief,
3598    )
3599    .await?;
3600    let audit = AuditRecord {
3601        id: Uuid::new_v4().to_string(),
3602        actor: crate::actor_of(person),
3603        action: "mission.create.requested".to_owned(),
3604        operation: operation_id.to_string(),
3605        resource: None,
3606        target: format!("issue-proposal {proposal}"),
3607        at: received_at,
3608    };
3609    tokio::task::spawn_blocking(move || registry.record_audit(&audit))
3610        .await
3611        .map_err(|_| ApiError::internal())?
3612        .map_err(|_| ApiError::internal())?;
3613    Ok((
3614        StatusCode::ACCEPTED,
3615        Json(MissionCreated {
3616            operation_id: operation_id.to_string(),
3617            mission_id: None,
3618            handle: None,
3619            proposal: Some(proposal),
3620            state: "awaiting_issue".to_owned(),
3621        }),
3622    ))
3623}
3624
3625fn valid_station_list(stations: &[String]) -> bool {
3626    stations.len() <= 64
3627        && stations.iter().all(|station| {
3628            !station.is_empty() && station.len() <= 256 && !station.chars().any(char::is_control)
3629        })
3630}
3631
3632/// Why a Mission may not be pinned to `named`, if it may not: one names no Station that ever
3633/// checked in, or one the Operation's own `stations` leaves out. Pins match Station IDs exactly,
3634/// so an unknown one is told the IDs it equals ignoring case, and those of Stations on a host of
3635/// that name.
3636fn station_pin_refusal(
3637    named: &[String],
3638    records: &[ai6::StationRecord],
3639    policy: Option<&ai6::OperationPolicy>,
3640    operation: &str,
3641) -> Option<String> {
3642    for station in named {
3643        if !records.iter().any(|record| record.station() == station) {
3644            let near: Vec<&str> = records
3645                .iter()
3646                .filter(|record| {
3647                    record.station().eq_ignore_ascii_case(station)
3648                        || record
3649                            .check_in()
3650                            .common
3651                            .host
3652                            .as_deref()
3653                            .is_some_and(|host| host.eq_ignore_ascii_case(station))
3654                })
3655                .map(ai6::StationRecord::station)
3656                .collect();
3657            let hint = if near.is_empty() {
3658                String::new()
3659            } else {
3660                format!("; Stations it may mean: {}", near.join(", "))
3661            };
3662            return Some(format!(
3663                "no Station {station:?} has checked in (a pin is an exact Station ID){hint}"
3664            ));
3665        }
3666        if let Some(policy) = policy
3667            && !policy.stations.is_empty()
3668            && !policy.stations.contains(station)
3669        {
3670            return Some(format!(
3671                "Operation {operation:?} does not run on Station {station:?}: its stations are [{}]",
3672                policy.stations.join(", ")
3673            ));
3674        }
3675    }
3676    None
3677}
3678
3679/// The Operation's placement policy as a Station published it at check-in: the Headquarters
3680/// Station's copy when it publishes one, else the first Station's that does.
3681fn published_policy<'a>(
3682    records: &'a [ai6::StationRecord],
3683    headquarters: Option<&str>,
3684    operation: &str,
3685) -> Option<(&'a ai6::StationRecord, ai6::OperationPolicy)> {
3686    let published =
3687        |record: &ai6::StationRecord| record.check_in().operation_policy(operation).cloned();
3688    headquarters
3689        .and_then(|station| records.iter().find(|record| record.station() == station))
3690        .and_then(|record| published(record).map(|policy| (record, policy)))
3691        .or_else(|| {
3692            records
3693                .iter()
3694                .find_map(|record| published(record).map(|policy| (record, policy)))
3695        })
3696}
3697
3698#[derive(Deserialize)]
3699#[serde(deny_unknown_fields)]
3700struct PlacementPreviewQuery {
3701    agent: Option<String>,
3702    role: Option<String>,
3703    /// Comma-separated Station IDs the Mission would narrow placement to.
3704    stations: Option<String>,
3705    /// Comma-separated tags the Agent must carry.
3706    tags: Option<String>,
3707}
3708
3709/// Where a Mission for the Operation would run, and why each other place would not.
3710#[non_exhaustive]
3711#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3712pub struct PlacementPreview {
3713    /// The Operation previewed.
3714    pub operation_id: String,
3715    /// The Station whose copy of the Operation's policy was used: the Headquarters Station
3716    /// when it publishes one, otherwise the first Station that does.
3717    pub policy_station: String,
3718    /// Eligible (Station, Theater, Agent) choices, best first.
3719    pub choices: Vec<ai6::PlacementChoice>,
3720    /// Everything ruled out, each with its reason.
3721    pub rejections: Vec<ai6::PlacementRejection>,
3722}
3723
3724fn comma_list(value: Option<String>) -> Vec<String> {
3725    value
3726        .iter()
3727        .flat_map(|list| list.split(','))
3728        .map(str::trim)
3729        .filter(|item| !item.is_empty())
3730        .map(str::to_owned)
3731        .collect()
3732}
3733
3734async fn placement_preview(
3735    State(gateway): State<Gateway>,
3736    headers: HeaderMap,
3737    Path(operation_id): Path<String>,
3738    Query(query): Query<PlacementPreviewQuery>,
3739) -> Result<Json<PlacementPreview>, ApiError> {
3740    let person = resolve_user(&gateway, bearer(&headers)?).await?;
3741    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
3742    authorize_operation_action(&gateway, person, &operation_id, "mission.read").await?;
3743    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
3744    let mut request = ai6::PlacementRequest::default();
3745    request.stations = comma_list(query.stations);
3746    request.agent = query.agent.filter(|agent| !agent.trim().is_empty());
3747    request.role = query.role.filter(|role| !role.trim().is_empty());
3748    request.tags = comma_list(query.tags);
3749    if !valid_station_list(&request.stations) || request.tags.len() > 32 {
3750        return Err(ApiError::bad_request());
3751    }
3752    let operation = operation_id.to_string();
3753    let preview = tokio::task::spawn_blocking(move || {
3754        let records = registry
3755            .stations(Duration::MAX)
3756            .map_err(|_| ApiError::internal())?;
3757        let headquarters = registry.headquarters().map_err(|_| ApiError::internal())?;
3758        let leases = registry.leases().map_err(|_| ApiError::internal())?;
3759        let (source, policy) = published_policy(
3760            &records,
3761            headquarters.as_ref().map(|lease| lease.station()),
3762            &operation,
3763        )
3764        .ok_or_else(|| ApiError::from(GatewayError::NotFound))?;
3765        let now = SystemTime::now()
3766            .duration_since(UNIX_EPOCH)
3767            .map_err(|_| ApiError::internal())?
3768            .as_secs_f64();
3769        let stations = records
3770            .iter()
3771            .map(|record| {
3772                let load = leases
3773                    .iter()
3774                    .filter(|lease| lease.station() == record.station())
3775                    .count();
3776                ai6::StationFacts::from_record(
3777                    record,
3778                    now,
3779                    registry.limits().stations.gone_dark_after.0,
3780                    load,
3781                )
3782            })
3783            .collect::<Vec<_>>();
3784        let placement = ai6::place(&policy, &request, &stations);
3785        Ok::<_, ApiError>(PlacementPreview {
3786            operation_id: operation,
3787            policy_station: source.station().to_owned(),
3788            choices: placement.choices,
3789            rejections: placement.rejections,
3790        })
3791    })
3792    .await
3793    .map_err(|_| ApiError::internal())??;
3794    Ok(Json(preview))
3795}
3796
3797async fn list_user_mission_proposals(
3798    State(gateway): State<Gateway>,
3799    headers: HeaderMap,
3800    Path(operation_id): Path<String>,
3801) -> Result<Json<Vec<MissionProposal>>, ApiError> {
3802    let person = resolve_user(&gateway, bearer(&headers)?).await?;
3803    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
3804    authorize_operation_action(&gateway, person, &operation_id, "mission.create").await?;
3805    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
3806    ensure_operation_registered(&registry, &operation_id).await?;
3807    let operation = operation_id.to_string();
3808    let proposals =
3809        tokio::task::spawn_blocking(move || registry.list_mission_proposals(&operation, 100))
3810            .await
3811            .map_err(|_| ApiError::internal())?
3812            .map_err(|_| ApiError::internal())?;
3813    Ok(Json(proposals))
3814}
3815
3816async fn approve_user_mission_proposal(
3817    State(gateway): State<Gateway>,
3818    headers: HeaderMap,
3819    Path((operation_id, proposal_id)): Path<(String, String)>,
3820) -> Result<(StatusCode, Json<MissionProposalDecisionResponse>), ApiError> {
3821    let person = resolve_user(&gateway, bearer(&headers)?).await?;
3822    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
3823    validate_proposal_path_id(&proposal_id)?;
3824    authorize_operation_action(&gateway, person.clone(), &operation_id, "mission.create").await?;
3825    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
3826    ensure_operation_registered(&registry, &operation_id).await?;
3827    let operation = operation_id.to_string();
3828    let requested_id = proposal_id.clone();
3829    let approver = person.id.clone();
3830    let now = unix_timestamp()?;
3831    // The operator saw the proposal's vetting: only a malformed brief is stopped again. The
3832    // brief is promoted and cleared in one step, so no intake round sees it uncleared.
3833    let cleared = ai6::FindingKind::ALL
3834        .into_iter()
3835        .filter(|kind| *kind != ai6::FindingKind::Malformed)
3836        .collect::<Vec<_>>();
3837    let brief = tokio::task::spawn_blocking(move || {
3838        registry.promote_cleared(
3839            &operation,
3840            &requested_id,
3841            GATEWAY_RECEIVER,
3842            &cleared,
3843            &approver,
3844            now,
3845        )
3846    })
3847    .await
3848    .map_err(|_| ApiError::internal())?
3849    .map_err(proposal_registry_error)?;
3850    let mission_id = MissionId::new(brief.key()).map_err(|_| ApiError::internal())?;
3851    record_proposal_audit(
3852        &gateway,
3853        person,
3854        &operation_id,
3855        &proposal_id,
3856        "mission.proposal.approved",
3857    )
3858    .await?;
3859    Ok((
3860        StatusCode::ACCEPTED,
3861        Json(MissionProposalDecisionResponse {
3862            operation_id: operation_id.to_string(),
3863            proposal_id,
3864            mission_id: Some(mission_id.to_string()),
3865            handle: Some(brief.shown_handle()),
3866            state: "queued",
3867        }),
3868    ))
3869}
3870
3871async fn reject_user_mission_proposal(
3872    State(gateway): State<Gateway>,
3873    headers: HeaderMap,
3874    Path((operation_id, proposal_id)): Path<(String, String)>,
3875) -> Result<Json<MissionProposalDecisionResponse>, ApiError> {
3876    let person = resolve_user(&gateway, bearer(&headers)?).await?;
3877    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
3878    validate_proposal_path_id(&proposal_id)?;
3879    authorize_operation_action(&gateway, person.clone(), &operation_id, "mission.create").await?;
3880    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
3881    ensure_operation_registered(&registry, &operation_id).await?;
3882    let operation = operation_id.to_string();
3883    let requested_id = proposal_id.clone();
3884    tokio::task::spawn_blocking(move || {
3885        registry.reject_mission_proposal(&operation, &requested_id)
3886    })
3887    .await
3888    .map_err(|_| ApiError::internal())?
3889    .map_err(proposal_registry_error)?;
3890    record_proposal_audit(
3891        &gateway,
3892        person,
3893        &operation_id,
3894        &proposal_id,
3895        "mission.proposal.rejected",
3896    )
3897    .await?;
3898    Ok(Json(MissionProposalDecisionResponse {
3899        operation_id: operation_id.to_string(),
3900        proposal_id,
3901        mission_id: None,
3902        handle: None,
3903        state: "rejected",
3904    }))
3905}
3906
3907fn validate_proposal_path_id(proposal_id: &str) -> Result<(), ApiError> {
3908    if proposal_id.is_empty()
3909        || proposal_id.len() > 128
3910        || proposal_id
3911            .chars()
3912            .any(|character| character.is_control() || matches!(character, '/' | '\\'))
3913    {
3914        return Err(ApiError::bad_request());
3915    }
3916    Ok(())
3917}
3918
3919fn proposal_registry_error(error: std::io::Error) -> ApiError {
3920    match error.kind() {
3921        std::io::ErrorKind::NotFound => ApiError::not_found(),
3922        std::io::ErrorKind::AlreadyExists => ApiError::from(GatewayError::Conflict),
3923        std::io::ErrorKind::InvalidInput => ApiError::bad_request(),
3924        _ => ApiError::internal(),
3925    }
3926}
3927
3928async fn record_proposal_audit(
3929    gateway: &Gateway,
3930    person: Person,
3931    operation_id: &OperationId,
3932    proposal_id: &str,
3933    action: &'static str,
3934) -> Result<(), ApiError> {
3935    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
3936    let entry = AuditRecord {
3937        id: Uuid::new_v4().to_string(),
3938        actor: crate::actor_of(&person),
3939        action: action.to_owned(),
3940        operation: operation_id.to_string(),
3941        resource: None,
3942        target: proposal_id.to_owned(),
3943        at: unix_timestamp()?,
3944    };
3945    tokio::task::spawn_blocking(move || registry.record_audit(&entry))
3946        .await
3947        .map_err(|_| ApiError::internal())?
3948        .map_err(|_| ApiError::internal())?;
3949    Ok(())
3950}
3951
3952async fn authorized_board_runs(
3953    gateway: &Gateway,
3954    headers: &HeaderMap,
3955) -> Result<Vec<BoardRun>, ApiError> {
3956    let person = resolve_user(gateway, bearer(headers)?).await?;
3957    let authorizer = gateway.authorizer()?;
3958    let runs = gateway.board_runs().await;
3959    let tree = operation_tree(gateway).await?;
3960    let visible = tokio::task::spawn_blocking(move || {
3961        let mut visible = Vec::new();
3962        // One decision per Operation, not per Run.
3963        let mut readable = HashMap::<String, bool>::new();
3964        for run in runs {
3965            let allowed = match readable.get(&run.operation_id) {
3966                Some(allowed) => *allowed,
3967                None => {
3968                    let decision = authorizer
3969                        .authorize(operation_request(
3970                            person.clone(),
3971                            "mission.read",
3972                            &run.operation_id,
3973                            &tree,
3974                        ))
3975                        .map_err(|_| ())?;
3976                    readable.insert(run.operation_id.clone(), decision.allowed);
3977                    decision.allowed
3978                }
3979            };
3980            // A compartment may cover this Mission alone, not its Operation.
3981            if allowed
3982                || authorizer.allows_mission(
3983                    &person,
3984                    ai6::CompartmentAction::MissionRead,
3985                    &run.mission_id,
3986                    &run.operation_id,
3987                )
3988            {
3989                visible.push(run);
3990            }
3991        }
3992        Ok::<_, ()>(visible)
3993    })
3994    .await
3995    .map_err(|_| ApiError::internal())?
3996    .map_err(|_| ApiError::internal())?;
3997    Ok(visible)
3998}
3999
4000/// When a Run record last changed in a way the board shows, as Unix seconds: its close, or
4001/// else its opening; zero when it recorded neither.
4002fn record_updated_at(record: &ai6::RunRecord) -> f64 {
4003    record.closed_at.or(record.opened_at).unwrap_or(0.0)
4004}
4005
4006fn board_run_from_record(
4007    record: &ai6::RunRecord,
4008    operation_id: String,
4009    agent: Option<String>,
4010) -> BoardRun {
4011    BoardRun {
4012        operation_id,
4013        mission_id: record.mission_id.clone(),
4014        run_id: record
4015            .provider_id
4016            .clone()
4017            .unwrap_or_else(|| record.id.clone()),
4018        state: record.result.as_ref().map(|result| result.state.clone()),
4019        reason: record
4020            .result
4021            .as_ref()
4022            .and_then(|result| result.reason.clone()),
4023        sequence: 0,
4024        updated_at: Some(record_updated_at(record)).filter(|at| *at > 0.0),
4025        exposure: record
4026            .exposure
4027            .iter()
4028            .map(|exposure| exposure.source.clone())
4029            .collect(),
4030        station_id: Some(record.station.clone()),
4031        agent: agent.or_else(|| {
4032            record
4033                .launch
4034                .as_ref()
4035                .and_then(|launch| launch.agent.clone())
4036        }),
4037    }
4038}
4039
4040/// Looks up a single historical Run even when it has aged out of the board or was superseded.
4041async fn filed_run(
4042    State(gateway): State<Gateway>,
4043    headers: HeaderMap,
4044    Path(id): Path<String>,
4045) -> Result<Json<BoardRun>, ApiError> {
4046    let person = resolve_user(&gateway, bearer(&headers)?).await?;
4047    RunId::new(id.clone()).map_err(|_| ApiError::not_found())?;
4048    let registry = gateway.registry.clone().ok_or_else(ApiError::not_found)?;
4049    let authorizer = gateway.authorizer()?;
4050    let tree = operation_tree(&gateway).await?;
4051    let run = tokio::task::spawn_blocking(move || -> std::io::Result<_> {
4052        let record = match registry.run(&id)? {
4053            Some(record) => record,
4054            None => {
4055                let mut matches = registry
4056                    .runs()?
4057                    .into_iter()
4058                    .filter(|run| run.provider_id.as_deref() == Some(id.as_str()));
4059                let Some(record) = matches.next().filter(|_| matches.next().is_none()) else {
4060                    return Ok(None);
4061                };
4062                record
4063            }
4064        };
4065        let filed = registry.filed_brief(&record.mission_id)?;
4066        let brief = filed.as_ref().map(|filed| &filed.brief);
4067        let Some(operation) = record
4068            .operation
4069            .as_deref()
4070            .or_else(|| brief.and_then(|brief| brief.operation.as_deref()))
4071        else {
4072            return Ok(None);
4073        };
4074        let allowed = authorizer
4075            .authorize(operation_request(
4076                person.clone(),
4077                "mission.read",
4078                operation,
4079                &tree,
4080            ))
4081            .is_ok_and(|decision| decision.allowed)
4082            || authorizer.allows_mission(
4083                &person,
4084                ai6::CompartmentAction::MissionRead,
4085                &record.mission_id,
4086                operation,
4087            );
4088        let agent = brief
4089            .filter(|brief| brief.operation.as_deref() == Some(operation))
4090            .and_then(|brief| brief.agent.clone());
4091        Ok(allowed.then(|| board_run_from_record(&record, operation.to_owned(), agent)))
4092    })
4093    .await
4094    .map_err(|_| ApiError::internal())?
4095    .map_err(|_| ApiError::internal())?;
4096    run.map(Json).ok_or_else(ApiError::not_found)
4097}
4098
4099fn group_missions(runs: Vec<BoardRun>) -> Vec<BoardMission> {
4100    let mut missions = BTreeMap::<(String, String), Vec<BoardRun>>::new();
4101    for run in runs {
4102        missions
4103            .entry((run.operation_id.clone(), run.mission_id.clone()))
4104            .or_default()
4105            .push(run);
4106    }
4107    missions
4108        .into_iter()
4109        .map(|((operation_id, mission_id), runs)| BoardMission {
4110            operation_id,
4111            handle: mission_id.clone(),
4112            mission_id,
4113            runs,
4114            brief: None,
4115            usage: None,
4116            history: Vec::new(),
4117            conversation_tokens: None,
4118            pending: None,
4119            revision: None,
4120        })
4121        .collect()
4122}
4123
4124/// The Mission a route names by `id`: its UID, the key of a brief dropped by hand, or any
4125/// handle it was ever given, compared without case, with the handle it goes by now. An ID the
4126/// Registry does not know, a Mission started on a Station rather than from the queue, is taken
4127/// as it is.
4128pub(crate) async fn named_mission(gateway: &Gateway, id: &str) -> Result<MissionHandle, ApiError> {
4129    let Some(registry) = gateway.registry.clone() else {
4130        return Ok(MissionHandle::new(id, id));
4131    };
4132    let wanted = id.to_owned();
4133    let found = tokio::task::spawn_blocking(move || registry.resolve_mission(&wanted))
4134        .await
4135        .map_err(|_| ApiError::internal())?
4136        .map_err(|_| ApiError::internal())?;
4137    Ok(found.unwrap_or_else(|| MissionHandle::new(id, id)))
4138}
4139
4140/// The UID of the Mission a route names by `id`, as [`named_mission`] finds it.
4141pub(crate) async fn mission_key(gateway: &Gateway, id: &str) -> Result<String, ApiError> {
4142    Ok(named_mission(gateway, id).await?.mission_id)
4143}
4144
4145/// `POST /v1/user/operations/{operation_id}/missions/{mission_id}/rename`: gives the Mission
4146/// the handle `{"handle": …}`, under `mission.control`. Its UID, and everything keyed by it,
4147/// stays; the old handle still names it. A refusal is `{"error": TEXT}`.
4148async fn rename_user_mission(
4149    State(gateway): State<Gateway>,
4150    headers: HeaderMap,
4151    Path((operation_id, mission_id)): Path<(String, String)>,
4152    Json(request): Json<RenameMission>,
4153) -> Result<Json<RenamedMission>, refused::Refused> {
4154    let person = resolve_user(&gateway, bearer(&headers)?).await?;
4155    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
4156    authorize_operation_action(&gateway, person.clone(), &operation_id, "mission.control").await?;
4157    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
4158    let named = named_mission(&gateway, &mission_id).await?;
4159    let (store, uid, operation, handle) = (
4160        registry.clone(),
4161        named.mission_id.clone(),
4162        operation_id.to_string(),
4163        request.handle,
4164    );
4165    let renamed = tokio::task::spawn_blocking(move || {
4166        let filed = store.filed_brief(&uid)?;
4167        if filed.is_none_or(|filed| filed.brief.operation.as_deref() != Some(operation.as_str())) {
4168            return Err(std::io::Error::new(
4169                std::io::ErrorKind::NotFound,
4170                "the Operation has no such Mission",
4171            ));
4172        }
4173        store.rename_mission(&uid, &handle)
4174    })
4175    .await
4176    .map_err(|_| ApiError::internal())?
4177    .map_err(|error| {
4178        let status = match error.kind() {
4179            std::io::ErrorKind::NotFound => StatusCode::NOT_FOUND,
4180            std::io::ErrorKind::InvalidInput => StatusCode::BAD_REQUEST,
4181            std::io::ErrorKind::AlreadyExists => StatusCode::CONFLICT,
4182            _ => return refused::Refused::from(ApiError::internal()),
4183        };
4184        refused::refused(status, error.to_string())
4185    })?;
4186    let at = unix_timestamp()?;
4187    let audit = AuditRecord {
4188        id: Uuid::new_v4().to_string(),
4189        actor: crate::actor_of(&person),
4190        action: "mission.rename".to_owned(),
4191        operation: operation_id.to_string(),
4192        resource: Some(format!("mission:{}", renamed.mission_id)),
4193        target: renamed.mission_id.clone(),
4194        at,
4195    };
4196    let event = TimelineEvent::new("control", "rename.done", operation_id.to_string(), at)
4197        .mission(renamed.mission_id.clone())
4198        .actor(person.id)
4199        .detail(TimelineDetailKey::Handle, renamed.handle.clone())
4200        .detail(TimelineDetailKey::Previous, named.handle.clone());
4201    tokio::task::spawn_blocking(move || {
4202        registry.record_audit(&audit)?;
4203        registry.record_event(&event)
4204    })
4205    .await
4206    .map_err(|_| ApiError::internal())?
4207    .map_err(|_| ApiError::internal())?;
4208    Ok(Json(RenamedMission {
4209        operation_id: operation_id.to_string(),
4210        mission_id: renamed.mission_id,
4211        handle: renamed.handle,
4212        previous: named.handle,
4213    }))
4214}
4215
4216/// Backfills the historical Mission Reports of one Operation for its configuration managers.
4217async fn backfill_missions(
4218    State(gateway): State<Gateway>,
4219    headers: HeaderMap,
4220    Path(operation): Path<String>,
4221) -> Result<Json<ai6::directorates::registry::backfill::BackfillSummary>, ApiError> {
4222    let person = resolve_user(&gateway, bearer(&headers)?).await?;
4223    let operation = OperationId::new(operation).map_err(|_| ApiError::bad_request())?;
4224    authorize_operation_action(&gateway, person.clone(), &operation, "mission.control").await?;
4225    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
4226    let at = unix_timestamp()?;
4227    tokio::task::spawn_blocking(move || {
4228        ai6::directorates::registry::backfill::backfill(
4229            registry.as_ref(),
4230            operation.as_str(),
4231            &actor_of(&person),
4232            at,
4233        )
4234    })
4235    .await
4236    .map_err(|_| ApiError::internal())?
4237    .map(Json)
4238    .map_err(|_| ApiError::internal())
4239}
4240
4241async fn health() -> StatusCode {
4242    StatusCode::NO_CONTENT
4243}
4244
4245#[derive(Deserialize)]
4246struct IssueAccessTokenRequest {
4247    person_id: String,
4248    ttl_seconds: u64,
4249}
4250
4251/// What `POST /v1/auth/renew` answers: the token's times, and no secret.
4252#[derive(Serialize)]
4253struct RenewedAccessToken {
4254    token_id: String,
4255    expires_at: f64,
4256    /// Seconds it has left, so a client schedules by this rather than by its own clock.
4257    expires_in: f64,
4258    /// When renewing stops ([`session_end`]).
4259    ends_at: Option<f64>,
4260    /// When the sign-in goes idle without another renewal; `None` with no idle limit.
4261    idle_ends_at: Option<f64>,
4262}
4263
4264/// Seconds a sign-in may go without a renewal (`session_idle`); `None` with no limit.
4265fn idle_seconds(table: &ai6::UnexGatewayLimits) -> Option<f64> {
4266    table.session_idle.get().map(|idle| idle.as_secs_f64())
4267}
4268
4269/// How long a token granted now lasts: `ttl`, or the idle limit when that is shorter, since a
4270/// token not renewed in time is a sign-in that went idle.
4271fn sign_in_ttl(table: &ai6::UnexGatewayLimits, ttl: Duration) -> Duration {
4272    table.session_idle.get().map_or(ttl, |idle| ttl.min(idle))
4273}
4274
4275/// When renewing a token stops: `session_max` after it was issued, or its own expiry when that
4276/// is later (a lifetime asked for at sign-in, or renewal turned off). `None` with no bound.
4277fn session_end(issued_at: f64, expires_at: f64, session_max: TimeLimit) -> Option<f64> {
4278    session_max
4279        .get()
4280        .map(|max| (issued_at + max.as_secs_f64()).max(expires_at))
4281}
4282
4283/// How long a token is issued for: `asked`, seconds within `access_token_max_ttl`, else the
4284/// gateway's `access_token_ttl`.
4285fn access_token_ttl(gateway: &Gateway, asked: Option<u64>) -> Result<Duration, ApiError> {
4286    let table = &gateway.config.unex().gateway;
4287    let Some(asked) = asked else {
4288        return Ok(table.access_token_ttl.0);
4289    };
4290    let asked = Duration::from_secs(asked);
4291    if !table.access_token_max_ttl.allows(asked) {
4292        return Err(ApiError::bad_request());
4293    }
4294    Ok(asked)
4295}
4296
4297#[derive(Serialize)]
4298struct AccessSession {
4299    token_id: String,
4300    person_id: String,
4301    expires_at: f64,
4302}
4303
4304#[derive(Serialize)]
4305struct UserProfile {
4306    person_id: String,
4307    name: String,
4308    display_name: Option<String>,
4309    /// The two letters of the avatar, from the directory's given name and surname; absent
4310    /// when the directory gave neither, and the client derives them from the name.
4311    #[serde(skip_serializing_if = "Option::is_none")]
4312    initials: Option<String>,
4313    groups: Vec<String>,
4314    expires_at: f64,
4315    operations: Vec<UserOperationAccess>,
4316    stations: Vec<UserStationAccess>,
4317    /// The actions the person holds on the roster (`config:roster`).
4318    roster: Vec<String>,
4319    /// For each configuration family the roster routes serve beyond the roster (`charges`), the
4320    /// actions the person holds on `config:<family>`; a family with none is absent.
4321    config: BTreeMap<String, Vec<String>>,
4322    /// The actions the person holds on the global access policy (`access.read`, `access.manage`),
4323    /// the accounts (`account.manage`), other people's memory (`assistant.memory.admin`) and the
4324    /// global memory (`memory.write`), and approving a provider library (`plugin.manage`).
4325    global_actions: Vec<String>,
4326    /// The actions the person holds on M's own Reports (`config:reports`): `station.read` and
4327    /// `station.configure`.
4328    reports: Vec<String>,
4329    /// Whether this gateway serves Moneypenny, whom Outer Office offers only when it does.
4330    moneypenny: bool,
4331}
4332
4333#[derive(Serialize)]
4334struct UserOperationAccess {
4335    operation_id: String,
4336    /// What the Operation is called, when it has a name.
4337    #[serde(skip_serializing_if = "Option::is_none")]
4338    name: Option<String>,
4339    /// The nearest Operation above it the person may read; omitted for a root or when every
4340    /// ancestor is hidden from them.
4341    #[serde(skip_serializing_if = "Option::is_none")]
4342    parent: Option<String>,
4343    actions: Vec<String>,
4344    /// The compartments that give the person something here.
4345    #[serde(skip_serializing_if = "Vec::is_empty")]
4346    compartments: Vec<String>,
4347}
4348
4349#[derive(Serialize)]
4350struct UserStationAccess {
4351    station_id: String,
4352    actions: Vec<String>,
4353}
4354
4355#[derive(Serialize)]
4356struct StationSettingsResponse {
4357    station_id: String,
4358    max_concurrent_missions: usize,
4359    min_free_memory_mb: u64,
4360    max_cpu_percent: u32,
4361    configured: bool,
4362    execution_enabled: bool,
4363}
4364
4365/// A settings change; an absent resource limit keeps its current value.
4366#[derive(Deserialize)]
4367#[serde(deny_unknown_fields)]
4368struct UpdateStationSettings {
4369    max_concurrent_missions: usize,
4370    #[serde(default)]
4371    min_free_memory_mb: Option<u64>,
4372    #[serde(default)]
4373    max_cpu_percent: Option<u32>,
4374}
4375
4376#[derive(Serialize)]
4377struct AgentRoleResponse {
4378    #[serde(flatten)]
4379    role: AgentRole,
4380    operation_override: bool,
4381}
4382
4383#[derive(Serialize)]
4384struct RevokedAccessToken {
4385    revoked: bool,
4386}
4387
4388async fn issue_access_token(
4389    State(gateway): State<Gateway>,
4390    headers: HeaderMap,
4391    Json(request): Json<IssueAccessTokenRequest>,
4392) -> Result<(StatusCode, Json<IssuedAccessToken>), ApiError> {
4393    gateway
4394        .authenticate_station(bearer(&headers)?)
4395        .map_err(ApiError::from)?;
4396    let ttl = access_token_ttl(&gateway, Some(request.ttl_seconds))?;
4397    let registry = gateway.registry.clone().ok_or_else(ApiError::internal)?;
4398    let session_max = gateway.config.unex().gateway.session_max;
4399    let issued = issue_access_token_record(registry, request.person_id, ttl, session_max).await?;
4400    Ok((StatusCode::CREATED, Json(issued)))
4401}
4402
4403/// What `POST /v1/auth/login` accepts here, so a sign-in page asks for nothing it cannot use.
4404/// Says nothing about any account, so it needs no token.
4405#[derive(Serialize)]
4406struct AuthMethods {
4407    /// What the sign-in policy offers this request: `password` (a name and a secret), `proxy` (an
4408    /// identity the reverse proxy asserts), or any other method the policy names.
4409    methods: Vec<String>,
4410    /// `next` while a sign-in that has passed some steps waits for the rest.
4411    #[serde(skip_serializing_if = "Option::is_none")]
4412    step: Option<&'static str>,
4413}
4414
4415async fn auth_methods(
4416    State(gateway): State<Gateway>,
4417    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
4418    headers: HeaderMap,
4419) -> Result<Json<AuthMethods>, ApiError> {
4420    let Some(providers) = gateway.access.clone() else {
4421        return Ok(Json(AuthMethods {
4422            methods: Vec::new(),
4423            step: None,
4424        }));
4425    };
4426    let address = connection.map(|Extension(ConnectInfo(address))| address);
4427    if let Some(token) = headers
4428        .get(second_factor::PENDING_HEADER)
4429        .and_then(|value| value.to_str().ok())
4430    {
4431        let methods =
4432            second_factor::offer_next(&gateway, &providers, &headers, address, token).await?;
4433        return Ok(Json(AuthMethods {
4434            methods,
4435            step: Some("next"),
4436        }));
4437    }
4438    let context = gateway.sign_in_context(
4439        ai6::directorates::m::access::purposes::SIGN_IN,
4440        &headers,
4441        address,
4442        sign_in::SERVICE,
4443    );
4444    let mut methods: Vec<String> = Vec::new();
4445    for offer in gateway
4446        .decide_sign_in(&providers, context)
4447        .await
4448        .map(|decision| decision.methods)
4449        .unwrap_or_default()
4450    {
4451        if !methods.contains(&offer.method) {
4452            methods.push(offer.method);
4453        }
4454    }
4455    Ok(Json(AuthMethods {
4456        methods,
4457        step: None,
4458    }))
4459}
4460
4461async fn login(
4462    State(gateway): State<Gateway>,
4463    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
4464    certificates: Option<Extension<tls::ClientCertificates>>,
4465    headers: HeaderMap,
4466    Json(request): Json<LoginRequest>,
4467) -> Result<Response, ApiError> {
4468    let address = connection.map(|Extension(ConnectInfo(address))| address);
4469    // A next step of a sign-in that is under way, or a code with none under way.
4470    if request.pending.is_some()
4471        || request.method.as_deref().is_some_and(|method| {
4472            ai6::directorates::m::access::methods::NEEDS_ACCOUNT.contains(&method)
4473        })
4474    {
4475        let chain = certificates.map(|Extension(tls::ClientCertificates(chain))| chain);
4476        return second_factor::continue_login(&gateway, address, chain, &headers, request).await;
4477    }
4478    // A browser always names the page's origin on a POST, and nothing else this gateway serves
4479    // does, so that is what tells a web sign-in from a desktop app's or an API client's.
4480    let from_browser = headers.contains_key(ORIGIN);
4481    if from_browser {
4482        require_login_origin(&gateway, &headers)?;
4483    }
4484    let ttl = sign_in_ttl(
4485        &gateway.config.unex().gateway,
4486        access_token_ttl(&gateway, request.ttl_seconds)?,
4487    );
4488    let wants_cookie = from_browser && request.session_cookie != Some(false);
4489    let providers = gateway.access.clone().ok_or_else(ApiError::unavailable)?;
4490    // The method presented is decided before any provider is asked or any try is counted: a
4491    // refusal costs the address nothing.
4492    let proxied = providers
4493        .proxy_identity
4494        .as_ref()
4495        .is_some_and(|proxy| headers.contains_key(&proxy.header));
4496    let method = if proxied { "proxy" } else { "password" };
4497    let context = gateway.sign_in_context(
4498        ai6::directorates::m::access::purposes::SIGN_IN,
4499        &headers,
4500        address,
4501        sign_in::SERVICE,
4502    );
4503    let offer = gateway
4504        .decide_sign_in(&providers, context.clone())
4505        .await
4506        .and_then(|decision| {
4507            decision
4508                .methods
4509                .into_iter()
4510                .find(|offer| offer.method == method)
4511        })
4512        .ok_or_else(sign_in::not_accepted)?;
4513    let (person, step) = if proxied {
4514        let person = proxy_person(&gateway, &providers, &headers)
4515            .await?
4516            .ok_or_else(ApiError::unauthorized)?;
4517        let step = sign_in::step(method, None, &person)?;
4518        (person, step)
4519    } else {
4520        let (person, provider) = authenticate_password(
4521            &gateway,
4522            &providers,
4523            &headers,
4524            address,
4525            request.clone(),
4526            &offer.providers,
4527        )
4528        .await?;
4529        let step = sign_in::step(method, provider.as_deref(), &person)?;
4530        (person, step)
4531    };
4532    // A valid factor is decided again with the person. A complete sign-in is issued; one the
4533    // policy offers more steps to waits for them; anything else is answered as a wrong
4534    // password is.
4535    let factors = vec![step];
4536    let decision = gateway
4537        .decide_sign_in(
4538            &providers,
4539            SignInContext {
4540                done: Gateway::passed(&factors),
4541                person: Some(person.clone()),
4542                ..context
4543            },
4544        )
4545        .await;
4546    match decision {
4547        Some(decision) if decision.complete => {
4548            complete_login(&gateway, from_browser, wants_cookie, ttl, person, factors).await
4549        }
4550        Some(decision) if !decision.methods.is_empty() => {
4551            let mut methods: Vec<String> = Vec::new();
4552            for offer in decision.methods {
4553                if !methods.contains(&offer.method) {
4554                    methods.push(offer.method);
4555                }
4556            }
4557            gateway
4558                .wait_for_next_step(&person, factors, methods, from_browser, &request)
4559                .await
4560        }
4561        _ => Err(ApiError::unauthorized()),
4562    }
4563}
4564
4565/// Opens the sign-in `factors` completed for `person`: its token, and for a browser its
4566/// cookies.
4567async fn complete_login(
4568    gateway: &Gateway,
4569    from_browser: bool,
4570    wants_cookie: bool,
4571    ttl: Duration,
4572    person: Person,
4573    factors: Vec<SignInFactor>,
4574) -> Result<Response, ApiError> {
4575    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
4576    let table = &gateway.config.unex().gateway;
4577    let session_max = table.session_max;
4578    let issued_at = unix_timestamp()?;
4579    let cookie = if wants_cookie && session_cookies_on(table) {
4580        Some(
4581            store_session_cookie(
4582                registry.clone(),
4583                &person.id,
4584                issued_at,
4585                session_max,
4586                idle_seconds(table),
4587                factors.clone(),
4588            )
4589            .await?,
4590        )
4591    } else {
4592        None
4593    };
4594    let sign_in = cookie.as_ref().map(|cookie| cookie.sign_in.clone());
4595    let issued = store_bearer(
4596        registry,
4597        person.id,
4598        Times {
4599            issued_at,
4600            expires_at: issued_at + ttl.as_secs_f64(),
4601            now: issued_at,
4602            idle: idle_seconds(table),
4603        },
4604        session_max,
4605        sign_in.clone(),
4606        factors,
4607    )
4608    .await?;
4609    let page_cookie = from_browser
4610        .then(|| page_cookie_for(gateway, &issued, sign_in.as_deref()))
4611        .flatten();
4612    let mut response = (StatusCode::CREATED, Json(issued)).into_response();
4613    if let Some(cookie) = cookie {
4614        response.headers_mut().insert(SET_COOKIE, cookie.header);
4615    }
4616    page_access::append(response.headers_mut(), page_cookie);
4617    Ok(response)
4618}
4619
4620/// The page cookie of a browser's sign-in that `issued` was issued in: it names the sign-in
4621/// (`sign_in`, the session cookie's record) when there is one, else the token itself, and lasts as
4622/// long as what it names may.
4623fn page_cookie_for(
4624    gateway: &Gateway,
4625    issued: &IssuedAccessToken,
4626    sign_in: Option<&str>,
4627) -> Option<HeaderValue> {
4628    let seconds = match sign_in {
4629        Some(_) => issued
4630            .ends_at
4631            .map_or(f64::MAX, |ends| ends - issued_now(issued)),
4632        None => issued.expires_in,
4633    };
4634    page_access::set_page_cookie(gateway, sign_in.unwrap_or(&issued.token_id), seconds)
4635}
4636
4637/// The moment `issued` was answered at, by its own times.
4638fn issued_now(issued: &IssuedAccessToken) -> f64 {
4639    issued.expires_at - issued.expires_in
4640}
4641
4642/// The person a trusted reverse proxy asserts on this request; `None` when it asserts nobody.
4643async fn proxy_person(
4644    gateway: &Gateway,
4645    providers: &AccessProviders,
4646    headers: &HeaderMap,
4647) -> Result<Option<Person>, ApiError> {
4648    let Some(proxy) = &providers.proxy_identity else {
4649        return Ok(None);
4650    };
4651    let Some(value) = headers.get(&proxy.header) else {
4652        return Ok(None);
4653    };
4654    require_login_origin(gateway, headers)?;
4655    let sent = headers
4656        .get(PROXY_SECRET_HEADER)
4657        .map(|value| value.as_bytes())
4658        .unwrap_or_default();
4659    let proven = proxy
4660        .secret
4661        .as_ref()
4662        .is_some_and(|secret| constant_time_eq(secret.as_bytes(), sent));
4663    if !proven {
4664        journal_login_refusal(LoginCheck::ProxySecret);
4665        return Err(ApiError::unauthorized());
4666    }
4667    let unusable = || {
4668        journal_login_refusal(LoginCheck::ProxyIdentity);
4669        ApiError::unauthorized()
4670    };
4671    let value = value.to_str().map_err(|_| unusable())?;
4672    let value = value.trim();
4673    if value.is_empty() || value.len() > 512 || value.contains(',') {
4674        return Err(unusable());
4675    }
4676    let directory = providers.directory.clone();
4677    let lookup = Lookup {
4678        by: proxy.lookup_by.clone(),
4679        value: value.to_owned(),
4680        ..Default::default()
4681    };
4682    tokio::task::spawn_blocking(move || directory.lookup(lookup))
4683        .await
4684        .map_err(|_| ApiError::internal())?
4685        .map_err(|_| ApiError::internal())?
4686        .ok_or_else(|| {
4687            journal_login_refusal(LoginCheck::DirectoryMiss);
4688            ApiError::unauthorized()
4689        })
4690        .map(Some)
4691}
4692
4693/// `POST /v1/auth/resume`: a fresh access token for the sign-in a session cookie holds, so a
4694/// reloaded page need not ask for the password. The sign-in's time keeps running from when it
4695/// was made. It answers as `login` does; a cookie that does not stand is cleared.
4696async fn resume(
4697    State(gateway): State<Gateway>,
4698    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
4699    headers: HeaderMap,
4700) -> Result<Response, ApiError> {
4701    // Unlike a bearer, a cookie goes along by itself, so the origin is not optional here.
4702    require_login_origin(&gateway, &headers)?;
4703    let value = session_cookie(&headers).ok_or_else(ApiError::unauthorized)?;
4704    let address = connection.map(|Extension(ConnectInfo(address))| address);
4705    if let Some((issued, sign_in)) = resumed_token(&gateway, &headers, address, value).await? {
4706        let page_cookie = page_cookie_for(&gateway, &issued, Some(&sign_in));
4707        let mut response = (StatusCode::CREATED, Json(issued)).into_response();
4708        page_access::append(response.headers_mut(), page_cookie);
4709        return Ok(response);
4710    }
4711    // Judged before being counted: the value cannot be guessed, so the count only slows a client
4712    // hammering this route, and must not keep out a good cookie behind the same address.
4713    let resume_guard = gateway.resume_guard();
4714    let source = resume_guard.source(&headers, address);
4715    let refusal = match resume_guard.tried_address(source) {
4716        Some(wait) => ApiError::too_many_attempts(wait),
4717        None => ApiError::unauthorized(),
4718    };
4719    let mut response = refusal.into_response();
4720    response.headers_mut().append(SET_COOKIE, ended_cookie()?);
4721    Ok(response)
4722}
4723
4724/// The token a session cookie's value gets, with the ID of its sign-in; `None` when it gets none: the setting is off, the
4725/// value is not a standing cookie, its time is up, its person has left the directory, or a
4726/// front proxy now says this browser is someone else.
4727async fn resumed_token(
4728    gateway: &Gateway,
4729    headers: &HeaderMap,
4730    address: Option<SocketAddr>,
4731    value: &str,
4732) -> Result<Option<(IssuedAccessToken, String)>, ApiError> {
4733    let table = &gateway.config.unex().gateway;
4734    if !session_cookies_on(table) {
4735        return Ok(None);
4736    }
4737    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
4738    let digest = session_cookie_digest(value);
4739    let found = registry.clone();
4740    let cookie = tokio::task::spawn_blocking(move || found.find_session_cookie(&digest))
4741        .await
4742        .map_err(|_| ApiError::internal())?
4743        .map_err(|_| ApiError::internal())?;
4744    let Some(cookie) = cookie else {
4745        return Ok(None);
4746    };
4747    let providers = gateway.access.clone().ok_or_else(ApiError::unavailable)?;
4748    let directory = providers.directory.clone();
4749    let person_id = cookie.person_id().to_owned();
4750    let person = tokio::task::spawn_blocking(move || {
4751        directory.lookup(Lookup {
4752            by: "id".to_owned(),
4753            value: person_id,
4754            ..Default::default()
4755        })
4756    })
4757    .await
4758    .map_err(|_| ApiError::internal())?
4759    .map_err(|_| ApiError::internal())?;
4760    let Some(person) = person else {
4761        return Ok(None);
4762    };
4763    let asserted = proxy_person(gateway, &providers, headers).await?;
4764    if asserted.is_some_and(|asserted| asserted.id != person.id) {
4765        return Ok(None);
4766    }
4767    let factors = cookie.factors();
4768    if !still_complete(
4769        gateway,
4770        &providers,
4771        headers,
4772        address,
4773        &person,
4774        factors,
4775        sign_in::SERVICE,
4776    )
4777    .await
4778    {
4779        return Ok(None);
4780    }
4781    let now = unix_timestamp()?;
4782    // The sign-in's end as it was set, or sooner if `session_max` has been lowered since.
4783    let ends = cookie
4784        .expires_at()
4785        .min(cookie.issued_at() + table.session_max.as_secs_f64());
4786    if ends <= now {
4787        return Ok(None);
4788    }
4789    let session_end = cookie.issued_at() + table.session_max.as_secs_f64();
4790    let ttl = sign_in_ttl(table, table.access_token_ttl.0).as_secs_f64();
4791    // A resumed sign-in is in use: its cookie goes on from now, and the new token with it.
4792    keep_cookie(
4793        registry.clone(),
4794        cookie.token_id(),
4795        now,
4796        idle_seconds(table),
4797        session_end,
4798    )
4799    .await;
4800    let kept = idle_seconds(table).map_or(session_end, |idle| (now + idle).min(session_end));
4801    let issued = store_bearer(
4802        registry,
4803        person.id,
4804        Times {
4805            issued_at: cookie.issued_at(),
4806            expires_at: (now + ttl).min(ends.max(kept)),
4807            now,
4808            idle: idle_seconds(table),
4809        },
4810        table.session_max,
4811        Some(cookie.token_id().to_owned()),
4812        cookie.factors().to_vec(),
4813    )
4814    .await?;
4815    Ok(Some((issued, cookie.token_id().to_owned())))
4816}
4817
4818/// `POST /v1/auth/renew`: moves the presented token's expiry on by `access_token_ttl`, up to
4819/// `session_max` after it was issued. The value does not change, so what is bound to it keeps
4820/// working; the person must still be in the directory, and it is no try at a password.
4821async fn renew(
4822    State(gateway): State<Gateway>,
4823    connection: Option<Extension<ConnectInfo<SocketAddr>>>,
4824    headers: HeaderMap,
4825) -> Result<Response, ApiError> {
4826    if headers.contains_key(ORIGIN) {
4827        require_origin(&gateway, &headers)?;
4828    }
4829    let token = bearer(&headers)?;
4830    let person = resolve_user(&gateway, token).await?;
4831    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
4832    let digest = access_token_digest(token);
4833    let record = tokio::task::spawn_blocking(move || registry.find_access_token(&digest))
4834        .await
4835        .map_err(|_| ApiError::internal())?
4836        .map_err(|_| ApiError::internal())?
4837        .ok_or_else(ApiError::unauthorized)?;
4838    let providers = gateway.access.clone().ok_or_else(ApiError::unavailable)?;
4839    let address = connection.map(|Extension(ConnectInfo(address))| address);
4840    let factors = record.factors();
4841    if !still_complete(
4842        &gateway,
4843        &providers,
4844        &headers,
4845        address,
4846        &person,
4847        factors,
4848        sign_in::SERVICE,
4849    )
4850    .await
4851    {
4852        return Err(ApiError::unauthorized());
4853    }
4854    let from_station = sign_in::from_station(factors);
4855    let table = &gateway.config.unex().gateway;
4856    let session_max = table.session_max;
4857    let now = unix_timestamp()?;
4858    let session_end_at = record.issued_at() + session_max.as_secs_f64();
4859    let expires_at =
4860        (now + sign_in_ttl(table, table.access_token_ttl.0).as_secs_f64()).min(session_end_at);
4861    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
4862    let token_id = record.token_id().to_owned();
4863    let extended =
4864        tokio::task::spawn_blocking(move || registry.extend_access_token(&token_id, expires_at))
4865            .await
4866            .map_err(|_| ApiError::internal())?
4867            .map_err(|_| ApiError::internal())?
4868            .ok_or_else(ApiError::unauthorized)?;
4869    let ends_at = session_end(extended.issued_at(), extended.expires_at(), session_max);
4870    if let Some(cookie) = extended.sign_in() {
4871        keep_cookie(
4872            gateway.registry.clone().ok_or_else(ApiError::unavailable)?,
4873            cookie,
4874            now,
4875            idle_seconds(table),
4876            session_end_at,
4877        )
4878        .await;
4879    }
4880    let renewed = RenewedAccessToken {
4881        token_id: extended.token_id().to_owned(),
4882        expires_at: extended.expires_at(),
4883        expires_in: extended.expires_at() - unix_timestamp()?,
4884        ends_at,
4885        idle_ends_at: idle_seconds(table)
4886            .map(|idle| (now + idle).min(ends_at.unwrap_or(f64::INFINITY))),
4887    };
4888    // A browser's renewal keeps its page cookie as long as the sign-in it names.
4889    // A Station's token is no browser's sign-in: its renewal sets no page cookie.
4890    let page_cookie = (headers.contains_key(ORIGIN) && !from_station).then(|| {
4891        let seconds = match extended.sign_in() {
4892            Some(_) => renewed.ends_at.unwrap_or(f64::MAX) - unix_timestamp().unwrap_or(0.0),
4893            None => renewed.expires_in,
4894        };
4895        page_access::set_page_cookie(
4896            &gateway,
4897            extended.sign_in().unwrap_or(extended.token_id()),
4898            seconds,
4899        )
4900    });
4901    let mut response = Json(renewed).into_response();
4902    page_access::append(response.headers_mut(), page_cookie.flatten());
4903    Ok(response)
4904}
4905
4906/// Whether the steps a sign-in was opened with still complete it for `service`, decided as it
4907/// stands now: the policy in force, the person as the directory has them, the address of this
4908/// request. A token a Station issued is not decided; a record with no steps at all is no sign-in
4909/// and holds nothing.
4910async fn still_complete(
4911    gateway: &Gateway,
4912    providers: &AccessProviders,
4913    headers: &HeaderMap,
4914    address: Option<SocketAddr>,
4915    person: &Person,
4916    factors: &[SignInFactor],
4917    service: &str,
4918) -> bool {
4919    if sign_in::from_station(factors) {
4920        return true;
4921    }
4922    if factors.is_empty() {
4923        return false;
4924    }
4925    let context = SignInContext {
4926        done: Gateway::passed(factors),
4927        person: Some(person.clone()),
4928        ..gateway.sign_in_context(
4929            ai6::directorates::m::access::purposes::RESUME,
4930            headers,
4931            address,
4932            service,
4933        )
4934    };
4935    gateway
4936        .decide_sign_in(providers, context)
4937        .await
4938        .is_some_and(|decision| decision.complete)
4939}
4940
4941/// The person a name and a password name, and the ID of the provider that accepted them when it
4942/// has one. Only `offered` providers are asked, in that order; an empty list is every provider,
4943/// in the gateway's own order.
4944async fn authenticate_password(
4945    gateway: &Gateway,
4946    providers: &AccessProviders,
4947    headers: &HeaderMap,
4948    connection: Option<SocketAddr>,
4949    request: LoginRequest,
4950    offered: &[String],
4951) -> Result<(Person, Option<String>), ApiError> {
4952    let asked: Vec<Signer> = if offered.is_empty() {
4953        providers.authenticators.clone()
4954    } else {
4955        offered
4956            .iter()
4957            .filter_map(|id| {
4958                providers
4959                    .authenticators
4960                    .iter()
4961                    .find(|signer| signer.id.as_deref() == Some(id))
4962                    .cloned()
4963            })
4964            .collect()
4965    };
4966    if providers.authenticators.is_empty() {
4967        return Err(ApiError::unauthorized());
4968    }
4969    let login_guard = gateway.login_guard();
4970    let source = login_guard.source(headers, connection);
4971    if let Some(wait) = login_guard.tried(source, &request.name) {
4972        return Err(ApiError::too_many_attempts(wait));
4973    }
4974    let attempt = Attempt {
4975        name: Some(request.name),
4976        secret: Some(request.secret),
4977        peer: Some(source.to_string()),
4978        secure: Some(true),
4979        method: Some("password".to_owned()),
4980        ..Attempt::default()
4981    };
4982    // Each provider answers for what it claims: `Unknown` is "not mine", asked of the next, and
4983    // `Invalid` is "mine, and refused".
4984    let verdict = tokio::task::spawn_blocking(move || {
4985        for signer in asked {
4986            match signer.authenticator.authenticate(attempt.clone())? {
4987                Verdict::Unknown => {}
4988                decided => return Ok((decided, signer.id)),
4989            }
4990        }
4991        Ok((Verdict::Unknown, None))
4992    })
4993    .await
4994    .map_err(|_| ApiError::internal())?
4995    .map_err(|_: ai6::guatiao::library::ProviderError| ApiError::internal())?;
4996    let (Verdict::Valid(lookup), provider) = verdict else {
4997        return Err(ApiError::unauthorized());
4998    };
4999    let directory = providers.directory.clone();
5000    let person = tokio::task::spawn_blocking(move || directory.lookup(lookup))
5001        .await
5002        .map_err(|_| ApiError::internal())?
5003        .map_err(|_| ApiError::internal())?
5004        .ok_or_else(ApiError::unauthorized)?;
5005    Ok((person, provider))
5006}
5007
5008async fn issue_access_token_record(
5009    registry: Arc<dyn RegistryBackend>,
5010    person_id: String,
5011    ttl: Duration,
5012    session_max: TimeLimit,
5013) -> Result<IssuedAccessToken, ApiError> {
5014    let issued_at = unix_timestamp()?;
5015    // The record says a Station issued it: no sign-in made it, and none is decided again.
5016    let issuer = SignInFactor::try_new(sign_in::STATION, None, Some(person_id.clone()))
5017        .map_err(|_| ApiError::internal())?;
5018    store_bearer(
5019        registry,
5020        person_id,
5021        Times {
5022            issued_at,
5023            expires_at: issued_at + ttl.as_secs_f64(),
5024            now: issued_at,
5025            idle: None,
5026        },
5027        session_max,
5028        None,
5029        vec![issuer],
5030    )
5031    .await
5032}
5033
5034/// A bearer token's times. A resumed token's `issued_at` is the sign-in's, which is what keeps
5035/// its renewals within `session_max` of that sign-in.
5036struct Times {
5037    issued_at: f64,
5038    expires_at: f64,
5039    now: f64,
5040    /// Seconds the sign-in may go idle from `now`; `None` with no limit.
5041    idle: Option<f64>,
5042}
5043
5044/// A new secret. Two independent UUIDs provide 256 random bits without a separate token crate.
5045fn new_secret() -> String {
5046    format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple())
5047}
5048
5049/// Stores a new bearer token, of the sign-in holding the session cookie `sign_in` when one is
5050/// named.
5051async fn store_bearer(
5052    registry: Arc<dyn RegistryBackend>,
5053    person_id: String,
5054    times: Times,
5055    session_max: TimeLimit,
5056    sign_in: Option<String>,
5057    factors: Vec<SignInFactor>,
5058) -> Result<IssuedAccessToken, ApiError> {
5059    let Times {
5060        issued_at,
5061        expires_at,
5062        now,
5063        idle,
5064    } = times;
5065    let token_id = Uuid::new_v4().to_string();
5066    let token = new_secret();
5067    let digest = access_token_digest(&token);
5068    let mut record = AccessTokenRecord::try_new(
5069        token_id.clone(),
5070        digest,
5071        person_id,
5072        issued_at,
5073        expires_at,
5074        None,
5075    )
5076    .map_err(|_| ApiError::bad_request())?
5077    .with_factors(factors);
5078    if let Some(sign_in) = sign_in {
5079        record = record
5080            .in_sign_in(sign_in)
5081            .map_err(|_| ApiError::internal())?;
5082    }
5083    tokio::task::spawn_blocking(move || registry.store_access_token(&record))
5084        .await
5085        .map_err(|_| ApiError::internal())?
5086        .map_err(|_| ApiError::internal())?;
5087    Ok(IssuedAccessToken {
5088        token_id,
5089        token,
5090        expires_at,
5091        expires_in: expires_at - now,
5092        ends_at: session_end(issued_at, expires_at, session_max),
5093        idle_ends_at: idle.map(|idle| {
5094            (now + idle)
5095                .min(session_end(issued_at, expires_at, session_max).unwrap_or(f64::INFINITY))
5096        }),
5097    })
5098}
5099
5100/// A session cookie just stored: its record's ID and the header that hands it to the browser.
5101struct NewSessionCookie {
5102    sign_in: String,
5103    header: HeaderValue,
5104}
5105
5106/// Whether a browser's sign-in gets a session cookie: with renewal off the sign-in ends with its
5107/// first token, and there is nothing to come back to.
5108fn session_cookies_on(table: &ai6::UnexGatewayLimits) -> bool {
5109    table.session_cookie && table.session_max.get() != Some(Duration::ZERO)
5110}
5111
5112/// Moves a sign-in's session cookie on to `idle` seconds from `now`, and never past `ends`: the
5113/// cookie stands while the sign-in is used, and a failure to write that down is not the
5114/// request's.
5115async fn keep_cookie(
5116    registry: Arc<dyn RegistryBackend>,
5117    cookie: &str,
5118    now: f64,
5119    idle: Option<f64>,
5120    ends: f64,
5121) {
5122    let until = idle.map_or(ends, |idle| (now + idle).min(ends));
5123    let until = if until.is_finite() { until } else { f64::MAX };
5124    let cookie = cookie.to_owned();
5125    let _ = tokio::task::spawn_blocking(move || registry.extend_access_token(&cookie, until)).await;
5126}
5127
5128/// Stores a sign-in's session cookie, which ends `session_max` after `issued_at` and never
5129/// later, and `idle` seconds after `issued_at` unless the sign-in is renewed.
5130async fn store_session_cookie(
5131    registry: Arc<dyn RegistryBackend>,
5132    person_id: &str,
5133    issued_at: f64,
5134    session_max: TimeLimit,
5135    idle: Option<f64>,
5136    factors: Vec<SignInFactor>,
5137) -> Result<NewSessionCookie, ApiError> {
5138    let lifetime = session_max.as_secs_f64();
5139    // No bound leaves nothing to write down but the largest time there is. Past about a year a
5140    // browser keeps a cookie only as long as it chooses, whatever Max-Age says.
5141    let ends = if lifetime.is_finite() {
5142        issued_at + lifetime
5143    } else {
5144        f64::MAX
5145    };
5146    let expires_at = idle.map_or(ends, |idle| (issued_at + idle).min(ends));
5147    let max_age = lifetime.ceil().min(f64::from(u32::MAX)) as u64;
5148    let value = new_secret();
5149    let sign_in = Uuid::new_v4().to_string();
5150    let record = AccessTokenRecord::try_new(
5151        sign_in.clone(),
5152        session_cookie_digest(&value),
5153        person_id,
5154        issued_at,
5155        expires_at,
5156        None,
5157    )
5158    .map_err(|_| ApiError::bad_request())?
5159    .with_factors(factors)
5160    .into_session_cookie();
5161    tokio::task::spawn_blocking(move || registry.store_access_token(&record))
5162        .await
5163        .map_err(|_| ApiError::internal())?
5164        .map_err(|_| ApiError::internal())?;
5165    Ok(NewSessionCookie {
5166        sign_in,
5167        header: session_cookie_header(&value, max_age)?,
5168    })
5169}
5170
5171async fn resolve_user(gateway: &Gateway, token: &str) -> Result<Person, ApiError> {
5172    let person = resolve_user_unnoted(gateway, token).await?;
5173    principals::note(gateway, &person);
5174    Ok(person)
5175}
5176
5177async fn resolve_user_unnoted(gateway: &Gateway, token: &str) -> Result<Person, ApiError> {
5178    match resolve_digest(gateway, access_token_digest(token)).await {
5179        // Not a sign-in's token: a key provider may claim it as a key.
5180        Err(error)
5181            if error.status == StatusCode::UNAUTHORIZED
5182                && gateway
5183                    .access
5184                    .as_ref()
5185                    .is_some_and(|access| access.keys.is_some()) =>
5186        {
5187            keys::resolve(gateway, token)
5188                .await?
5189                .ok_or_else(ApiError::unauthorized)
5190        }
5191        other => other,
5192    }
5193}
5194
5195/// [`resolve_user`] for what a key may not do for its person: it needs the person's own
5196/// sign-in, not a key narrowed to some of their grants.
5197async fn resolve_signed_in(gateway: &Gateway, token: &str) -> Result<Person, ApiError> {
5198    let person = resolve_user(gateway, token).await?;
5199    if ai6::is_key_narrowed(&person) || ai6::key_id(&person).is_some() {
5200        return Err(ApiError::refused(
5201            StatusCode::FORBIDDEN,
5202            "an API key cannot do this; sign in with a password or a sign-in token".to_owned(),
5203        ));
5204    }
5205    Ok(person)
5206}
5207
5208/// Who an audit record names as acting: the person, and the key when they acted through one.
5209pub(crate) fn actor_of(person: &Person) -> String {
5210    match ai6::key_id(person) {
5211        Some(key) => format!("{} via key {key}", person.id),
5212        None => person.id.clone(),
5213    }
5214}
5215
5216/// The person whose access token, or live [`StandIn`], has the digest `digest`.
5217async fn resolve_digest(gateway: &Gateway, digest: String) -> Result<Person, ApiError> {
5218    let standing_in = gateway
5219        .stand_ins
5220        .lock()
5221        .unwrap_or_else(std::sync::PoisonError::into_inner)
5222        .get(&digest)
5223        .cloned();
5224    let person_id = match standing_in {
5225        Some(person_id) => person_id,
5226        None => {
5227            let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5228            tokio::task::spawn_blocking(move || registry.find_access_token(&digest))
5229                .await
5230                .map_err(|_| ApiError::internal())?
5231                .map_err(|_| ApiError::internal())?
5232                .ok_or_else(ApiError::unauthorized)?
5233                .person_id()
5234                .to_owned()
5235        }
5236    };
5237    person_by_id(gateway, person_id).await
5238}
5239
5240/// The person with ID `person_id` in the directory, now.
5241async fn person_by_id(gateway: &Gateway, person_id: String) -> Result<Person, ApiError> {
5242    let directory = gateway
5243        .access
5244        .as_ref()
5245        .ok_or_else(ApiError::unavailable)?
5246        .directory
5247        .clone();
5248    let mut person = tokio::task::spawn_blocking(move || {
5249        directory.lookup(Lookup {
5250            by: "id".to_owned(),
5251            value: person_id,
5252            ..Default::default()
5253        })
5254    })
5255    .await
5256    .map_err(|_| ApiError::internal())?
5257    .map_err(|_| ApiError::internal())?
5258    .ok_or_else(ApiError::unauthorized)?;
5259    // Only a key's own sign-in narrows a person; a directory's attribute of that name does not.
5260    ai6::clear_key(&mut person);
5261    Ok(person)
5262}
5263
5264async fn issue_user_attach_token(
5265    State(gateway): State<Gateway>,
5266    headers: HeaderMap,
5267    Json(request): Json<GrantRequest>,
5268) -> Result<Json<TokenResponse>, ApiError> {
5269    let person = resolve_user(&gateway, bearer(&headers)?).await?;
5270    let mode = match request.mode.as_str() {
5271        "read" => AttachMode::Read,
5272        "write" => AttachMode::Write,
5273        _ => return Err(ApiError::bad_request()),
5274    };
5275    let grant = AttachGrant {
5276        operation_id: OperationId::new(request.operation_id)
5277            .map_err(|_| ApiError::bad_request())?,
5278        mission_id: MissionId::new(request.mission_id).map_err(|_| ApiError::bad_request())?,
5279        run_id: RunId::new(request.run_id).map_err(|_| ApiError::bad_request())?,
5280        mode,
5281    };
5282    authorize_attachment(&gateway, person, &grant).await?;
5283    Ok(Json(TokenResponse {
5284        token: gateway.store_attach_token(grant).await?,
5285    }))
5286}
5287
5288async fn authorize_attachment(
5289    gateway: &Gateway,
5290    person: Person,
5291    grant: &AttachGrant,
5292) -> Result<(), ApiError> {
5293    let run = gateway
5294        .inner
5295        .lock()
5296        .await
5297        .runs
5298        .get(&grant.run_id)
5299        .map(|record| (record.operation_id.clone(), record.mission_id.clone()))
5300        .ok_or_else(|| ApiError::from(GatewayError::NotFound))?;
5301    if run != (grant.operation_id.clone(), grant.mission_id.clone()) {
5302        return Err(ApiError::forbidden());
5303    }
5304    let providers = gateway.access.clone().ok_or_else(ApiError::unavailable)?;
5305    let action = match grant.mode {
5306        AttachMode::Read => "run.read",
5307        AttachMode::Write => "run.input",
5308    };
5309    let request = operation_request(
5310        person,
5311        action,
5312        grant.operation_id.as_str(),
5313        &operation_tree(gateway).await?,
5314    );
5315    let decision = tokio::task::spawn_blocking(move || providers.authorizer.authorize(request))
5316        .await
5317        .map_err(|_| ApiError::internal())?
5318        .map_err(|_| ApiError::internal())?;
5319    if !decision.allowed {
5320        return Err(ApiError::forbidden());
5321    }
5322    Ok(())
5323}
5324
5325async fn access_session(
5326    State(gateway): State<Gateway>,
5327    headers: HeaderMap,
5328) -> Result<Json<AccessSession>, ApiError> {
5329    let registry = gateway.registry.clone().ok_or_else(ApiError::internal)?;
5330    let token = bearer(&headers)?;
5331    let digest = access_token_digest(token);
5332    let record = tokio::task::spawn_blocking(move || registry.find_access_token(&digest))
5333        .await
5334        .map_err(|_| ApiError::internal())?
5335        .map_err(|_| ApiError::internal())?
5336        .ok_or_else(ApiError::unauthorized)?;
5337    Ok(Json(AccessSession {
5338        token_id: record.token_id().to_owned(),
5339        person_id: record.person_id().to_owned(),
5340        expires_at: record.expires_at(),
5341    }))
5342}
5343
5344async fn user_profile(
5345    State(gateway): State<Gateway>,
5346    headers: HeaderMap,
5347) -> Result<Json<UserProfile>, ApiError> {
5348    let token = bearer(&headers)?;
5349    let person = resolve_user(&gateway, token).await?;
5350    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5351    let digest = access_token_digest(token);
5352    let record = tokio::task::spawn_blocking(move || registry.find_access_token(&digest))
5353        .await
5354        .map_err(|_| ApiError::internal())?
5355        .map_err(|_| ApiError::internal())?
5356        .ok_or_else(ApiError::unauthorized)?;
5357    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5358    let station_records = tokio::task::spawn_blocking(move || registry.stations(Duration::MAX))
5359        .await
5360        .map_err(|_| ApiError::internal())?
5361        .map_err(|_| ApiError::internal())?;
5362    let authorization_person = person.clone();
5363    let tree = OperationTree::from_check_ins(&station_records);
5364    observe_tree(&gateway, &tree);
5365    // The profile says what could be read and reads nothing.
5366    let authorizer = gateway.probing_authorizer()?;
5367    let (operations, stations, roster, config, global_actions, reports) =
5368        tokio::task::spawn_blocking(move || {
5369            let mut operation_ids: BTreeSet<String> =
5370                tree.operations().map(str::to_owned).collect();
5371            let mut stations = Vec::new();
5372            for station in &station_records {
5373                let station_id = station.station().to_owned();
5374                let mut actions = Vec::new();
5375                for &action in ai6::STATION_ACTIONS {
5376                    let allowed = authorizer
5377                        .authorize(AuthorizationRequest {
5378                            person: authorization_person.clone(),
5379                            action: action.to_owned(),
5380                            resource: format!("station:{station_id}"),
5381                            ancestors: Vec::new(),
5382                        })
5383                        .map_err(|_| ApiError::internal())?
5384                        .allowed;
5385                    if allowed {
5386                        actions.push(action.to_owned());
5387                    }
5388                }
5389                if !actions.is_empty() {
5390                    stations.push(UserStationAccess {
5391                        station_id,
5392                        actions,
5393                    });
5394                }
5395                for operation in &station.check_in().common.operations {
5396                    if let Ok(operation_id) = OperationId::new(operation.clone()) {
5397                        operation_ids.insert(operation_id.to_string());
5398                    }
5399                }
5400            }
5401            let mut operations = Vec::new();
5402            for operation_id in operation_ids {
5403                let mut actions = Vec::new();
5404                for &action in ai6::OPERATION_ACTIONS {
5405                    let allowed = authorizer
5406                        .authorize(operation_request(
5407                            authorization_person.clone(),
5408                            action,
5409                            &operation_id,
5410                            &tree,
5411                        ))
5412                        .map_err(|_| ApiError::internal())?
5413                        .allowed;
5414                    if allowed {
5415                        actions.push(action.to_owned());
5416                    }
5417                }
5418                let compartments: Vec<String> = authorizer
5419                    .compiled()
5420                    .map(|compiled| {
5421                        compiled
5422                            .person_compartments(&authorization_person, &operation_id)
5423                            .into_iter()
5424                            .map(str::to_owned)
5425                            .collect()
5426                    })
5427                    .unwrap_or_default();
5428                if !actions.is_empty() {
5429                    operations.push(UserOperationAccess {
5430                        name: tree.name(&operation_id),
5431                        operation_id,
5432                        parent: None,
5433                        actions,
5434                        compartments,
5435                    });
5436                }
5437            }
5438            // An ancestor is named only when the person may read its Missions.
5439            let readable: BTreeSet<String> = operations
5440                .iter()
5441                .filter(|access| access.actions.iter().any(|action| action == "mission.read"))
5442                .map(|access| access.operation_id.clone())
5443                .collect();
5444            for access in &mut operations {
5445                access.parent =
5446                    tree.visible_parent(&access.operation_id, |id| readable.contains(id));
5447            }
5448            stations.sort_by(|left, right| left.station_id.cmp(&right.station_id));
5449            let mut roster = Vec::new();
5450            for action in ["roster.read", "roster.manage", "audit.read"] {
5451                let allowed = authorizer
5452                    .authorize(AuthorizationRequest {
5453                        person: authorization_person.clone(),
5454                        action: action.to_owned(),
5455                        resource: roster::ROSTER_RESOURCE.to_owned(),
5456                        ancestors: Vec::new(),
5457                    })
5458                    .map_err(|_| ApiError::internal())?
5459                    .allowed;
5460                if allowed {
5461                    roster.push(action.to_owned());
5462                }
5463            }
5464            let mut config: BTreeMap<String, Vec<String>> = BTreeMap::new();
5465            for (kind, record) in roster::CONFIG_KINDS {
5466                for action in ["config.read", "config.manage"] {
5467                    let allowed = authorizer
5468                        .authorize(AuthorizationRequest {
5469                            person: authorization_person.clone(),
5470                            action: action.to_owned(),
5471                            resource: format!("config:{}", record.name()),
5472                            ancestors: Vec::new(),
5473                        })
5474                        .map_err(|_| ApiError::internal())?
5475                        .allowed;
5476                    // Changing the plugin family also takes plugin.manage.
5477                    let allowed = allowed
5478                        && (record != ai6::ConfigRecord::Plugin
5479                            || action != "config.manage"
5480                            || authorizer
5481                                .authorize(AuthorizationRequest {
5482                                    person: authorization_person.clone(),
5483                                    action: "plugin.manage".to_owned(),
5484                                    resource: libraries::RESOURCE.to_owned(),
5485                                    ancestors: Vec::new(),
5486                                })
5487                                .map_err(|_| ApiError::internal())?
5488                                .allowed);
5489                    if allowed {
5490                        config
5491                            .entry(kind.to_owned())
5492                            .or_default()
5493                            .push(action.to_owned());
5494                    }
5495                }
5496            }
5497            let mut global_actions = Vec::new();
5498            for (action, resource) in [
5499                ("access.read", ai6::CONFIG_ACCESS),
5500                ("access.manage", ai6::CONFIG_ACCESS),
5501                ("account.manage", ai6::CONFIG_ACCOUNTS),
5502                ("assistant.memory.admin", "config:assistant"),
5503                ("assistant.own_agent", "config:assistant"),
5504                ("compartment.manage", "compartment:*"),
5505                ("memory.write", "config:memory"),
5506                ("plugin.manage", "config:plugin"),
5507            ] {
5508                let allowed = authorizer
5509                    .authorize(AuthorizationRequest {
5510                        person: authorization_person.clone(),
5511                        action: action.to_owned(),
5512                        resource: resource.to_owned(),
5513                        ancestors: Vec::new(),
5514                    })
5515                    .map_err(|_| ApiError::internal())?
5516                    .allowed;
5517                if allowed {
5518                    global_actions.push(action.to_owned());
5519                }
5520            }
5521            // M's own Reports: `station.read` reads them, `station.configure` assesses them.
5522            let mut reports = Vec::new();
5523            for action in ["station.read", "station.configure"] {
5524                let allowed = authorizer
5525                    .authorize(AuthorizationRequest {
5526                        person: authorization_person.clone(),
5527                        action: action.to_owned(),
5528                        resource: reports::M_RESOURCE.to_owned(),
5529                        ancestors: Vec::new(),
5530                    })
5531                    .map_err(|_| ApiError::internal())?
5532                    .allowed;
5533                if allowed {
5534                    reports.push(action.to_owned());
5535                }
5536            }
5537            Ok::<_, ApiError>((
5538                operations,
5539                stations,
5540                roster,
5541                config,
5542                global_actions,
5543                reports,
5544            ))
5545        })
5546        .await
5547        .map_err(|_| ApiError::internal())??;
5548    Ok(Json(UserProfile {
5549        display_name: principals::shown_name(&person),
5550        initials: principals::shown_initials(&person),
5551        person_id: person.id,
5552        name: person.name,
5553        groups: person.groups,
5554        expires_at: record.expires_at(),
5555        operations,
5556        stations,
5557        roster,
5558        config,
5559        global_actions,
5560        reports,
5561        moneypenny: gateway.assistant().is_some(),
5562    }))
5563}
5564
5565async fn authorize_operation_action(
5566    gateway: &Gateway,
5567    person: Person,
5568    operation_id: &OperationId,
5569    action: &'static str,
5570) -> Result<(), ApiError> {
5571    authorize_resource_action(
5572        gateway,
5573        person,
5574        tree::operation_resource(operation_id.as_str()),
5575        action,
5576    )
5577    .await
5578}
5579
5580/// The tree of Operations from the Stations' latest check-ins; empty without a Registry.
5581async fn operation_tree(gateway: &Gateway) -> Result<OperationTree, ApiError> {
5582    let Some(registry) = gateway.registry.clone() else {
5583        return Ok(OperationTree::default());
5584    };
5585    let tree = tokio::task::spawn_blocking(move || registry.stations(Duration::MAX))
5586        .await
5587        .map_err(|_| ApiError::internal())?
5588        .map(|records| OperationTree::from_check_ins(&records))
5589        .map_err(|_| ApiError::internal())?;
5590    observe_tree(gateway, &tree);
5591    Ok(tree)
5592}
5593
5594/// Every Operation the gateway knows of: from the Stations' check-ins and its roster.
5595async fn known_operations(gateway: &Gateway) -> Vec<String> {
5596    let mut known: BTreeSet<String> = BTreeSet::new();
5597    if let Ok(tree) = operation_tree(gateway).await {
5598        known.extend(tree.operations().map(str::to_owned));
5599    }
5600    if let Some(registry) = gateway.registry.clone()
5601        && let Ok(Ok(stations)) =
5602            tokio::task::spawn_blocking(move || registry.stations(Duration::MAX)).await
5603    {
5604        for station in stations {
5605            known.extend(station.into_check_in().common.operations);
5606        }
5607    }
5608    if let Some(source) = gateway.roster.clone()
5609        && let Ok(Ok(definitions)) = tokio::task::spawn_blocking(move || {
5610            source.definitions(ai6::ConfigRecord::Operation, &ai6::ConfigScope::Global)
5611        })
5612        .await
5613    {
5614        known.extend(definitions.records.into_iter().map(|(id, _)| id));
5615    }
5616    known.into_iter().collect()
5617}
5618
5619/// Tells the access policy the tree the Stations last published, so Operation policies are
5620/// checked against it.
5621fn observe_tree(gateway: &Gateway, tree: &OperationTree) {
5622    if let Some(access) = &gateway.access_admin {
5623        access.observe_lineage(access_admin::tree_lineage(tree));
5624    }
5625}
5626
5627async fn authorize_resource_action(
5628    gateway: &Gateway,
5629    person: Person,
5630    resource: String,
5631    action: &'static str,
5632) -> Result<(), ApiError> {
5633    if resource_action_allowed(gateway, person, resource, action).await? {
5634        Ok(())
5635    } else {
5636        Err(ApiError::forbidden())
5637    }
5638}
5639
5640/// Whether `person` holds `action` on `resource`, for what a view only shows to who does.
5641async fn resource_action_allowed(
5642    gateway: &Gateway,
5643    person: Person,
5644    resource: String,
5645    action: &'static str,
5646) -> Result<bool, ApiError> {
5647    let authorizer = gateway.authorizer()?;
5648    let request = resource_request(person, action, resource, &operation_tree(gateway).await?);
5649    let decision = tokio::task::spawn_blocking(move || authorizer.authorize(request))
5650        .await
5651        .map_err(|_| ApiError::internal())?
5652        .map_err(|_| ApiError::internal())?;
5653    Ok(decision.allowed)
5654}
5655
5656async fn ensure_station_registered(
5657    registry: &Arc<dyn RegistryBackend>,
5658    station_id: &str,
5659) -> Result<ai6::StationRecord, ApiError> {
5660    let registry = registry.clone();
5661    let station_id = station_id.to_owned();
5662    tokio::task::spawn_blocking(move || {
5663        registry
5664            .stations(Duration::MAX)
5665            .map_err(|_| ApiError::internal())?
5666            .into_iter()
5667            .find(|station| station.station() == station_id)
5668            .ok_or_else(|| ApiError::from(GatewayError::NotFound))
5669    })
5670    .await
5671    .map_err(|_| ApiError::internal())?
5672}
5673
5674async fn get_user_station_settings(
5675    State(gateway): State<Gateway>,
5676    headers: HeaderMap,
5677    Path(station_id): Path<String>,
5678) -> Result<Json<StationSettingsResponse>, ApiError> {
5679    let person = resolve_user(&gateway, bearer(&headers)?).await?;
5680    StationSettings::try_new(station_id.clone(), 1).map_err(|_| ApiError::bad_request())?;
5681    authorize_resource_action(
5682        &gateway,
5683        person,
5684        format!("station:{station_id}"),
5685        "station.read",
5686    )
5687    .await?;
5688    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5689    let station = ensure_station_registered(&registry, &station_id).await?;
5690    let execution_enabled = station
5691        .check_in()
5692        .common
5693        .roles
5694        .iter()
5695        .any(|role| role == "execution");
5696    let station_key = station_id.clone();
5697    let registry = registry.clone();
5698    let settings = tokio::task::spawn_blocking(move || registry.station_settings(&station_key))
5699        .await
5700        .map_err(|_| ApiError::internal())?
5701        .map_err(|_| ApiError::internal())?;
5702    let (max_concurrent_missions, limits, configured) = match settings {
5703        Some(settings) => (
5704            settings.max_concurrent_missions(),
5705            settings.resource_limits(),
5706            true,
5707        ),
5708        None => (
5709            station.check_in().common.capacity,
5710            ai6::ResourceLimits::default(),
5711            false,
5712        ),
5713    };
5714    Ok(Json(StationSettingsResponse {
5715        station_id,
5716        max_concurrent_missions,
5717        min_free_memory_mb: limits.min_free_memory_mb,
5718        max_cpu_percent: limits.max_cpu_percent,
5719        configured,
5720        execution_enabled,
5721    }))
5722}
5723
5724async fn put_user_station_settings(
5725    State(gateway): State<Gateway>,
5726    headers: HeaderMap,
5727    Path(station_id): Path<String>,
5728    Json(request): Json<UpdateStationSettings>,
5729) -> Result<StatusCode, ApiError> {
5730    let person = resolve_user(&gateway, bearer(&headers)?).await?;
5731    let settings = StationSettings::try_new(station_id.clone(), request.max_concurrent_missions)
5732        .map_err(|_| ApiError::bad_request())?;
5733    authorize_resource_action(
5734        &gateway,
5735        person.clone(),
5736        format!("station:{station_id}"),
5737        "station.configure",
5738    )
5739    .await?;
5740    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5741    let station = ensure_station_registered(&registry, &station_id).await?;
5742    let execution_enabled = station
5743        .check_in()
5744        .common
5745        .roles
5746        .iter()
5747        .any(|role| role == "execution");
5748    if !execution_enabled {
5749        return Err(ApiError::from(GatewayError::Conflict));
5750    }
5751    let station = station_id.clone();
5752    let write_registry = registry.clone();
5753    let mut changed = vec!["max_concurrent_missions"];
5754    if request.min_free_memory_mb.is_some() {
5755        changed.push("min_free_memory_mb");
5756    }
5757    if request.max_cpu_percent.is_some() {
5758        changed.push("max_cpu_percent");
5759    }
5760    tokio::task::spawn_blocking(move || {
5761        let current = write_registry
5762            .station_settings(&station)?
5763            .map(|settings| settings.resource_limits())
5764            .unwrap_or_default();
5765        let limits = ai6::ResourceLimits::new(
5766            request
5767                .min_free_memory_mb
5768                .unwrap_or(current.min_free_memory_mb),
5769            request.max_cpu_percent.unwrap_or(current.max_cpu_percent),
5770        );
5771        write_registry.set_station_settings(&station, &settings.with_resource_limits(limits)?)
5772    })
5773    .await
5774    .map_err(|_| ApiError::internal())?
5775    .map_err(|_| ApiError::bad_request())?;
5776    let audit = AuditRecord {
5777        id: Uuid::new_v4().to_string(),
5778        actor: crate::actor_of(&person),
5779        action: "station.settings.update".to_owned(),
5780        operation: String::new(),
5781        resource: Some(format!("station:{station_id}")),
5782        target: changed.join(", "),
5783        at: unix_timestamp()?,
5784    };
5785    tokio::task::spawn_blocking(move || registry.record_audit(&audit))
5786        .await
5787        .map_err(|_| ApiError::internal())?
5788        .map_err(|_| ApiError::internal())?;
5789    Ok(StatusCode::NO_CONTENT)
5790}
5791
5792/// Refuses an Operation no Station lists, as a checkout (`operations`) or as one it may place
5793/// Missions of (`runnable_operations`, which covers Operations on a remote Theater).
5794async fn ensure_operation_registered(
5795    registry: &Arc<dyn RegistryBackend>,
5796    operation_id: &OperationId,
5797) -> Result<(), ApiError> {
5798    let registry = registry.clone();
5799    let operation_id = operation_id.to_string();
5800    let registered = tokio::task::spawn_blocking(move || {
5801        registry
5802            .stations(Duration::MAX)
5803            .map(|stations| {
5804                stations.iter().any(|station| {
5805                    let common = &station.check_in().common;
5806                    common.operations.contains(&operation_id)
5807                        || common.runnable_operations.contains(&operation_id)
5808                })
5809            })
5810            .map_err(|_| ApiError::internal())
5811    })
5812    .await
5813    .map_err(|_| ApiError::internal())??;
5814    if registered {
5815        Ok(())
5816    } else {
5817        Err(ApiError::from(GatewayError::NotFound))
5818    }
5819}
5820
5821async fn list_user_agent_roles(
5822    State(gateway): State<Gateway>,
5823    headers: HeaderMap,
5824    Path(operation_id): Path<String>,
5825) -> Result<Json<Vec<AgentRoleResponse>>, ApiError> {
5826    let person = resolve_user(&gateway, bearer(&headers)?).await?;
5827    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
5828    authorize_operation_action(&gateway, person, &operation_id, "agent.read").await?;
5829    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5830    ensure_operation_registered(&registry, &operation_id).await?;
5831    let operation = operation_id.to_string();
5832    let roles = tokio::task::spawn_blocking(move || {
5833        let mut roles = BTreeMap::new();
5834        let headquarters = registry.headquarters().map_err(|_| ApiError::internal())?;
5835        if let Some(headquarters) = headquarters {
5836            let stations = registry
5837                .stations(Duration::MAX)
5838                .map_err(|_| ApiError::internal())?;
5839            if let Some(station) = stations
5840                .iter()
5841                .find(|station| station.station() == headquarters.station())
5842            {
5843                for role in station.check_in().agent_roles.iter().flatten() {
5844                    if role.validate().is_ok() {
5845                        roles.insert(role.id.clone(), (role.clone(), false));
5846                    }
5847                }
5848            }
5849        }
5850        for role in registry
5851            .list_agent_roles(&operation)
5852            .map_err(|_| ApiError::internal())?
5853        {
5854            roles.insert(role.id.clone(), (role, true));
5855        }
5856        Ok::<_, ApiError>(
5857            roles
5858                .into_values()
5859                .map(|(role, operation_override)| AgentRoleResponse {
5860                    role,
5861                    operation_override,
5862                })
5863                .collect::<Vec<_>>(),
5864        )
5865    })
5866    .await
5867    .map_err(|_| ApiError::internal())??;
5868    Ok(Json(roles))
5869}
5870
5871async fn user_agent_role_form(
5872    State(gateway): State<Gateway>,
5873    headers: HeaderMap,
5874    Path(operation_id): Path<String>,
5875) -> Result<Json<ai6::RecordForm>, ApiError> {
5876    let person = resolve_user(&gateway, bearer(&headers)?).await?;
5877    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
5878    authorize_operation_action(&gateway, person, &operation_id, "agent.configure").await?;
5879    let registry = gateway
5880        .registry
5881        .as_ref()
5882        .ok_or_else(ApiError::unavailable)?;
5883    ensure_operation_registered(registry, &operation_id).await?;
5884    ai6::directorates::m::records::EditorForm::AgentRole
5885        .form()
5886        .map(Json)
5887        .map_err(|_| ApiError::internal())
5888}
5889
5890async fn put_user_agent_role(
5891    State(gateway): State<Gateway>,
5892    headers: HeaderMap,
5893    Path((operation_id, role_id)): Path<(String, String)>,
5894    Json(role): Json<AgentRole>,
5895) -> Result<StatusCode, ApiError> {
5896    let person = resolve_user(&gateway, bearer(&headers)?).await?;
5897    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
5898    if role.id != role_id || role.validate().is_err() {
5899        return Err(ApiError::bad_request());
5900    }
5901    authorize_operation_action(&gateway, person.clone(), &operation_id, "agent.configure").await?;
5902    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5903    ensure_operation_registered(&registry, &operation_id).await?;
5904    let operation = operation_id.to_string();
5905    let audit = AuditRecord {
5906        id: Uuid::new_v4().to_string(),
5907        actor: crate::actor_of(&person),
5908        action: "agent.role.update".to_owned(),
5909        operation: operation.clone(),
5910        resource: None,
5911        target: role.id.clone(),
5912        at: unix_timestamp()?,
5913    };
5914    tokio::task::spawn_blocking(move || registry.put_agent_role(&operation, &role))
5915        .await
5916        .map_err(|_| ApiError::internal())?
5917        .map_err(|_| ApiError::bad_request())?;
5918    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5919    tokio::task::spawn_blocking(move || registry.record_audit(&audit))
5920        .await
5921        .map_err(|_| ApiError::internal())?
5922        .map_err(|_| ApiError::internal())?;
5923    Ok(StatusCode::NO_CONTENT)
5924}
5925
5926async fn delete_user_agent_role(
5927    State(gateway): State<Gateway>,
5928    headers: HeaderMap,
5929    Path((operation_id, role_id)): Path<(String, String)>,
5930) -> Result<StatusCode, ApiError> {
5931    let person = resolve_user(&gateway, bearer(&headers)?).await?;
5932    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
5933    if role_id.is_empty()
5934        || role_id.len() > 128
5935        || !role_id
5936            .bytes()
5937            .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
5938    {
5939        return Err(ApiError::bad_request());
5940    }
5941    authorize_operation_action(&gateway, person.clone(), &operation_id, "agent.configure").await?;
5942    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5943    ensure_operation_registered(&registry, &operation_id).await?;
5944    let operation = operation_id.to_string();
5945    let role = role_id.clone();
5946    let removed =
5947        tokio::task::spawn_blocking(move || registry.remove_agent_role(&operation, &role))
5948            .await
5949            .map_err(|_| ApiError::internal())?
5950            .map_err(|_| ApiError::internal())?;
5951    if !removed {
5952        return Err(ApiError::from(GatewayError::NotFound));
5953    }
5954    let audit = AuditRecord {
5955        id: Uuid::new_v4().to_string(),
5956        actor: crate::actor_of(&person),
5957        action: "agent.role.remove".to_owned(),
5958        operation: operation_id.to_string(),
5959        resource: None,
5960        target: role_id,
5961        at: unix_timestamp()?,
5962    };
5963    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5964    tokio::task::spawn_blocking(move || registry.record_audit(&audit))
5965        .await
5966        .map_err(|_| ApiError::internal())?
5967        .map_err(|_| ApiError::internal())?;
5968    Ok(StatusCode::NO_CONTENT)
5969}
5970
5971#[derive(Deserialize)]
5972#[serde(deny_unknown_fields)]
5973struct QuarantineRequest {
5974    reason: String,
5975}
5976
5977fn valid_agent_id(agent_id: &str) -> bool {
5978    !agent_id.is_empty()
5979        && agent_id.len() <= 128
5980        && agent_id
5981            .bytes()
5982            .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
5983}
5984
5985async fn list_user_quarantines(
5986    State(gateway): State<Gateway>,
5987    headers: HeaderMap,
5988    Path(operation_id): Path<String>,
5989) -> Result<Json<Vec<Quarantine>>, ApiError> {
5990    let person = resolve_user(&gateway, bearer(&headers)?).await?;
5991    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
5992    authorize_operation_action(&gateway, person, &operation_id, "agent.read").await?;
5993    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
5994    let operation = operation_id.to_string();
5995    let records = tokio::task::spawn_blocking(move || registry.quarantines())
5996        .await
5997        .map_err(|_| ApiError::internal())?
5998        .map_err(|_| ApiError::internal())?;
5999    Ok(Json(
6000        records
6001            .into_iter()
6002            .filter(|record| {
6003                record
6004                    .operation
6005                    .as_deref()
6006                    .is_none_or(|own| own == operation)
6007            })
6008            .collect(),
6009    ))
6010}
6011
6012async fn quarantine_user_agent(
6013    State(gateway): State<Gateway>,
6014    headers: HeaderMap,
6015    Path((operation_id, agent_id)): Path<(String, String)>,
6016    Json(request): Json<QuarantineRequest>,
6017) -> Result<StatusCode, ApiError> {
6018    let person = resolve_user(&gateway, bearer(&headers)?).await?;
6019    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
6020    let reason = request.reason.trim().to_owned();
6021    if !valid_agent_id(&agent_id)
6022        || reason.is_empty()
6023        || reason.chars().count() > 512
6024        || reason.chars().any(char::is_control)
6025    {
6026        return Err(ApiError::bad_request());
6027    }
6028    authorize_operation_action(&gateway, person.clone(), &operation_id, "agent.configure").await?;
6029    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
6030    ensure_operation_registered(&registry, &operation_id).await?;
6031    let at = unix_timestamp()?;
6032    let record = Quarantine::new(
6033        agent_id.clone(),
6034        Some(operation_id.to_string()),
6035        reason,
6036        person.id.clone(),
6037        at,
6038    );
6039    let audit = AuditRecord {
6040        id: Uuid::new_v4().to_string(),
6041        actor: crate::actor_of(&person),
6042        action: "agent.quarantine".to_owned(),
6043        operation: operation_id.to_string(),
6044        resource: None,
6045        target: agent_id,
6046        at,
6047    };
6048    tokio::task::spawn_blocking(move || {
6049        registry.quarantine_agent(&record)?;
6050        registry.record_audit(&audit)
6051    })
6052    .await
6053    .map_err(|_| ApiError::internal())?
6054    .map_err(|_| ApiError::internal())?;
6055    Ok(StatusCode::CREATED)
6056}
6057
6058/// An audit record with the name of the person who acted, when the gateway has seen them sign in.
6059#[derive(Serialize)]
6060struct AuditEntry {
6061    #[serde(flatten)]
6062    record: AuditRecord,
6063    #[serde(skip_serializing_if = "Option::is_none")]
6064    actor_name: Option<String>,
6065}
6066
6067async fn user_audit(
6068    State(gateway): State<Gateway>,
6069    headers: HeaderMap,
6070    Query(query): Query<UserAuditQuery>,
6071) -> Result<Json<Vec<AuditEntry>>, ApiError> {
6072    let person = resolve_user(&gateway, bearer(&headers)?).await?;
6073    let operation_filter = query
6074        .operation_id
6075        .map(OperationId::new)
6076        .transpose()
6077        .map_err(|_| ApiError::bad_request())?
6078        .map(|operation| operation.to_string());
6079    if operation_filter.is_some() && query.station_id.is_some() {
6080        return Err(ApiError::bad_request());
6081    }
6082    let station_filter = query
6083        .station_id
6084        .map(|station_id| {
6085            StationSettings::try_new(station_id.clone(), 1)
6086                .map(|_| station_id)
6087                .map_err(|_| ApiError::bad_request())
6088        })
6089        .transpose()?;
6090    let limit = audit_page(query.limit, &gateway.config.unex().timeline)
6091        .ok_or_else(ApiError::bad_request)?;
6092    let action_filter = match query.action {
6093        Some(prefix) if prefix.is_empty() || prefix.chars().any(char::is_control) => {
6094            return Err(ApiError::bad_request());
6095        }
6096        other => other,
6097    };
6098    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
6099    let authorizer = gateway.authorizer()?;
6100    let tree = operation_tree(&gateway).await?;
6101    if let Some(operation_id) = &operation_filter {
6102        let scoped_authorizer = authorizer.clone();
6103        let request = operation_request(person.clone(), "audit.read", operation_id, &tree);
6104        let allowed = tokio::task::spawn_blocking(move || scoped_authorizer.authorize(request))
6105            .await
6106            .map_err(|_| ApiError::internal())?
6107            .map_err(|_| ApiError::internal())?
6108            .allowed;
6109        if !allowed {
6110            return Err(ApiError::forbidden());
6111        }
6112    } else if let Some(station_id) = &station_filter {
6113        let registry_check = registry.clone();
6114        ensure_station_registered(&registry_check, station_id).await?;
6115        let scoped_authorizer = authorizer.clone();
6116        let scoped_person = person.clone();
6117        let resource = format!("station:{station_id}");
6118        let allowed = tokio::task::spawn_blocking(move || {
6119            scoped_authorizer.authorize(AuthorizationRequest {
6120                person: scoped_person,
6121                action: "audit.read".to_owned(),
6122                resource,
6123                ancestors: Vec::new(),
6124            })
6125        })
6126        .await
6127        .map_err(|_| ApiError::internal())?
6128        .map_err(|_| ApiError::internal())?
6129        .allowed;
6130        if !allowed {
6131            return Err(ApiError::forbidden());
6132        }
6133    }
6134    let entries = tokio::task::spawn_blocking(move || {
6135        let records = registry.list_audit(500).map_err(|_| ApiError::internal())?;
6136        let mut visible = Vec::new();
6137        for record in records {
6138            // Matching is done before the page is cut, so a page holds what was asked for.
6139            if action_filter
6140                .as_deref()
6141                .is_some_and(|prefix| !record.action.starts_with(prefix))
6142            {
6143                continue;
6144            }
6145            // A crossing belongs to both sides: the reader's Operation and what it read.
6146            let crossed = record
6147                .resource
6148                .as_deref()
6149                .and_then(|resource| resource.strip_prefix("operation:"));
6150            if operation_filter.as_ref().is_some_and(|operation_id| {
6151                operation_id != &record.operation && crossed != Some(operation_id.as_str())
6152            }) {
6153                continue;
6154            }
6155            let resource = record
6156                .resource
6157                .clone()
6158                .filter(|resource| !resource.starts_with("mission:"))
6159                .unwrap_or_else(|| tree::operation_resource(&record.operation));
6160            if station_filter
6161                .as_ref()
6162                .is_some_and(|station_id| resource != format!("station:{station_id}"))
6163            {
6164                continue;
6165            }
6166            let allowed = authorizer
6167                .authorize(resource_request(
6168                    person.clone(),
6169                    "audit.read",
6170                    resource,
6171                    &tree,
6172                ))
6173                .map_err(|_| ApiError::internal())?
6174                .allowed
6175                || (crossed.is_some()
6176                    && authorizer
6177                        .authorize(operation_request(
6178                            person.clone(),
6179                            "audit.read",
6180                            &record.operation,
6181                            &tree,
6182                        ))
6183                        .map_err(|_| ApiError::internal())?
6184                        .allowed);
6185            if allowed {
6186                visible.push(record);
6187                if visible.len() == limit {
6188                    break;
6189                }
6190            }
6191        }
6192        Ok::<_, ApiError>(visible)
6193    })
6194    .await
6195    .map_err(|_| ApiError::internal())??;
6196    let people = principals::named(
6197        &gateway,
6198        entries
6199            .iter()
6200            .map(|record| principals::actor_person(&record.actor).to_owned())
6201            .collect(),
6202    )
6203    .await?;
6204    Ok(Json(
6205        entries
6206            .into_iter()
6207            .map(|record| AuditEntry {
6208                actor_name: people
6209                    .get(principals::actor_person(&record.actor))
6210                    .map(|person| person.label().to_owned()),
6211                record,
6212            })
6213            .collect(),
6214    ))
6215}
6216
6217/// `POST /v1/auth/logout`: ends the sign-in of the presented token, of the session cookie when
6218/// the app's own page sends one, or both. The cookie counts by itself because a token can be over
6219/// by then, and signing out must still end what a reload would come back to.
6220async fn logout(State(gateway): State<Gateway>, headers: HeaderMap) -> Result<Response, ApiError> {
6221    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
6222    let cookie = session_cookie(&headers);
6223    let mut ended = false;
6224    if let Some(value) = cookie.filter(|_| require_origin(&gateway, &headers).is_ok()) {
6225        let digest = session_cookie_digest(value);
6226        let found = registry.clone();
6227        let record = tokio::task::spawn_blocking(move || found.find_session_cookie(&digest))
6228            .await
6229            .map_err(|_| ApiError::internal())?
6230            .map_err(|_| ApiError::internal())?;
6231        if let Some(record) = record {
6232            ended |= revoke_token_record(&registry, record).await?;
6233        }
6234    }
6235    if let Ok(token) = bearer(&headers) {
6236        let digest = access_token_digest(token);
6237        let found = registry.clone();
6238        let record = tokio::task::spawn_blocking(move || found.find_access_token(&digest))
6239            .await
6240            .map_err(|_| ApiError::internal())?
6241            .map_err(|_| ApiError::internal())?;
6242        if let Some(record) = record {
6243            ended |= revoke_token_record(&registry, record).await?;
6244        }
6245    }
6246    let mut response = if ended {
6247        StatusCode::NO_CONTENT.into_response()
6248    } else {
6249        ApiError::unauthorized().into_response()
6250    };
6251    if cookie.is_some() {
6252        response.headers_mut().append(SET_COOKIE, ended_cookie()?);
6253    }
6254    // A browser's page cookie named this sign-in, which no longer stands either way.
6255    if headers.contains_key(ORIGIN) {
6256        page_access::append(
6257            response.headers_mut(),
6258            page_access::ended_page_cookie(&gateway),
6259        );
6260    }
6261    Ok(response)
6262}
6263
6264async fn revoke_token_record(
6265    registry: &Arc<dyn RegistryBackend>,
6266    record: AccessTokenRecord,
6267) -> Result<bool, ApiError> {
6268    let registry = registry.clone();
6269    let token_id = record.token_id().to_owned();
6270    tokio::task::spawn_blocking(move || registry.revoke_access_token(&token_id))
6271        .await
6272        .map_err(|_| ApiError::internal())?
6273        .map_err(|_| ApiError::internal())
6274}
6275
6276async fn revoke_access_token(
6277    State(gateway): State<Gateway>,
6278    headers: HeaderMap,
6279    Path(token_id): Path<String>,
6280) -> Result<Json<RevokedAccessToken>, ApiError> {
6281    gateway
6282        .authenticate_station(bearer(&headers)?)
6283        .map_err(ApiError::from)?;
6284    let registry = gateway.registry.clone().ok_or_else(ApiError::internal)?;
6285    let revoked = tokio::task::spawn_blocking(move || registry.revoke_access_token(&token_id))
6286        .await
6287        .map_err(|_| ApiError::internal())?
6288        .map_err(|_| ApiError::internal())?;
6289    Ok(Json(RevokedAccessToken { revoked }))
6290}
6291
6292fn access_token_digest(token: &str) -> String {
6293    secret_digest(b"ai6-access-token\0", token)
6294}
6295
6296/// Under its own prefix, so a cookie's value presented as a bearer token looks up a digest that
6297/// no record has.
6298fn session_cookie_digest(value: &str) -> String {
6299    secret_digest(b"ai6-session-cookie\0", value)
6300}
6301
6302fn secret_digest(purpose: &[u8], secret: &str) -> String {
6303    let mut hasher = Sha256::new();
6304    hasher.update(purpose);
6305    hasher.update(secret.as_bytes());
6306    PeerId::from_bytes(hasher.finalize().into()).hex()
6307}
6308
6309fn unix_timestamp() -> Result<f64, ApiError> {
6310    SystemTime::now()
6311        .duration_since(UNIX_EPOCH)
6312        .map(|time| time.as_secs_f64())
6313        .map_err(|_| ApiError::internal())
6314}
6315
6316fn utc_timestamp() -> Result<String, ApiError> {
6317    let seconds = SystemTime::now()
6318        .duration_since(UNIX_EPOCH)
6319        .map_err(|_| ApiError::internal())?
6320        .as_secs();
6321    let at = time::OffsetDateTime::from_unix_timestamp(
6322        i64::try_from(seconds).map_err(|_| ApiError::internal())?,
6323    )
6324    .map_err(|_| ApiError::internal())?;
6325    at.format(&time::format_description::well_known::Rfc3339)
6326        .map_err(|_| ApiError::internal())
6327}
6328
6329#[derive(Serialize)]
6330struct MissionProposalDecisionResponse {
6331    operation_id: String,
6332    proposal_id: String,
6333    mission_id: Option<String>,
6334    handle: Option<String>,
6335    state: &'static str,
6336}
6337
6338#[derive(Deserialize)]
6339#[serde(deny_unknown_fields)]
6340struct UserAuditQuery {
6341    operation_id: Option<String>,
6342    station_id: Option<String>,
6343    /// Only the records whose action starts with this (`run.context`, `internal.read`).
6344    action: Option<String>,
6345    limit: Option<usize>,
6346}
6347
6348/// The run a Run record says.
6349fn mission_run(record: &ai6::RunRecord) -> MissionRun {
6350    MissionRun {
6351        route: record.launch.as_ref().map(|launch| {
6352            ai6::RouteRef::new(
6353                launch.handler.clone(),
6354                launch.model.clone(),
6355                launch.pool.clone(),
6356            )
6357        }),
6358        account: record.account.clone(),
6359        state: record.result.as_ref().map(|result| result.state.clone()),
6360        changes: record.result.as_ref().and_then(|result| result.changes),
6361        verdict: record.verdict.clone(),
6362        deliverables: record
6363            .deliverables
6364            .iter()
6365            .map(ToString::to_string)
6366            .collect(),
6367        evidence: record.evidence.clone(),
6368        probe_requested: record.probe_requested,
6369        recommendation: record.recommendation.clone(),
6370        starts: record.starts.clone(),
6371        final_report: None,
6372        number: record.number,
6373        run_id: record.id.clone(),
6374        handle: record.handle.clone(),
6375        provider_id: record.provider_id.clone(),
6376        predecessor: record.predecessor.clone(),
6377        station: record.station.clone(),
6378        theater: record.theater.clone(),
6379        status: serde_json::to_value(record.status)
6380            .ok()
6381            .and_then(|status| status.as_str().map(str::to_owned))
6382            .unwrap_or_default(),
6383        lost: record.lost.clone(),
6384        checkpoint_branch: record
6385            .checkpoint
6386            .as_ref()
6387            .map(|checkpoint| checkpoint.branch.clone()),
6388    }
6389}
6390
6391/// The runs at each Mission among `records`, in run order.
6392fn runs_by_mission(records: Vec<ai6::RunRecord>) -> BTreeMap<String, Vec<MissionRun>> {
6393    let mut attempts = BTreeMap::<String, Vec<MissionRun>>::new();
6394    for record in &records {
6395        attempts
6396            .entry(record.mission_id.clone())
6397            .or_default()
6398            .push(mission_run(record));
6399    }
6400    for list in attempts.values_mut() {
6401        list.sort_by_key(|attempt| attempt.number);
6402    }
6403    attempts
6404}
6405
6406#[derive(Deserialize)]
6407struct GrantRequest {
6408    operation_id: String,
6409    mission_id: String,
6410    run_id: String,
6411    mode: String,
6412}
6413
6414#[derive(Serialize)]
6415struct TokenResponse {
6416    token: String,
6417}
6418
6419#[derive(Deserialize)]
6420struct ExchangeRequest {
6421    token: String,
6422}
6423
6424#[derive(Debug, Deserialize)]
6425struct AfterQuery {
6426    after: Option<u64>,
6427}
6428
6429async fn register_run(
6430    State(gateway): State<Gateway>,
6431    headers: HeaderMap,
6432    Json(request): Json<ai6::wire::RunRegistration>,
6433) -> Result<(StatusCode, Json<ai6_diptel::station::RunRegistered>), ApiError> {
6434    let token = bearer(&headers)?;
6435    let run_id = RunId::new(request.run_id).map_err(|_| ApiError::bad_request())?;
6436    let operation_id =
6437        OperationId::new(request.operation_id).map_err(|_| ApiError::bad_request())?;
6438    let mission_id = MissionId::new(request.mission_id).map_err(|_| ApiError::bad_request())?;
6439    gateway
6440        .register_run(
6441            token,
6442            operation_id.clone(),
6443            mission_id.clone(),
6444            run_id.clone(),
6445        )
6446        .await?;
6447    if let Some(brief) = request.mission {
6448        gateway
6449            .publish_mission_brief(token, operation_id, mission_id, brief)
6450            .await?;
6451    }
6452    let next_sequence = gateway.next_sequence(token, &run_id).await?;
6453    let terminal_bytes = gateway.terminal_bytes(&run_id);
6454    Ok((
6455        StatusCode::CREATED,
6456        Json(ai6_diptel::station::RunRegistered::new(
6457            next_sequence,
6458            u64::try_from(terminal_bytes).ok(),
6459        )),
6460    ))
6461}
6462
6463async fn publish_lifecycle(
6464    State(gateway): State<Gateway>,
6465    headers: HeaderMap,
6466    Path((run, sequence)): Path<(String, u64)>,
6467    Json(request): Json<ai6_diptel::station::LifecycleReport>,
6468) -> Result<StatusCode, ApiError> {
6469    let state = RunState::parse(&request.state).ok_or_else(ApiError::bad_request)?;
6470    if request
6471        .reason
6472        .as_deref()
6473        .is_some_and(|reason| !ai6_diptel::valid_reason(reason))
6474    {
6475        return Err(ApiError::bad_request());
6476    }
6477    gateway
6478        .publish_lifecycle(
6479            bearer(&headers)?,
6480            LifecycleEvent {
6481                operation_id: OperationId::new(request.operation_id)
6482                    .map_err(|_| ApiError::bad_request())?,
6483                mission_id: MissionId::new(request.mission_id)
6484                    .map_err(|_| ApiError::bad_request())?,
6485                run_id: RunId::new(run).map_err(|_| ApiError::bad_request())?,
6486                state,
6487                reason: request.reason,
6488                sequence,
6489            },
6490        )
6491        .await?;
6492    Ok(StatusCode::ACCEPTED)
6493}
6494
6495async fn publish_terminal_output(
6496    State(gateway): State<Gateway>,
6497    headers: HeaderMap,
6498    Path((run, sequence)): Path<(String, u64)>,
6499    body: Bytes,
6500) -> Result<StatusCode, ApiError> {
6501    gateway
6502        .publish_terminal_output(
6503            bearer(&headers)?,
6504            RunId::new(run).map_err(|_| ApiError::bad_request())?,
6505            sequence,
6506            body.to_vec(),
6507        )
6508        .await?;
6509    Ok(StatusCode::ACCEPTED)
6510}
6511
6512async fn ingest_event(
6513    State(gateway): State<Gateway>,
6514    headers: HeaderMap,
6515    Path((run, sequence)): Path<(String, u64)>,
6516    body: Bytes,
6517) -> Result<StatusCode, ApiError> {
6518    gateway
6519        .ingest(
6520            bearer(&headers)?,
6521            &RunId::new(run).map_err(|_| ApiError::bad_request())?,
6522            sequence,
6523            body.to_vec(),
6524        )
6525        .await?;
6526    Ok(StatusCode::ACCEPTED)
6527}
6528
6529async fn issue_attach_token(
6530    State(gateway): State<Gateway>,
6531    headers: HeaderMap,
6532    Json(request): Json<GrantRequest>,
6533) -> Result<Json<TokenResponse>, ApiError> {
6534    let mode = match request.mode.as_str() {
6535        "read" => AttachMode::Read,
6536        "write" => AttachMode::Write,
6537        _ => return Err(ApiError::bad_request()),
6538    };
6539    let token = gateway
6540        .issue_attach_token(
6541            bearer(&headers)?,
6542            AttachGrant {
6543                operation_id: OperationId::new(request.operation_id)
6544                    .map_err(|_| ApiError::bad_request())?,
6545                mission_id: MissionId::new(request.mission_id)
6546                    .map_err(|_| ApiError::bad_request())?,
6547                run_id: RunId::new(request.run_id).map_err(|_| ApiError::bad_request())?,
6548                mode,
6549            },
6550        )
6551        .await?;
6552    Ok(Json(TokenResponse { token }))
6553}
6554
6555async fn exchange_attach_token(
6556    State(gateway): State<Gateway>,
6557    headers: HeaderMap,
6558    Json(request): Json<ExchangeRequest>,
6559) -> Result<Response, ApiError> {
6560    require_origin(&gateway, &headers)?;
6561    let ticket = gateway.exchange_attach_token(&request.token).await?;
6562    let cookie = format!(
6563        "ai6_attach={ticket}; Path=/v1/socket; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
6564        gateway.config.attach_token_ttl().as_secs().max(1)
6565    );
6566    let mut response = StatusCode::NO_CONTENT.into_response();
6567    response.headers_mut().insert(
6568        SET_COOKIE,
6569        HeaderValue::from_str(&cookie).map_err(|_| ApiError::internal())?,
6570    );
6571    Ok(response)
6572}
6573
6574/// How long an input poll is held: `wait_ms`, else the `controls` table's wait.
6575#[derive(Deserialize)]
6576#[serde(deny_unknown_fields)]
6577struct InputPoll {
6578    wait_ms: Option<u64>,
6579}
6580
6581async fn next_agent_input(
6582    State(gateway): State<Gateway>,
6583    headers: HeaderMap,
6584    Query(poll): Query<InputPoll>,
6585) -> Result<Response, ApiError> {
6586    gateway.authenticate_station(bearer(&headers)?)?;
6587    let table = &gateway.config.unex().controls;
6588    let wait = poll
6589        .wait_ms
6590        .map_or(table.poll_wait.0, Duration::from_millis);
6591    let wait = table
6592        .max_poll_wait
6593        .get()
6594        .map_or(wait, |most| wait.min(most));
6595    let Some(input) = gateway.receive_agent_input_within(wait).await else {
6596        return Response::builder()
6597            .status(StatusCode::NO_CONTENT)
6598            .body(Body::empty())
6599            .map_err(|_| ApiError::internal());
6600    };
6601    let mut response = Response::new(Body::from(input.frame));
6602    *response.status_mut() = StatusCode::OK;
6603    response.headers_mut().insert(
6604        "content-type",
6605        HeaderValue::from_static("application/vnd.ai6.guatiao"),
6606    );
6607    response.headers_mut().insert(
6608        "x-ai6-operation-id",
6609        HeaderValue::from_str(input.operation_id.as_str()).map_err(|_| ApiError::internal())?,
6610    );
6611    response.headers_mut().insert(
6612        "x-ai6-mission-id",
6613        HeaderValue::from_str(input.mission_id.as_str()).map_err(|_| ApiError::internal())?,
6614    );
6615    response.headers_mut().insert(
6616        "x-ai6-run-id",
6617        HeaderValue::from_str(input.run_id.as_str()).map_err(|_| ApiError::internal())?,
6618    );
6619    Ok(response)
6620}
6621
6622async fn websocket_attach(
6623    State(gateway): State<Gateway>,
6624    Path(run): Path<String>,
6625    Query(after): Query<AfterQuery>,
6626    headers: HeaderMap,
6627    upgrade: WebSocketUpgrade,
6628) -> Result<Response, ApiError> {
6629    require_origin(&gateway, &headers)?;
6630    let cookie = headers
6631        .get(COOKIE)
6632        .and_then(|value| value.to_str().ok())
6633        .and_then(attach_cookie)
6634        .ok_or_else(ApiError::unauthorized)?;
6635    let run_id = RunId::new(run).map_err(|_| ApiError::bad_request())?;
6636    let attachment = gateway
6637        .attach(&run_id, cookie, after.after.unwrap_or(0))
6638        .await?;
6639    let max_write_buffer = gateway
6640        .config
6641        .limits
6642        .max_frame_bytes
6643        .saturating_mul(2)
6644        .max(gateway.config.limits.socket_buffer_bytes);
6645    Ok(upgrade
6646        .max_message_size(gateway.config.limits.max_frame_bytes)
6647        .max_frame_size(gateway.config.limits.max_frame_bytes)
6648        .max_write_buffer_size(max_write_buffer)
6649        .protocols(["ai6.guatiao"])
6650        .on_upgrade(move |socket| {
6651            serve_socket(
6652                browser_link::AppSocket::websocket(socket),
6653                gateway,
6654                attachment,
6655                run_id,
6656            )
6657        }))
6658}
6659
6660async fn serve_socket(
6661    socket: browser_link::AppSocket,
6662    gateway: Gateway,
6663    attachment: Attachment,
6664    run_id: RunId,
6665) {
6666    let Attachment {
6667        mode,
6668        replay,
6669        mut events,
6670        connection_id,
6671        expires,
6672        ..
6673    } = attachment;
6674    let browser_link::AppSocket {
6675        mut sender,
6676        mut receiver,
6677    } = socket;
6678    for frame in replay {
6679        if sender.send(Message::Binary(frame.into())).await.is_err() {
6680            gateway.disconnect_connection(&run_id, &connection_id).await;
6681            return;
6682        }
6683    }
6684    loop {
6685        tokio::select! {
6686            _ = tokio::time::sleep_until(tokio::time::Instant::from_std(expires)) => {
6687                let _ = sender.send(Message::Close(Some(CloseFrame {
6688                    code: 1008,
6689                    reason: "attachment credential expired".into(),
6690                }))).await;
6691                break;
6692            }
6693            message = receiver.next() => match message {
6694                Some(Ok(Message::Binary(frame))) if mode == AttachMode::Write => {
6695                    if gateway.submit_input(&run_id, &connection_id, frame.to_vec()).await.is_err() {
6696                        let _ = sender.send(close_policy()).await;
6697                        break;
6698                    }
6699                }
6700                Some(Ok(Message::Binary(_))) | Some(Ok(Message::Text(_))) => {
6701                    let _ = sender.send(close_policy()).await;
6702                    break;
6703                }
6704                Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break,
6705                Some(Ok(Message::Ping(payload))) => {
6706                    if sender.send(Message::Pong(payload)).await.is_err() { break; }
6707                }
6708                Some(Ok(Message::Pong(_))) => {}
6709            },
6710            event = events.recv() => match event {
6711                Ok(frame) => {
6712                    if sender.send(Message::Binary(frame.into())).await.is_err() { break; }
6713                }
6714                Err(broadcast::error::RecvError::Lagged(_)) => {
6715                    let _ = sender.send(Message::Close(Some(CloseFrame {
6716                        code: 1013,
6717                        reason: "viewer fell behind; reconnect with a cursor".into(),
6718                    }))).await;
6719                    break;
6720                }
6721                Err(broadcast::error::RecvError::Closed) => break,
6722            }
6723        }
6724    }
6725    gateway.disconnect_connection(&run_id, &connection_id).await;
6726}
6727
6728fn close_policy() -> Message {
6729    Message::Close(Some(CloseFrame {
6730        code: 1008,
6731        reason: "write authorization is required".into(),
6732    }))
6733}
6734
6735fn require_origin(gateway: &Gateway, headers: &HeaderMap) -> Result<(), ApiError> {
6736    origin_check(gateway, headers).map_err(|_| ApiError::forbidden())
6737}
6738
6739/// Which check a refused login failed. The caller is told only that the request is not
6740/// authorized; the journal gets the name.
6741#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6742pub(crate) enum LoginCheck {
6743    /// The request names no `Origin`.
6744    OriginMissing,
6745    /// The `Origin` is not the public origin.
6746    OriginMismatch,
6747    /// `X-Forwarded-Proto` is not `https`.
6748    ForwardedProto,
6749    /// The proxy secret header is absent or differs from the configured secret.
6750    ProxySecret,
6751    /// The proxy's identity header is empty, too long, lists several names or is not text.
6752    ProxyIdentity,
6753    /// The directory holds nobody the proxy's identity names.
6754    DirectoryMiss,
6755}
6756
6757impl LoginCheck {
6758    fn name(self) -> &'static str {
6759        match self {
6760            Self::OriginMissing => "origin header missing",
6761            Self::OriginMismatch => "origin is not the public origin",
6762            Self::ForwardedProto => "forwarded protocol is not https",
6763            Self::ProxySecret => "proxy secret does not match",
6764            Self::ProxyIdentity => "proxy identity header is unusable",
6765            Self::DirectoryMiss => "directory has no such person",
6766        }
6767    }
6768}
6769
6770fn origin_check(gateway: &Gateway, headers: &HeaderMap) -> Result<(), LoginCheck> {
6771    let origin = headers
6772        .get(ORIGIN)
6773        .and_then(|value| value.to_str().ok())
6774        .ok_or(LoginCheck::OriginMissing)?;
6775    if origin != gateway.public_origin() {
6776        return Err(LoginCheck::OriginMismatch);
6777    }
6778    let forwarded_proto = headers
6779        .get("x-forwarded-proto")
6780        .and_then(|value| value.to_str().ok());
6781    if forwarded_proto != Some("https") {
6782        return Err(LoginCheck::ForwardedProto);
6783    }
6784    Ok(())
6785}
6786
6787/// Writes one journal line for a refused login, naming the check and nothing the request sent.
6788fn journal_login_refusal(check: LoginCheck) {
6789    let line = format!("universal-exports: login refused: {}", check.name());
6790    #[cfg(test)]
6791    JOURNALED.lock().unwrap().push(line.clone());
6792    eprintln!("{line}");
6793}
6794
6795/// What the tests read back of the journal.
6796#[cfg(test)]
6797static JOURNALED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
6798
6799/// [`require_origin`] for a login route: a refusal is journaled with the failing check.
6800fn require_login_origin(gateway: &Gateway, headers: &HeaderMap) -> Result<(), ApiError> {
6801    origin_check(gateway, headers).map_err(|check| {
6802        journal_login_refusal(check);
6803        ApiError::forbidden()
6804    })
6805}
6806
6807fn bearer(headers: &HeaderMap) -> Result<&str, ApiError> {
6808    headers
6809        .get(AUTHORIZATION)
6810        .and_then(|value| value.to_str().ok())
6811        .and_then(|value| value.strip_prefix("Bearer "))
6812        .filter(|value| !value.is_empty())
6813        .ok_or_else(ApiError::unauthorized)
6814}
6815
6816fn attach_cookie(cookie: &str) -> Option<&str> {
6817    named_cookie(cookie, "ai6_attach")
6818}
6819
6820fn named_cookie<'a>(cookie: &'a str, wanted: &str) -> Option<&'a str> {
6821    cookie.split(';').find_map(|part| {
6822        let (name, value) = part.trim().split_once('=')?;
6823        (name == wanted && !value.is_empty()).then_some(value)
6824    })
6825}
6826
6827/// The cookie that resumes a sign-in; only `resume` and `logout` read it.
6828const SESSION_COOKIE: &str = "ai6_session";
6829
6830/// A client speaking HTTP/2 may split `Cookie` over several headers.
6831fn session_cookie(headers: &HeaderMap) -> Option<&str> {
6832    headers
6833        .get_all(COOKIE)
6834        .iter()
6835        .filter_map(|value| value.to_str().ok())
6836        .find_map(|cookie| named_cookie(cookie, SESSION_COOKIE))
6837}
6838
6839fn session_cookie_header(value: &str, max_age: u64) -> Result<HeaderValue, ApiError> {
6840    HeaderValue::from_str(&format!(
6841        "{SESSION_COOKIE}={value}; Path=/v1/auth; HttpOnly; Secure; SameSite=Strict; \
6842         Max-Age={max_age}"
6843    ))
6844    .map_err(|_| ApiError::internal())
6845}
6846
6847/// Tells the browser to drop the cookie.
6848fn ended_cookie() -> Result<HeaderValue, ApiError> {
6849    session_cookie_header("", 0)
6850}
6851
6852struct ApiError {
6853    status: StatusCode,
6854    message: std::borrow::Cow<'static, str>,
6855    retry_after_seconds: Option<u64>,
6856}
6857
6858impl ApiError {
6859    /// A 400 that says what was wrong with the request.
6860    fn invalid(message: String) -> Self {
6861        Self::refused(StatusCode::BAD_REQUEST, message)
6862    }
6863
6864    /// A refusal with `status` that says why.
6865    fn refused(status: StatusCode, message: String) -> Self {
6866        Self {
6867            status,
6868            message: std::borrow::Cow::Owned(message),
6869            retry_after_seconds: None,
6870        }
6871    }
6872
6873    fn payload_too_large() -> Self {
6874        Self {
6875            status: StatusCode::PAYLOAD_TOO_LARGE,
6876            message: std::borrow::Cow::Borrowed("request body is too large"),
6877            retry_after_seconds: None,
6878        }
6879    }
6880
6881    fn not_found() -> Self {
6882        Self {
6883            status: StatusCode::NOT_FOUND,
6884            message: std::borrow::Cow::Borrowed("resource is not available"),
6885            retry_after_seconds: None,
6886        }
6887    }
6888
6889    fn bad_request() -> Self {
6890        Self {
6891            status: StatusCode::BAD_REQUEST,
6892            message: std::borrow::Cow::Borrowed("request is invalid"),
6893            retry_after_seconds: None,
6894        }
6895    }
6896
6897    fn unauthorized() -> Self {
6898        Self {
6899            status: StatusCode::UNAUTHORIZED,
6900            message: std::borrow::Cow::Borrowed("authentication is required"),
6901            retry_after_seconds: None,
6902        }
6903    }
6904
6905    fn forbidden() -> Self {
6906        Self {
6907            status: StatusCode::FORBIDDEN,
6908            message: std::borrow::Cow::Borrowed("request is not authorized"),
6909            retry_after_seconds: None,
6910        }
6911    }
6912
6913    fn internal() -> Self {
6914        Self {
6915            status: StatusCode::INTERNAL_SERVER_ERROR,
6916            message: std::borrow::Cow::Borrowed("gateway operation failed"),
6917            retry_after_seconds: None,
6918        }
6919    }
6920
6921    fn unavailable() -> Self {
6922        Self {
6923            status: StatusCode::SERVICE_UNAVAILABLE,
6924            message: std::borrow::Cow::Borrowed("user access providers are unavailable"),
6925            retry_after_seconds: None,
6926        }
6927    }
6928
6929    fn too_many_attempts(wait: Duration) -> Self {
6930        Self {
6931            status: StatusCode::TOO_MANY_REQUESTS,
6932            message: std::borrow::Cow::Borrowed("too many login attempts; try again later"),
6933            retry_after_seconds: Some(wait.as_secs().max(1)),
6934        }
6935    }
6936}
6937
6938impl From<GatewayError> for ApiError {
6939    fn from(error: GatewayError) -> Self {
6940        let status = match error {
6941            GatewayError::Unauthorized | GatewayError::InvalidCredential => {
6942                StatusCode::UNAUTHORIZED
6943            }
6944            GatewayError::Forbidden => StatusCode::FORBIDDEN,
6945            GatewayError::NotFound => StatusCode::NOT_FOUND,
6946            GatewayError::Conflict | GatewayError::Backpressure => StatusCode::CONFLICT,
6947            GatewayError::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
6948            GatewayError::InvalidFrame | GatewayError::InvalidConfiguration => {
6949                StatusCode::BAD_REQUEST
6950            }
6951        };
6952        Self {
6953            status,
6954            message: std::borrow::Cow::Borrowed("gateway request was refused"),
6955            retry_after_seconds: None,
6956        }
6957    }
6958}
6959
6960impl IntoResponse for ApiError {
6961    fn into_response(self) -> Response {
6962        let mut response = (self.status, self.message).into_response();
6963        if let Some(seconds) = self.retry_after_seconds {
6964            response
6965                .headers_mut()
6966                .insert(RETRY_AFTER, HeaderValue::from(seconds));
6967        }
6968        response
6969    }
6970}
6971
6972fn prune_expired(inner: &mut Inner) {
6973    let now = Instant::now();
6974    inner.attach_tokens.retain(|_, timed| timed.expires > now);
6975    inner
6976        .connection_tickets
6977        .retain(|_, timed| timed.expires > now);
6978    for run in inner.runs.values_mut() {
6979        if run.lease.as_ref().is_some_and(|lease| lease.expires <= now) {
6980            run.lease = None;
6981        }
6982    }
6983}
6984
6985fn pending_credential_capacity(config: &GatewayConfig) -> usize {
6986    config
6987        .limits
6988        .max_runs
6989        .saturating_mul(config.limits.max_clients_per_run)
6990        .clamp(16, 65_536)
6991}
6992
6993fn client_slots_or_max(limits: GatewayLimits) -> usize {
6994    limits.max_runs.saturating_mul(limits.max_clients_per_run)
6995}
6996
6997/// Whether `left` and `right` are equal, in time that does not depend on where they differ.
6998/// A different length is refused at once: the length of a stored secret or digest is fixed by
6999/// its format and is not itself secret.
7000fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
7001    left.len() == right.len() && bool::from(left.ct_eq(right))
7002}
7003
7004fn validate_input_frame(run_id: &RunId, frame: &[u8]) -> Result<u64, GatewayError> {
7005    let template = TerminalData::new(run_id.clone(), 1, TerminalDirection::Input, Vec::new())
7006        .map_err(|_| GatewayError::InvalidFrame)?;
7007    let resize_template =
7008        TerminalResize::new(run_id.clone(), 1, 80, 24).map_err(|_| GatewayError::InvalidFrame)?;
7009    let (terminal_schema, _) =
7010        terminal_frames(&template).map_err(|_| GatewayError::InvalidFrame)?;
7011    let (resize_schema, _) =
7012        resize_frames(&resize_template).map_err(|_| GatewayError::InvalidFrame)?;
7013    let mut receiver = FrameReceiver::new();
7014    receiver
7015        .accept(&terminal_schema)
7016        .map_err(|_| GatewayError::InvalidFrame)?;
7017    receiver
7018        .accept(&resize_schema)
7019        .map_err(|_| GatewayError::InvalidFrame)?;
7020    match receiver
7021        .accept(frame)
7022        .map_err(|_| GatewayError::InvalidFrame)?
7023        .ok_or(GatewayError::InvalidFrame)?
7024    {
7025        IncomingFrame::Terminal(data)
7026            if data.run_id() == run_id
7027                && data.direction() == TerminalDirection::Input
7028                && data.sequence() > 0 =>
7029        {
7030            Ok(data.sequence())
7031        }
7032        IncomingFrame::Resize(resize) if resize.run_id() == run_id && resize.sequence() > 0 => {
7033            Ok(resize.sequence())
7034        }
7035        IncomingFrame::Terminal(_) | IncomingFrame::Resize(_) => Err(GatewayError::Forbidden),
7036        IncomingFrame::Lifecycle(_)
7037        | IncomingFrame::Control(_)
7038        | IncomingFrame::Gap(_)
7039        | IncomingFrame::Closed(_) => Err(GatewayError::InvalidFrame),
7040    }
7041}
7042
7043fn validate_lifecycle_value(
7044    value: &guatiao::Value,
7045    operation_id: &OperationId,
7046    mission_id: &MissionId,
7047    run_id: &RunId,
7048    expected_sequence: u64,
7049) -> Result<(), GatewayError> {
7050    let map: &Map = value.try_as_ref().ok_or(GatewayError::InvalidFrame)?;
7051    let station = read_text(map, "operation_id")?;
7052    let mission = read_text(map, "mission_id")?;
7053    let run = read_text(map, "run_id")?;
7054    let state = read_text(map, "state")?;
7055    let sequence = read_sequence(map)?;
7056    if station != operation_id.as_str()
7057        || mission != mission_id.as_str()
7058        || run != run_id.as_str()
7059        || RunState::parse(state).is_none()
7060        || sequence != expected_sequence
7061    {
7062        return Err(GatewayError::Forbidden);
7063    }
7064    Ok(())
7065}
7066
7067/// The schema and value of a gap, when a sequence lies between `after` and `before`.
7068fn gap_between(
7069    run_id: &RunId,
7070    after: u64,
7071    before: u64,
7072) -> Result<Option<[Vec<u8>; 2]>, GatewayError> {
7073    let Ok(gap) = ai6_diptel::TerminalGap::new(run_id.clone(), after, before) else {
7074        return Ok(None);
7075    };
7076    let (schema, value) = ai6_diptel::gap_frames(&gap).map_err(|_| GatewayError::InvalidFrame)?;
7077    Ok(Some([schema, value]))
7078}
7079
7080fn validate_terminal_output(
7081    value: &guatiao::Value,
7082    run_id: &RunId,
7083    expected_sequence: u64,
7084    max_frame_bytes: usize,
7085) -> Result<(), GatewayError> {
7086    let map: &Map = value.try_as_ref().ok_or(GatewayError::InvalidFrame)?;
7087    let run = read_text(map, "run_id")?;
7088    let direction = read_text(map, "direction")?;
7089    let sequence = read_sequence(map)?;
7090    let bytes: &[u8] = map
7091        .required("bytes")
7092        .map_err(|_| GatewayError::InvalidFrame)?
7093        .try_into()
7094        .map_err(|_| GatewayError::InvalidFrame)?;
7095    if run != run_id.as_str() || direction != "output" || sequence != expected_sequence {
7096        return Err(GatewayError::Forbidden);
7097    }
7098    if bytes.len() > max_frame_bytes {
7099        return Err(GatewayError::TooLarge);
7100    }
7101    Ok(())
7102}
7103
7104fn read_text<'a>(map: &'a Map, key: &str) -> Result<&'a str, GatewayError> {
7105    <&str>::try_from(map.required(key).map_err(|_| GatewayError::InvalidFrame)?)
7106        .map_err(|_| GatewayError::InvalidFrame)
7107}
7108
7109fn read_sequence(map: &Map) -> Result<u64, GatewayError> {
7110    u64::try_from(
7111        map.required("sequence")
7112            .map_err(|_| GatewayError::InvalidFrame)?,
7113    )
7114    .map_err(|_| GatewayError::InvalidFrame)
7115}
7116
7117#[cfg(test)]
7118mod tests {
7119    use super::*;
7120
7121    #[test]
7122    fn secrets_compare_equal_only_when_every_byte_and_the_length_match() {
7123        assert!(constant_time_eq(b"", b""));
7124        assert!(constant_time_eq(b"station-token", b"station-token"));
7125        assert!(!constant_time_eq(b"station-token", b"station-tokeN"));
7126        assert!(!constant_time_eq(b"station-token", b"station-toke"));
7127        assert!(!constant_time_eq(b"station-toke", b"station-token"));
7128        assert!(!constant_time_eq(b"", b"x"));
7129    }
7130
7131    const PROXY_TEST_SECRET: &str = "proxy-secret-that-is-long-enough-for-tests";
7132    use ai6::{FileRegistry, RoleAuthorizer};
7133    use ai6_diptel::{
7134        LifecycleEvent, RunState, TerminalData, TerminalDirection, TerminalResize,
7135        lifecycle_frames, resize_frames, terminal_frames,
7136    };
7137    use guatiao::library::ProviderError;
7138    use tokio_tungstenite::tungstenite::client::IntoClientRequest;
7139
7140    pub(super) fn test_limits() -> GatewayLimits {
7141        GatewayLimits {
7142            max_runs: 4,
7143            max_clients_per_run: 3,
7144            scrollback_events: 2,
7145            max_frame_bytes: 1024,
7146            max_input_frames_per_second: 20,
7147            input_queue_capacity: 2,
7148            fanout_capacity: 2,
7149            ..GatewayLimits::default()
7150        }
7151    }
7152
7153    #[test]
7154    fn reverse_proxy_access_can_be_configured_without_a_password_authenticator() {
7155        struct DirectoryStub;
7156
7157        impl Directory for DirectoryStub {
7158            fn lookup(&self, _lookup: Lookup) -> Result<Option<Person>, ProviderError> {
7159                Ok(None)
7160            }
7161        }
7162
7163        let access = AccessProviders::from_reverse_proxy(
7164            Arc::new(DirectoryStub),
7165            Arc::new(RoleAuthorizer::default()),
7166            HeaderName::from_static("x-forwarded-user"),
7167            "name",
7168        );
7169
7170        assert!(access.authenticators.is_empty());
7171        assert_eq!(
7172            access
7173                .proxy_identity
7174                .as_ref()
7175                .map(|proxy| (proxy.header.as_str(), proxy.lookup_by.as_str())),
7176            Some(("x-forwarded-user", "name"))
7177        );
7178    }
7179
7180    #[test]
7181    fn a_running_gateway_follows_its_login_counts_lifetimes_and_secret_bounds() {
7182        let gateway = gateway();
7183        let source: std::net::IpAddr = "203.0.113.9".parse().unwrap();
7184        let strict = LoginLimits {
7185            per_address: std::num::NonZeroU32::MIN,
7186            ..LoginLimits::default()
7187        };
7188        gateway.set_login_limits(&strict);
7189        assert!(gateway.resume_guard().tried_address(source).is_none());
7190        assert!(gateway.resume_guard().tried_address(source).is_some());
7191        assert!(gateway.login_guard().tried(source, "ana").is_none());
7192        assert!(gateway.login_guard().tried(source, "ana").is_some());
7193        gateway.set_login_limits(&LoginLimits::default());
7194        assert!(
7195            gateway.resume_guard().tried_address(source).is_none(),
7196            "a changed record starts the counts over"
7197        );
7198
7199        gateway
7200            .config
7201            .set_lifetimes(Duration::from_secs(7), Duration::from_secs(8))
7202            .unwrap();
7203        assert_eq!(gateway.config.attach_token_ttl(), Duration::from_secs(7));
7204        assert_eq!(gateway.config.write_lease_ttl(), Duration::from_secs(8));
7205        assert!(
7206            gateway
7207                .config
7208                .set_lifetimes(Duration::ZERO, Duration::from_secs(8))
7209                .is_err()
7210        );
7211        assert_eq!(gateway.config.attach_token_ttl(), Duration::from_secs(7));
7212
7213        let (_, origin) = gateway.config.secret_limits();
7214        assert!(gateway.config.set_secret_limits(8, origin).is_ok());
7215        assert_eq!(gateway.config.secret_limits().0, 8);
7216        assert!(
7217            gateway.config.set_secret_limits(1000, origin).is_err(),
7218            "a token shorter than the bound is refused"
7219        );
7220        assert!(
7221            gateway
7222                .config
7223                .set_secret_limits(8, ai6::Limit::at(3))
7224                .is_err()
7225        );
7226        assert_eq!(gateway.config.secret_limits().0, 8);
7227    }
7228
7229    fn gateway() -> Gateway {
7230        Gateway::new(
7231            GatewayConfig::new(
7232                "https://localhost",
7233                "m-token-that-is-long-enough-for-testing",
7234                test_limits(),
7235                Duration::from_secs(30),
7236                Duration::from_secs(30),
7237            )
7238            .unwrap(),
7239        )
7240    }
7241
7242    async fn register(gateway: &Gateway) -> (OperationId, MissionId, RunId) {
7243        let station = OperationId::new("station-a").unwrap();
7244        let mission = MissionId::new("mission-a").unwrap();
7245        let run = RunId::new("provider-id-a").unwrap();
7246        gateway
7247            .register_run(
7248                "m-token-that-is-long-enough-for-testing",
7249                station.clone(),
7250                mission.clone(),
7251                run.clone(),
7252            )
7253            .await
7254            .unwrap();
7255        (station, mission, run)
7256    }
7257
7258    #[tokio::test]
7259    async fn board_missions_group_provider_ids_by_station_and_mission() {
7260        let gateway = gateway();
7261        let (station, mission, _) = register(&gateway).await;
7262        gateway
7263            .register_run(
7264                "m-token-that-is-long-enough-for-testing",
7265                station,
7266                mission,
7267                RunId::new("provider-id-b").unwrap(),
7268            )
7269            .await
7270            .unwrap();
7271
7272        let missions = gateway.board_missions().await;
7273
7274        assert_eq!(missions.len(), 1);
7275        assert_eq!(missions[0].operation_id, "station-a");
7276        assert_eq!(missions[0].mission_id, "mission-a");
7277        assert_eq!(missions[0].runs.len(), 2);
7278    }
7279
7280    async fn grant(gateway: &Gateway, mode: AttachMode) -> String {
7281        let (station, mission, run) = register(gateway).await;
7282        gateway
7283            .issue_attach_token(
7284                "m-token-that-is-long-enough-for-testing",
7285                AttachGrant {
7286                    operation_id: station,
7287                    mission_id: mission,
7288                    run_id: run,
7289                    mode,
7290                },
7291            )
7292            .await
7293            .unwrap()
7294    }
7295
7296    fn output(run: &RunId, sequence: u64) -> (Vec<u8>, Vec<u8>) {
7297        let event = TerminalData::new(
7298            run.clone(),
7299            sequence,
7300            TerminalDirection::Output,
7301            vec![0xff, sequence as u8],
7302        )
7303        .unwrap();
7304        terminal_frames(&event).unwrap()
7305    }
7306
7307    #[tokio::test]
7308    async fn m_authentication_and_station_scoping_are_enforced() {
7309        let gateway = gateway();
7310        assert_eq!(
7311            gateway.authenticate_station("wrong").unwrap_err(),
7312            GatewayError::Unauthorized
7313        );
7314        let (_, _, run) = register(&gateway).await;
7315        let result = gateway
7316            .issue_attach_token(
7317                "m-token-that-is-long-enough-for-testing",
7318                AttachGrant {
7319                    operation_id: OperationId::new("other-station").unwrap(),
7320                    mission_id: MissionId::new("mission-a").unwrap(),
7321                    run_id: run,
7322                    mode: AttachMode::Read,
7323                },
7324            )
7325            .await;
7326        assert_eq!(result.unwrap_err(), GatewayError::Forbidden);
7327    }
7328
7329    #[tokio::test]
7330    async fn the_board_shows_why_a_run_is_held_until_its_next_state() {
7331        let gateway = gateway();
7332        let (operation, mission, run) = register(&gateway).await;
7333        let event = |state, reason: Option<&str>, sequence| LifecycleEvent {
7334            operation_id: operation.clone(),
7335            mission_id: mission.clone(),
7336            run_id: run.clone(),
7337            state,
7338            reason: reason.map(str::to_owned),
7339            sequence,
7340        };
7341        let token = "m-token-that-is-long-enough-for-testing";
7342        gateway
7343            .publish_lifecycle(token, event(RunState::Blocked, Some("green-ink"), 1))
7344            .await
7345            .unwrap();
7346        let board = gateway.board_runs().await;
7347        assert_eq!(
7348            (board[0].state.as_deref(), board[0].reason.as_deref()),
7349            (Some("blocked"), Some("green-ink"))
7350        );
7351        gateway
7352            .publish_lifecycle(token, event(RunState::Working, None, 2))
7353            .await
7354            .unwrap();
7355        assert_eq!(gateway.board_runs().await[0].reason, None);
7356        assert!(
7357            gateway
7358                .publish_lifecycle(token, event(RunState::Blocked, Some("Green Ink"), 3))
7359                .await
7360                .is_err(),
7361            "a reason is a name"
7362        );
7363    }
7364
7365    #[tokio::test]
7366    async fn typed_m_publisher_encodes_failed_state_and_binary_terminal_output() {
7367        let gateway = gateway();
7368        let (station, mission, run) = register(&gateway).await;
7369        assert_eq!(gateway.board_runs().await[0].updated_at, None);
7370        gateway
7371            .publish_lifecycle(
7372                "m-token-that-is-long-enough-for-testing",
7373                LifecycleEvent {
7374                    operation_id: station,
7375                    mission_id: mission,
7376                    run_id: run.clone(),
7377                    state: RunState::Failed,
7378                    reason: None,
7379                    sequence: 1,
7380                },
7381            )
7382            .await
7383            .unwrap();
7384        let board = gateway.board_runs().await;
7385        assert_eq!(board[0].state.as_deref(), Some("failed"));
7386        assert!(board[0].updated_at.is_some_and(|at| at > 0.0));
7387        gateway
7388            .publish_terminal_output(
7389                "m-token-that-is-long-enough-for-testing",
7390                run.clone(),
7391                2,
7392                vec![0xff, 0x00, 0x80],
7393            )
7394            .await
7395            .unwrap();
7396
7397        let token = grant(&gateway, AttachMode::Read).await;
7398        let ticket = gateway.exchange_attach_token(&token).await.unwrap();
7399        let attachment = gateway.attach(&run, &ticket, 0).await.unwrap();
7400        assert_eq!(attachment.replay.len(), 4);
7401        let mut receiver = guatiao::value::wire::channel::Receiver::new();
7402        for frame in &attachment.replay {
7403            match receiver.accept(frame).unwrap() {
7404                guatiao::value::wire::channel::Received::Value { channel: 1, value } => {
7405                    let map: &Map = value.try_as_ref().unwrap();
7406                    assert_eq!(read_text(map, "state").unwrap(), "failed");
7407                    assert_eq!(read_text(map, "mission_id").unwrap(), "mission-a");
7408                }
7409                guatiao::value::wire::channel::Received::Value { channel: 2, value } => {
7410                    let map: &Map = value.try_as_ref().unwrap();
7411                    let bytes: &[u8] = map.required("bytes").unwrap().try_into().unwrap();
7412                    assert_eq!(bytes, [0xff, 0x00, 0x80]);
7413                }
7414                _ => {}
7415            }
7416        }
7417    }
7418
7419    #[tokio::test]
7420    async fn attach_tokens_are_single_use_and_write_lease_is_exclusive() {
7421        let gateway = gateway();
7422        let token = grant(&gateway, AttachMode::Write).await;
7423        let cookie = gateway.exchange_attach_token(&token).await.unwrap();
7424        assert_eq!(
7425            gateway.exchange_attach_token(&token).await.unwrap_err(),
7426            GatewayError::InvalidCredential
7427        );
7428        let run = RunId::new("provider-id-a").unwrap();
7429        let attachment = gateway.attach(&run, &cookie, 0).await.unwrap();
7430
7431        let second_token = grant(&gateway, AttachMode::Write).await;
7432        let second_cookie = gateway.exchange_attach_token(&second_token).await.unwrap();
7433        assert_eq!(
7434            gateway.attach(&run, &second_cookie, 0).await.unwrap_err(),
7435            GatewayError::Conflict
7436        );
7437        gateway.disconnect(attachment).await;
7438        let next = grant(&gateway, AttachMode::Write).await;
7439        let next = gateway.exchange_attach_token(&next).await.unwrap();
7440        assert!(gateway.attach(&run, &next, 0).await.is_ok());
7441    }
7442
7443    #[tokio::test]
7444    async fn credentials_and_write_leases_expire() {
7445        let gateway = Gateway::new(
7446            GatewayConfig::new(
7447                "https://localhost",
7448                "m-token-that-is-long-enough-for-testing",
7449                test_limits(),
7450                Duration::from_millis(40),
7451                Duration::from_millis(10),
7452            )
7453            .unwrap(),
7454        );
7455        let (_, _, run) = register(&gateway).await;
7456        let token = grant(&gateway, AttachMode::Read).await;
7457        tokio::time::sleep(Duration::from_millis(50)).await;
7458        assert_eq!(
7459            gateway.exchange_attach_token(&token).await.unwrap_err(),
7460            GatewayError::InvalidCredential
7461        );
7462
7463        let old_token = grant(&gateway, AttachMode::Write).await;
7464        let old_ticket = gateway.exchange_attach_token(&old_token).await.unwrap();
7465        let old_writer = gateway.attach(&run, &old_ticket, 0).await.unwrap();
7466        tokio::time::sleep(Duration::from_millis(15)).await;
7467        let new_token = grant(&gateway, AttachMode::Write).await;
7468        let new_ticket = gateway.exchange_attach_token(&new_token).await.unwrap();
7469        let new_writer = gateway.attach(&run, &new_ticket, 0).await.unwrap();
7470        assert_eq!(new_writer.mode, AttachMode::Write);
7471        let stale_input =
7472            TerminalData::new(run.clone(), 1, TerminalDirection::Input, vec![b'x']).unwrap();
7473        let (_, stale_frame) = terminal_frames(&stale_input).unwrap();
7474        assert_eq!(
7475            gateway
7476                .submit_input(&run, &old_writer.connection_id, stale_frame)
7477                .await
7478                .unwrap_err(),
7479            GatewayError::Forbidden,
7480            "an expired writer cannot submit after another writer takes the lease"
7481        );
7482        gateway.disconnect(old_writer).await;
7483        gateway.disconnect(new_writer).await;
7484    }
7485
7486    #[tokio::test]
7487    async fn attachment_ticket_is_run_scoped_and_read_is_default() {
7488        let gateway = gateway();
7489        let token = grant(&gateway, AttachMode::Read).await;
7490        let cookie = gateway.exchange_attach_token(&token).await.unwrap();
7491        assert_eq!(
7492            gateway
7493                .attach(&RunId::new("other").unwrap(), &cookie, 0)
7494                .await
7495                .unwrap_err(),
7496            GatewayError::Forbidden
7497        );
7498
7499        let token = grant(&gateway, AttachMode::Read).await;
7500        let cookie = gateway.exchange_attach_token(&token).await.unwrap();
7501        let attachment = gateway
7502            .attach(&RunId::new("provider-id-a").unwrap(), &cookie, 0)
7503            .await
7504            .unwrap();
7505        assert_eq!(attachment.mode, AttachMode::Read);
7506        gateway.disconnect(attachment).await;
7507    }
7508
7509    #[tokio::test]
7510    async fn scrollback_is_bounded_and_replay_honors_the_sequence_cursor() {
7511        let gateway = gateway();
7512        let (_, _, run) = register(&gateway).await;
7513        let (schema, first) = output(&run, 1);
7514        gateway
7515            .ingest("m-token-that-is-long-enough-for-testing", &run, 0, schema)
7516            .await
7517            .unwrap();
7518        gateway
7519            .ingest("m-token-that-is-long-enough-for-testing", &run, 1, first)
7520            .await
7521            .unwrap();
7522        let (_, second) = output(&run, 2);
7523        gateway
7524            .ingest("m-token-that-is-long-enough-for-testing", &run, 2, second)
7525            .await
7526            .unwrap();
7527        let (_, third) = output(&run, 3);
7528        gateway
7529            .ingest("m-token-that-is-long-enough-for-testing", &run, 3, third)
7530            .await
7531            .unwrap();
7532
7533        let token = grant(&gateway, AttachMode::Read).await;
7534        let ticket = gateway.exchange_attach_token(&token).await.unwrap();
7535        let mut attachment = gateway.attach(&run, &ticket, 1).await.unwrap();
7536        assert_eq!(
7537            attachment.replay.len(),
7538            3,
7539            "current schema plus both retained events newer than the cursor"
7540        );
7541        assert!(matches!(
7542            attachment.events.try_recv(),
7543            Err(broadcast::error::TryRecvError::Empty)
7544        ));
7545        gateway.disconnect(attachment).await;
7546    }
7547
7548    #[tokio::test]
7549    async fn what_a_station_is_told_fits_one_frame_at_any_sequence() {
7550        let gateway = gateway();
7551        let longest = RunId::new("s".repeat(ai6_diptel::MAX_ID_BYTES)).unwrap();
7552        let token = "m-token-that-is-long-enough-for-testing";
7553        gateway
7554            .register_run(
7555                token,
7556                OperationId::new("station-a").unwrap(),
7557                MissionId::new("mission-a").unwrap(),
7558                longest.clone(),
7559            )
7560            .await
7561            .unwrap();
7562        let stated = gateway.terminal_bytes(&longest);
7563        assert!(stated > 0, "the test's frames hold more than a header");
7564        gateway
7565            .publish_terminal_output(token, longest.clone(), u64::MAX, vec![7; stated])
7566            .await
7567            .expect("as much as it states fits, at the longest sequence");
7568        // A frame's length field grows by at most this much, so this is past the frame.
7569        let over = stated + LENGTH_GROWTH + 1;
7570        assert!(matches!(
7571            gateway
7572                .publish_terminal_output(token, longest, u64::MAX, vec![7; over])
7573                .await,
7574            Err(GatewayError::TooLarge)
7575        ));
7576    }
7577
7578    #[test]
7579    fn the_wire_limit_caps_what_a_station_is_told() {
7580        let gateway = Gateway::new(
7581            GatewayConfig::new(
7582                "https://localhost",
7583                "m-token-that-is-long-enough-for-testing",
7584                GatewayLimits {
7585                    max_frame_bytes: 4 * ai6_diptel::MAX_TERMINAL_BYTES,
7586                    ..test_limits()
7587                },
7588                Duration::from_secs(30),
7589                Duration::from_secs(30),
7590            )
7591            .unwrap(),
7592        );
7593        assert_eq!(
7594            gateway.terminal_bytes(&RunId::new("run").unwrap()),
7595            ai6_diptel::MAX_TERMINAL_BYTES
7596        );
7597    }
7598
7599    /// The gaps in `frames`, as (after, before), and the sequences of its other values, in order.
7600    fn gaps_and_values(frames: &[Vec<u8>]) -> (Vec<(u64, u64)>, Vec<u64>) {
7601        let mut receiver = FrameReceiver::new();
7602        let (mut gaps, mut values) = (Vec::new(), Vec::new());
7603        for frame in frames {
7604            match receiver.accept(frame).unwrap() {
7605                Some(IncomingFrame::Gap(gap)) => {
7606                    gaps.push((gap.after(), gap.before()));
7607                    // Where it falls: nothing older follows.
7608                    values.push(gap.before() * 1000);
7609                }
7610                Some(IncomingFrame::Terminal(data)) => values.push(data.sequence()),
7611                _ => {}
7612            }
7613        }
7614        (gaps, values)
7615    }
7616
7617    /// Publishes output at each of `sequences`, then attaches after `after`.
7618    async fn attach_after(
7619        gateway: &Gateway,
7620        run: &RunId,
7621        sequences: &[u64],
7622        after: u64,
7623    ) -> Attachment {
7624        let token = "m-token-that-is-long-enough-for-testing";
7625        for sequence in sequences {
7626            gateway
7627                .publish_terminal_output(token, run.clone(), *sequence, vec![1])
7628                .await
7629                .unwrap();
7630        }
7631        let grant = grant(gateway, AttachMode::Read).await;
7632        let ticket = gateway.exchange_attach_token(&grant).await.unwrap();
7633        gateway.attach(run, &ticket, after).await.unwrap()
7634    }
7635
7636    #[tokio::test]
7637    async fn a_viewer_whose_position_was_trimmed_is_told_of_the_gap() {
7638        let gateway = gateway();
7639        let (_, _, run) = register(&gateway).await;
7640        // The test's scrollback holds two events.
7641        let attachment = attach_after(&gateway, &run, &[1, 2, 3, 4, 5], 1).await;
7642        let (gaps, values) = gaps_and_values(&attachment.replay);
7643        assert_eq!(gaps, [(1, 4)], "2 and 3 are gone");
7644        assert_eq!(
7645            values,
7646            [4000, 4, 5],
7647            "the gap comes ahead of what follows it"
7648        );
7649        gateway.disconnect(attachment).await;
7650
7651        let attachment = attach_after(&gateway, &run, &[], 0).await;
7652        assert_eq!(
7653            gaps_and_values(&attachment.replay).0,
7654            [(0, 4)],
7655            "from the start too"
7656        );
7657        gateway.disconnect(attachment).await;
7658
7659        let attachment = attach_after(&gateway, &run, &[], 3).await;
7660        assert_eq!(
7661            gaps_and_values(&attachment.replay).0,
7662            [],
7663            "nothing it lacks is gone"
7664        );
7665        gateway.disconnect(attachment).await;
7666
7667        let attachment = attach_after(&gateway, &run, &[], 5).await;
7668        let (gaps, values) = gaps_and_values(&attachment.replay);
7669        assert_eq!(
7670            (gaps, values),
7671            (Vec::new(), Vec::new()),
7672            "it has everything"
7673        );
7674        gateway.disconnect(attachment).await;
7675    }
7676
7677    #[tokio::test]
7678    async fn a_hole_in_the_sequence_is_a_gap_on_replay_and_live() {
7679        // Room for a gap's two frames and the one after them in a viewer's queue.
7680        let gateway = Gateway::new(
7681            GatewayConfig::new(
7682                "https://localhost",
7683                "m-token-that-is-long-enough-for-testing",
7684                GatewayLimits {
7685                    fanout_capacity: 8,
7686                    ..test_limits()
7687                },
7688                Duration::from_secs(30),
7689                Duration::from_secs(30),
7690            )
7691            .unwrap(),
7692        );
7693        let (_, _, run) = register(&gateway).await;
7694        let mut attachment = attach_after(&gateway, &run, &[1, 4], 0).await;
7695        let (gaps, values) = gaps_and_values(&attachment.replay);
7696        assert_eq!(gaps, [(1, 4)], "the Station dropped 2 and 3");
7697        assert_eq!(values, [1, 4000, 4]);
7698
7699        let token = "m-token-that-is-long-enough-for-testing";
7700        gateway
7701            .publish_terminal_output(token, run.clone(), 7, vec![1])
7702            .await
7703            .unwrap();
7704        let mut live = attachment.replay.clone();
7705        while let Ok(frame) = attachment.events.try_recv() {
7706            live.push(frame);
7707        }
7708        assert_eq!(
7709            gaps_and_values(&live).0,
7710            [(1, 4), (4, 7)],
7711            "a viewer already attached hears of it before the frame that follows it"
7712        );
7713        gateway.disconnect(attachment).await;
7714    }
7715
7716    #[tokio::test]
7717    async fn a_gateway_that_restarted_tells_a_new_viewer_and_spares_one_that_has_it_all() {
7718        let gateway = gateway();
7719        let (_, _, run) = register(&gateway).await;
7720        // A Station's first event after this gateway restarted, its sequence going on from 40.
7721        let attachment = attach_after(&gateway, &run, &[41], 0).await;
7722        assert_eq!(gaps_and_values(&attachment.replay).0, [(0, 41)]);
7723        gateway.disconnect(attachment).await;
7724        let attachment = attach_after(&gateway, &run, &[], 40).await;
7725        assert_eq!(gaps_and_values(&attachment.replay).0, []);
7726        gateway.disconnect(attachment).await;
7727    }
7728
7729    #[tokio::test]
7730    async fn slow_viewers_are_bounded_and_report_lag() {
7731        let gateway = gateway();
7732        let (_, _, run) = register(&gateway).await;
7733        let (schema, value) = output(&run, 1);
7734        gateway
7735            .ingest("m-token-that-is-long-enough-for-testing", &run, 0, schema)
7736            .await
7737            .unwrap();
7738        let token = grant(&gateway, AttachMode::Read).await;
7739        let ticket = gateway.exchange_attach_token(&token).await.unwrap();
7740        let mut attachment = gateway.attach(&run, &ticket, 0).await.unwrap();
7741        for sequence in 1..=3 {
7742            let (_, frame) = output(&run, sequence);
7743            gateway
7744                .ingest(
7745                    "m-token-that-is-long-enough-for-testing",
7746                    &run,
7747                    sequence,
7748                    frame,
7749                )
7750                .await
7751                .unwrap();
7752        }
7753        assert!(matches!(
7754            attachment.events.recv().await,
7755            Err(broadcast::error::RecvError::Lagged(_))
7756        ));
7757        gateway.disconnect(attachment).await;
7758        assert!(!value.is_empty());
7759    }
7760
7761    #[tokio::test]
7762    async fn only_the_write_lease_can_submit_valid_input_to_m() {
7763        let gateway = gateway();
7764        let (_, _, run) = register(&gateway).await;
7765        let reader_token = grant(&gateway, AttachMode::Read).await;
7766        let reader_ticket = gateway.exchange_attach_token(&reader_token).await.unwrap();
7767        let reader = gateway.attach(&run, &reader_ticket, 0).await.unwrap();
7768
7769        let input =
7770            TerminalData::new(run.clone(), 1, TerminalDirection::Input, vec![0xff, 0x00]).unwrap();
7771        let (_, input_frame) = terminal_frames(&input).unwrap();
7772        let resize = TerminalResize::new(run.clone(), 2, 120, 40).unwrap();
7773        let (_, resize_frame) = resize_frames(&resize).unwrap();
7774        assert_eq!(
7775            gateway
7776                .submit_input(&run, &reader.connection_id, input_frame.clone())
7777                .await
7778                .unwrap_err(),
7779            GatewayError::Forbidden
7780        );
7781        assert_eq!(
7782            gateway
7783                .submit_input(&run, &reader.connection_id, resize_frame.clone())
7784                .await
7785                .unwrap_err(),
7786            GatewayError::Forbidden
7787        );
7788        gateway.disconnect(reader).await;
7789
7790        let writer_token = grant(&gateway, AttachMode::Write).await;
7791        let writer_ticket = gateway.exchange_attach_token(&writer_token).await.unwrap();
7792        let writer = gateway.attach(&run, &writer_ticket, 0).await.unwrap();
7793        gateway
7794            .submit_input(&run, &writer.connection_id, input_frame)
7795            .await
7796            .unwrap();
7797        gateway
7798            .submit_input(&run, &writer.connection_id, resize_frame)
7799            .await
7800            .unwrap();
7801        let queued = gateway.receive_agent_input().await.unwrap();
7802        assert_eq!(queued.run_id, run);
7803        assert!(!queued.frame.is_empty());
7804        assert!(format!("{queued:?}").contains("[REDACTED;"));
7805        assert!(!format!("{queued:?}").contains("ff00"));
7806        let queued_resize = gateway.receive_agent_input().await.unwrap();
7807        assert_eq!(queued_resize.run_id, run);
7808        assert!(!queued_resize.frame.is_empty());
7809
7810        let stale_resize = TerminalResize::new(queued_resize.run_id.clone(), 1, 80, 24).unwrap();
7811        let (_, stale_resize_frame) = resize_frames(&stale_resize).unwrap();
7812        assert_eq!(
7813            gateway
7814                .submit_input(
7815                    &queued_resize.run_id,
7816                    &writer.connection_id,
7817                    stale_resize_frame
7818                )
7819                .await
7820                .unwrap_err(),
7821            GatewayError::Conflict
7822        );
7823
7824        let duplicate = TerminalData::new(
7825            RunId::new("provider-id-a").unwrap(),
7826            1,
7827            TerminalDirection::Input,
7828            vec![0xff, 0x00],
7829        )
7830        .unwrap();
7831        let (_, duplicate_frame) = terminal_frames(&duplicate).unwrap();
7832        assert_eq!(
7833            gateway
7834                .submit_input(
7835                    &RunId::new("provider-id-a").unwrap(),
7836                    &writer.connection_id,
7837                    duplicate_frame
7838                )
7839                .await
7840                .unwrap_err(),
7841            GatewayError::Conflict
7842        );
7843
7844        let (_, output_frame) = output(&queued.run_id, 3);
7845        assert_eq!(
7846            gateway
7847                .submit_input(&run, &writer.connection_id, output_frame)
7848                .await
7849                .unwrap_err(),
7850            GatewayError::Forbidden
7851        );
7852        gateway.disconnect(writer).await;
7853    }
7854
7855    #[tokio::test]
7856    async fn http_m_publisher_accepts_lifecycle_and_binary_output() {
7857        let gateway = gateway();
7858        let observer = gateway.clone();
7859        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
7860        let address = listener.local_addr().unwrap();
7861        let server = tokio::spawn(async move { axum::serve(listener, gateway.router()).await });
7862        let base = format!("http://{address}");
7863        let client = reqwest::Client::new();
7864        let token = "m-token-that-is-long-enough-for-testing";
7865
7866        let registered = client
7867            .post(format!("{base}/v1/station/runs"))
7868            .bearer_auth(token)
7869            .json(&serde_json::json!({
7870                "operation_id": "station-a",
7871                "mission_id": "mission-a",
7872                "run_id": "provider-id-a",
7873                "mission": {
7874                    "prompt": "Inspect this change",
7875                    "agent_id": "analyst",
7876                    "handler_provider": "claude",
7877                    "terminal_provider": "pty",
7878                    "working_directory": "C:/stations/a",
7879                    "model": "sonnet",
7880                    "effort": "high",
7881                    "environment_keys": ["API_TOKEN"],
7882                    "station_id": "station-a",
7883                    "theater_id": "local",
7884                    "mode": "field"
7885                }
7886            }))
7887            .send()
7888            .await
7889            .unwrap();
7890        assert_eq!(registered.status(), StatusCode::CREATED);
7891        assert_eq!(
7892            registered.json::<serde_json::Value>().await.unwrap()["next_sequence"],
7893            1
7894        );
7895        let mission = observer.board_missions().await.remove(0);
7896        let brief = mission.brief.unwrap();
7897        assert_eq!(brief.prompt, "Inspect this change");
7898        assert_eq!(brief.environment_keys, ["API_TOKEN"]);
7899        assert_eq!(brief.station_id, "station-a");
7900
7901        let lifecycle = client
7902            .post(format!("{base}/v1/station/runs/provider-id-a/lifecycle/1"))
7903            .bearer_auth(token)
7904            .json(&serde_json::json!({
7905                "operation_id": "station-a",
7906                "mission_id": "mission-a",
7907                "state": "failed"
7908            }))
7909            .send()
7910            .await
7911            .unwrap();
7912        assert_eq!(lifecycle.status(), StatusCode::ACCEPTED);
7913
7914        let board = client.get(format!("{base}/v1/board")).send().await.unwrap();
7915        assert_eq!(board.status(), StatusCode::UNAUTHORIZED);
7916
7917        let terminal = client
7918            .post(format!("{base}/v1/station/runs/provider-id-a/terminal/2"))
7919            .bearer_auth(token)
7920            .body(vec![0xff, 0x00, 0x80])
7921            .send()
7922            .await
7923            .unwrap();
7924        assert_eq!(terminal.status(), StatusCode::ACCEPTED);
7925
7926        let resumed = client
7927            .post(format!("{base}/v1/station/runs"))
7928            .bearer_auth(token)
7929            .json(&serde_json::json!({
7930                "operation_id": "station-a",
7931                "mission_id": "mission-a",
7932                "run_id": "provider-id-a"
7933            }))
7934            .send()
7935            .await
7936            .unwrap();
7937        assert_eq!(resumed.status(), StatusCode::CREATED);
7938        assert_eq!(
7939            resumed.json::<serde_json::Value>().await.unwrap()["next_sequence"],
7940            3
7941        );
7942
7943        // A Run a provider limit paused is a board state of its own.
7944        let parked = client
7945            .post(format!("{base}/v1/station/runs/provider-id-a/lifecycle/3"))
7946            .bearer_auth(token)
7947            .json(&serde_json::json!({
7948                "operation_id": "station-a",
7949                "mission_id": "mission-a",
7950                "state": "parked"
7951            }))
7952            .send()
7953            .await
7954            .unwrap();
7955        assert_eq!(parked.status(), StatusCode::ACCEPTED);
7956        let run = observer.board_missions().await.remove(0).runs.remove(0);
7957        assert_eq!(run.state.as_deref(), Some("parked"));
7958        let unknown = client
7959            .post(format!("{base}/v1/station/runs/provider-id-a/lifecycle/4"))
7960            .bearer_auth(token)
7961            .json(&serde_json::json!({
7962                "operation_id": "station-a",
7963                "mission_id": "mission-a",
7964                "state": "paused"
7965            }))
7966            .send()
7967            .await
7968            .unwrap();
7969        assert_eq!(unknown.status(), StatusCode::BAD_REQUEST);
7970
7971        let denied = client
7972            .post(format!("{base}/v1/station/runs/provider-id-a/lifecycle/4"))
7973            .json(&serde_json::json!({
7974                "operation_id": "station-a",
7975                "mission_id": "mission-a",
7976                "state": "done"
7977            }))
7978            .send()
7979            .await
7980            .unwrap();
7981        assert_eq!(denied.status(), StatusCode::UNAUTHORIZED);
7982        server.abort();
7983    }
7984
7985    /// The step a password sign-in of Alice's passed.
7986    fn password_steps() -> Vec<SignInFactor> {
7987        vec![SignInFactor::try_new("password", None, Some("alice-id".to_owned())).unwrap()]
7988    }
7989
7990    struct OneAccount;
7991
7992    impl Authenticator for OneAccount {
7993        fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
7994            Ok(
7995                if attempt.name.as_deref() == Some("alice")
7996                    && attempt.secret.as_deref() == Some("right")
7997                {
7998                    Verdict::Valid(Lookup {
7999                        by: "name".to_owned(),
8000                        value: "alice".to_owned(),
8001                        ..Default::default()
8002                    })
8003                } else {
8004                    Verdict::Invalid
8005                },
8006            )
8007        }
8008    }
8009
8010    impl Directory for OneAccount {
8011        fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
8012            Ok((lookup.value == "alice").then(|| Person {
8013                id: "alice-id".to_owned(),
8014                name: "alice".to_owned(),
8015                ..Person::default()
8016            }))
8017        }
8018    }
8019
8020    async fn login_gateway(
8021        limits: LoginLimits,
8022    ) -> (String, tokio::task::JoinHandle<()>, tempfile::TempDir) {
8023        let config = GatewayConfig::new(
8024            "https://localhost",
8025            "m-token-that-is-long-enough-for-testing",
8026            test_limits(),
8027            Duration::from_secs(30),
8028            Duration::from_secs(30),
8029        )
8030        .unwrap()
8031        .with_login_limits(limits);
8032        let directory = tempfile::tempdir().unwrap();
8033        let registry = FileRegistry::open(directory.path());
8034        let gateway = Gateway::with_access(
8035            config,
8036            Arc::new(registry),
8037            AccessProviders::new(
8038                Arc::new(OneAccount),
8039                Arc::new(OneAccount),
8040                Arc::new(RoleAuthorizer::default()),
8041            ),
8042        );
8043        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8044        let base = format!("http://{}", listener.local_addr().unwrap());
8045        let server = tokio::spawn(async move {
8046            let _ = axum::serve(
8047                listener,
8048                gateway
8049                    .router()
8050                    .into_make_service_with_connect_info::<SocketAddr>(),
8051            )
8052            .await;
8053        });
8054        (base, server, directory)
8055    }
8056
8057    async fn try_login(
8058        client: &reqwest::Client,
8059        base: &str,
8060        name: &str,
8061        secret: &str,
8062        client_address: Option<&str>,
8063    ) -> reqwest::Response {
8064        let mut request = client
8065            .post(format!("{base}/v1/auth/login"))
8066            .json(&serde_json::json!({"name": name, "secret": secret}));
8067        if let Some(address) = client_address {
8068            request = request.header("x-forwarded-for", address);
8069        }
8070        request.send().await.unwrap()
8071    }
8072
8073    /// An authenticator that reads the request and takes no name or secret.
8074    struct ByRequest;
8075
8076    impl Authenticator for ByRequest {
8077        fn authenticate(&self, _: Attempt) -> Result<Verdict, ProviderError> {
8078            Ok(Verdict::Invalid)
8079        }
8080
8081        fn describe(&self) -> Result<ai6::Description, ProviderError> {
8082            Ok(ai6::Description {
8083                takes: Some(ai6::directorates::m::access::takes::REQUEST.to_owned()),
8084                ..ai6::Description::default()
8085            })
8086        }
8087    }
8088
8089    #[tokio::test]
8090    async fn auth_methods_say_what_login_accepts_and_need_no_token() {
8091        let header = || HeaderName::from_static("x-forwarded-user");
8092        let provided = |access: AccessProviders| async move {
8093            let config = GatewayConfig::new(
8094                "https://localhost",
8095                "m-token-that-is-long-enough-for-testing",
8096                test_limits(),
8097                Duration::from_secs(30),
8098                Duration::from_secs(30),
8099            )
8100            .unwrap();
8101            let directory = tempfile::tempdir().unwrap();
8102            let registry = Arc::new(FileRegistry::open(directory.path()));
8103            let gateway = Gateway::with_access(config, registry, access);
8104            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8105            let base = format!("http://{}", listener.local_addr().unwrap());
8106            let server = tokio::spawn(async move {
8107                let _ = axum::serve(listener, gateway.router()).await;
8108            });
8109            let answer: serde_json::Value = reqwest::get(format!("{base}/v1/auth/methods"))
8110                .await
8111                .unwrap()
8112                .json()
8113                .await
8114                .unwrap();
8115            server.abort();
8116            answer["methods"].clone()
8117        };
8118        let authorizer = || Arc::new(RoleAuthorizer::default());
8119        assert_eq!(
8120            provided(AccessProviders::new(
8121                Arc::new(OneAccount),
8122                Arc::new(OneAccount),
8123                authorizer(),
8124            ))
8125            .await,
8126            serde_json::json!(["password"])
8127        );
8128        assert_eq!(
8129            provided(
8130                AccessProviders::new(Arc::new(OneAccount), Arc::new(OneAccount), authorizer())
8131                    .with_proxy_identity(header(), "name")
8132            )
8133            .await,
8134            serde_json::json!(["password", "proxy"])
8135        );
8136        assert_eq!(
8137            provided(AccessProviders::from_reverse_proxy(
8138                Arc::new(OneAccount),
8139                authorizer(),
8140                header(),
8141                "name",
8142            ))
8143            .await,
8144            serde_json::json!(["proxy"])
8145        );
8146        assert_eq!(
8147            provided(AccessProviders::new(
8148                Arc::new(ByRequest),
8149                Arc::new(OneAccount),
8150                authorizer(),
8151            ))
8152            .await,
8153            serde_json::json!([])
8154        );
8155    }
8156
8157    /// Alice, until `gone` is set: the directory answers for her no longer.
8158    pub(super) struct Leaving {
8159        pub(super) gone: Arc<std::sync::atomic::AtomicBool>,
8160    }
8161
8162    impl Authenticator for Leaving {
8163        fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
8164            OneAccount.authenticate(attempt)
8165        }
8166    }
8167
8168    impl Directory for Leaving {
8169        fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
8170            if lookup.value == "bob" {
8171                return Ok(Some(Person {
8172                    id: "bob-id".to_owned(),
8173                    name: "bob".to_owned(),
8174                    ..Person::default()
8175                }));
8176            }
8177            let known = ["alice", "alice-id"].contains(&lookup.value.as_str());
8178            Ok(
8179                (known && !self.gone.load(std::sync::atomic::Ordering::SeqCst)).then(|| Person {
8180                    id: "alice-id".to_owned(),
8181                    name: "alice".to_owned(),
8182                    ..Person::default()
8183                }),
8184            )
8185        }
8186    }
8187
8188    /// A gateway under `change`d `[gateway]` limits, for what signing in and renewing do.
8189    struct Signing {
8190        base: String,
8191        registry: FileRegistry,
8192        gone: Arc<std::sync::atomic::AtomicBool>,
8193        server: tokio::task::JoinHandle<()>,
8194        _directory: tempfile::TempDir,
8195    }
8196
8197    impl Drop for Signing {
8198        fn drop(&mut self) {
8199            self.server.abort();
8200        }
8201    }
8202
8203    #[test]
8204    fn what_a_gateway_accepts_of_a_mission_and_an_audit_page_are_settings() {
8205        let text = ai6::TextLimits::default();
8206        assert!(mission_text_fits(
8207            &"t".repeat(512),
8208            &"p".repeat(65_536),
8209            &text
8210        ));
8211        assert!(!mission_text_fits(&"t".repeat(513), "p", &text));
8212        assert!(!mission_text_fits("t", &"p".repeat(65_537), &text));
8213        assert!(!mission_text_fits(" ", "p", &text));
8214        let mut wider = text.clone();
8215        wider.mission_title_chars = ai6::Limit::UNBOUNDED;
8216        wider.mission_prompt_bytes = ai6::Limit::at(1);
8217        assert!(mission_text_fits(&"t".repeat(5_000), "p", &wider));
8218        assert!(!mission_text_fits("t", "pp", &wider));
8219
8220        let mut pages = ai6::UnexTimelineLimits::default();
8221        assert_eq!(audit_page(None, &pages), Some(100));
8222        assert_eq!(audit_page(Some(500), &pages), Some(500));
8223        assert_eq!(audit_page(Some(501), &pages), None);
8224        assert_eq!(audit_page(Some(0), &pages), None);
8225        pages.audit_page = 7;
8226        pages.max_audit_page = ai6::Limit::UNBOUNDED;
8227        assert_eq!(audit_page(None, &pages), Some(7));
8228        assert_eq!(audit_page(Some(9_000), &pages), Some(9_000));
8229    }
8230
8231    #[test]
8232    fn the_gateway_s_own_limits_default_to_the_record_s() {
8233        let limits = GatewayLimits::default();
8234        assert_eq!(limits.max_runs, 16);
8235        assert_eq!(limits.max_clients_per_run, 12);
8236        assert_eq!(limits.scrollback_events, 64);
8237        assert_eq!(limits.max_frame_bytes, 256 * 1024);
8238        assert_eq!(limits.max_input_frames_per_second, 40);
8239        assert_eq!(limits.input_queue_capacity, 64);
8240        assert_eq!(limits.fanout_capacity, 8);
8241        assert_eq!(
8242            limits.buffer_budget_bytes,
8243            ai6::Limit::at(512 * 1024 * 1024)
8244        );
8245        assert_eq!(limits.client_slots, ai6::Limit::at(100_000));
8246        assert_eq!(limits.socket_buffer_bytes, 256 * 1024);
8247        assert_eq!(limits.station_token_min_bytes, 32);
8248        assert_eq!(limits.origin_bytes, ai6::Limit::at(2048));
8249        let login = LoginLimits::default();
8250        assert_eq!(login.name_bytes, 64);
8251        assert_eq!(login.forget_every, 256);
8252        assert_eq!(login.address_window, Duration::from_secs(60));
8253        assert_eq!(login.name_window, Duration::from_secs(600));
8254    }
8255
8256    impl Signing {
8257        async fn new(change: impl FnOnce(&mut ai6::UnexGatewayLimits)) -> Self {
8258            Self::built(change, LoginLimits::default(), |providers| providers).await
8259        }
8260
8261        async fn built(
8262            change: impl FnOnce(&mut ai6::UnexGatewayLimits),
8263            login: LoginLimits,
8264            providers: impl FnOnce(AccessProviders) -> AccessProviders,
8265        ) -> Self {
8266            let mut limits = ai6::UnexLimits::default();
8267            // The idle limit is its own tests': the others judge renewal by the cap alone.
8268            limits.gateway.session_idle = TimeLimit::UNBOUNDED;
8269            change(&mut limits.gateway);
8270            let config = GatewayConfig::new(
8271                "https://localhost",
8272                "m-token-that-is-long-enough-for-testing",
8273                test_limits(),
8274                Duration::from_secs(30),
8275                Duration::from_secs(30),
8276            )
8277            .unwrap()
8278            .with_unex_limits(limits)
8279            .with_login_limits(login);
8280            let directory = tempfile::tempdir().unwrap();
8281            let registry = FileRegistry::open(directory.path());
8282            let gone = Arc::new(std::sync::atomic::AtomicBool::new(false));
8283            let people = Arc::new(Leaving { gone: gone.clone() });
8284            let gateway = Gateway::with_access(
8285                config,
8286                Arc::new(registry.clone()),
8287                providers(AccessProviders::new(
8288                    people.clone(),
8289                    people,
8290                    Arc::new(RoleAuthorizer::default()),
8291                )),
8292            );
8293            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8294            let base = format!("http://{}", listener.local_addr().unwrap());
8295            let server = tokio::spawn(async move {
8296                let _ = axum::serve(
8297                    listener,
8298                    gateway
8299                        .router()
8300                        .into_make_service_with_connect_info::<SocketAddr>(),
8301                )
8302                .await;
8303            });
8304            Self {
8305                base,
8306                registry,
8307                gone,
8308                server,
8309                _directory: directory,
8310            }
8311        }
8312
8313        /// Signs in as Alice, naming the lifetime when `ttl_seconds` does.
8314        async fn login(&self, ttl_seconds: Option<u64>) -> reqwest::Response {
8315            let mut body = serde_json::json!({"name": "alice", "secret": "right"});
8316            if let Some(ttl_seconds) = ttl_seconds {
8317                body["ttl_seconds"] = ttl_seconds.into();
8318            }
8319            reqwest::Client::new()
8320                .post(format!("{}/v1/auth/login", self.base))
8321                .json(&body)
8322                .send()
8323                .await
8324                .unwrap()
8325        }
8326
8327        async fn renew(&self, token: &str) -> reqwest::Response {
8328            reqwest::Client::new()
8329                .post(format!("{}/v1/auth/renew", self.base))
8330                .bearer_auth(token)
8331                .send()
8332                .await
8333                .unwrap()
8334        }
8335
8336        /// A token of Alice's with these times, returning its value.
8337        fn token(&self, issued_at: f64, expires_at: f64) -> String {
8338            let token = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
8339            let record = AccessTokenRecord::try_new(
8340                Uuid::new_v4().to_string(),
8341                access_token_digest(&token),
8342                "alice-id",
8343                issued_at,
8344                expires_at,
8345                None,
8346            )
8347            .unwrap()
8348            .with_factors(password_steps());
8349            self.registry.store_access_token(&record).unwrap();
8350            token
8351        }
8352
8353        async fn session(&self, token: &str) -> reqwest::Response {
8354            reqwest::Client::new()
8355                .get(format!("{}/v1/auth/session", self.base))
8356                .bearer_auth(token)
8357                .send()
8358                .await
8359                .unwrap()
8360        }
8361
8362        /// A POST as the app's own page sends one.
8363        fn page_post(&self, path: &str) -> reqwest::RequestBuilder {
8364            reqwest::Client::new()
8365                .post(format!("{}{path}", self.base))
8366                .header(ORIGIN, "https://localhost")
8367                .header("x-forwarded-proto", "https")
8368        }
8369
8370        /// Signs in as Alice from the app's page, returning the answer's body and the cookie as
8371        /// a browser would send it back.
8372        async fn web_login(&self) -> (serde_json::Value, String) {
8373            let response = self
8374                .page_post("/v1/auth/login")
8375                .json(&serde_json::json!({"name": "alice", "secret": "right"}))
8376                .send()
8377                .await
8378                .unwrap();
8379            assert_eq!(response.status(), StatusCode::CREATED);
8380            let cookie = set_cookie_of(&response)
8381                .expect("a web sign-in gets a cookie")
8382                .split(';')
8383                .next()
8384                .unwrap()
8385                .to_owned();
8386            (response.json().await.unwrap(), cookie)
8387        }
8388
8389        async fn resume(&self, cookie: &str) -> reqwest::Response {
8390            self.page_post("/v1/auth/resume")
8391                .header(COOKIE, cookie)
8392                .send()
8393                .await
8394                .unwrap()
8395        }
8396
8397        /// A session cookie of Alice's with these times, returning it as a browser sends it.
8398        fn cookie(&self, issued_at: f64, expires_at: f64) -> String {
8399            let value = new_secret();
8400            let record = AccessTokenRecord::try_new(
8401                Uuid::new_v4().to_string(),
8402                session_cookie_digest(&value),
8403                "alice-id",
8404                issued_at,
8405                expires_at,
8406                None,
8407            )
8408            .unwrap()
8409            .with_factors(password_steps())
8410            .into_session_cookie();
8411            self.registry.store_access_token(&record).unwrap();
8412            format!("{SESSION_COOKIE}={value}")
8413        }
8414
8415        /// The record of a token value, while it stands.
8416        fn record_of(&self, token: &str) -> Option<AccessTokenRecord> {
8417            self.registry
8418                .find_access_token(&access_token_digest(token))
8419                .unwrap()
8420        }
8421    }
8422
8423    fn set_cookie_of(response: &reqwest::Response) -> Option<String> {
8424        response
8425            .headers()
8426            .get(SET_COOKIE)
8427            .map(|value| value.to_str().unwrap().to_owned())
8428    }
8429
8430    /// Says the response tells the browser to drop the session cookie.
8431    fn assert_clears_cookie(response: &reqwest::Response) {
8432        let set = set_cookie_of(response).expect("the cookie is cleared");
8433        assert!(set.starts_with("ai6_session=;"), "{set}");
8434        assert!(set.contains("Path=/v1/auth"), "{set}");
8435        assert!(set.contains("Max-Age=0"), "{set}");
8436    }
8437
8438    async fn body_of(response: reqwest::Response) -> serde_json::Value {
8439        assert_eq!(response.status(), StatusCode::OK);
8440        response.json().await.unwrap()
8441    }
8442
8443    fn time_in(body: &serde_json::Value, key: &str) -> f64 {
8444        body[key]
8445            .as_f64()
8446            .unwrap_or_else(|| panic!("{key} in {body}"))
8447    }
8448
8449    #[tokio::test]
8450    async fn renewal_keeps_the_same_token_up_to_the_cap() {
8451        let signing = Signing::new(|gateway| {
8452            gateway.access_token_ttl = ai6::Seconds::new(3_600);
8453            gateway.session_max = TimeLimit::secs(7_200);
8454        })
8455        .await;
8456        let before = unix_timestamp().ok().unwrap();
8457
8458        // Signing in says when the token ends and when renewing does.
8459        let signed_in: serde_json::Value = signing.login(None).await.json().await.unwrap();
8460        let expires_at = time_in(&signed_in, "expires_at");
8461        assert!(expires_at >= before + 3_600.0, "{signed_in}");
8462        assert!(
8463            (time_in(&signed_in, "expires_in") - 3_600.0).abs() < 1e-3,
8464            "{signed_in}"
8465        );
8466        assert!(
8467            (time_in(&signed_in, "ends_at") - (expires_at + 3_600.0)).abs() < 1e-3,
8468            "{signed_in}"
8469        );
8470
8471        // A renewal gives a whole lifetime from now, with the same token and no secret.
8472        let token = signing.token(before - 10.0, before + 120.0);
8473        let id = body_of(signing.session(&token).await).await["token_id"].clone();
8474        let renewed = body_of(signing.renew(&token).await).await;
8475        assert_eq!(renewed["token_id"], id);
8476        assert!(renewed.get("token").is_none(), "{renewed}");
8477        let renewed_until = time_in(&renewed, "expires_at");
8478        assert!(renewed_until >= before + 3_600.0, "{renewed}");
8479        let left = time_in(&renewed, "expires_in");
8480        assert!((3_590.0..=3_600.0).contains(&left), "{renewed}");
8481        assert!(
8482            (time_in(&renewed, "ends_at") - (before - 10.0 + 7_200.0)).abs() < 1e-3,
8483            "{renewed}"
8484        );
8485        let run = body_of(signing.session(&token).await).await;
8486        assert_eq!(run["token_id"], id);
8487        assert!((time_in(&run, "expires_at") - renewed_until).abs() < 1e-3);
8488
8489        // Near the cap it stops there, and again it stays there.
8490        let issued_at = before - 5_000.0;
8491        let token = signing.token(issued_at, before + 120.0);
8492        for _ in 0..2 {
8493            let capped = body_of(signing.renew(&token).await).await;
8494            assert!(
8495                (time_in(&capped, "expires_at") - (issued_at + 7_200.0)).abs() < 1e-3,
8496                "{capped}"
8497            );
8498            assert!(
8499                (time_in(&capped, "ends_at") - (issued_at + 7_200.0)).abs() < 1e-3,
8500                "{capped}"
8501            );
8502        }
8503
8504        // A browser's renewal must come from the public origin, like its sign-in.
8505        let foreign = reqwest::Client::new()
8506            .post(format!("{}/v1/auth/renew", signing.base))
8507            .bearer_auth(&token)
8508            .header(ORIGIN, "https://elsewhere.example")
8509            .header("x-forwarded-proto", "https")
8510            .send()
8511            .await
8512            .unwrap();
8513        assert_eq!(foreign.status(), StatusCode::FORBIDDEN);
8514        let own = reqwest::Client::new()
8515            .post(format!("{}/v1/auth/renew", signing.base))
8516            .bearer_auth(&token)
8517            .header(ORIGIN, "https://localhost")
8518            .header("x-forwarded-proto", "https")
8519            .send()
8520            .await
8521            .unwrap();
8522        assert_eq!(own.status(), StatusCode::OK);
8523    }
8524
8525    #[tokio::test]
8526    async fn run_max_turns_renewal_off_or_lets_it_run_on() {
8527        let off = Signing::new(|gateway| gateway.session_max = TimeLimit::secs(0)).await;
8528        let signed_in: serde_json::Value = off.login(None).await.json().await.unwrap();
8529        let expires_at = time_in(&signed_in, "expires_at");
8530        assert!(
8531            (time_in(&signed_in, "ends_at") - expires_at).abs() < 1e-3,
8532            "it ends when the token does: {signed_in}"
8533        );
8534        let token = signed_in["token"].as_str().unwrap();
8535        let renewed = body_of(off.renew(token).await).await;
8536        assert!((time_in(&renewed, "expires_at") - expires_at).abs() < 1e-3);
8537
8538        let unbound = Signing::new(|gateway| gateway.session_max = TimeLimit::UNBOUNDED).await;
8539        let now = unix_timestamp().ok().unwrap();
8540        let token = unbound.token(now - 1_000_000.0, now + 120.0);
8541        let renewed = body_of(unbound.renew(&token).await).await;
8542        assert!(renewed["ends_at"].is_null(), "{renewed}");
8543        assert!(
8544            time_in(&renewed, "expires_at") >= now + 3_600.0,
8545            "{renewed}"
8546        );
8547    }
8548
8549    #[tokio::test]
8550    async fn a_requested_lifetime_is_bound_by_the_setting_and_has_no_floor() {
8551        let signing = Signing::new(|gateway| {
8552            gateway.access_token_max_ttl = TimeLimit::secs(100);
8553            gateway.access_token_ttl = ai6::Seconds::new(50);
8554        })
8555        .await;
8556        let before = unix_timestamp().ok().unwrap();
8557        let default: serde_json::Value = signing.login(None).await.json().await.unwrap();
8558        assert!(
8559            time_in(&default, "expires_at") < before + 100.0,
8560            "{default}"
8561        );
8562        assert_eq!(signing.login(Some(1)).await.status(), StatusCode::CREATED);
8563        assert_eq!(signing.login(Some(100)).await.status(), StatusCode::CREATED);
8564        assert_eq!(
8565            signing.login(Some(101)).await.status(),
8566            StatusCode::BAD_REQUEST
8567        );
8568        assert_eq!(
8569            signing.login(Some(0)).await.status(),
8570            StatusCode::BAD_REQUEST
8571        );
8572        let issued = reqwest::Client::new()
8573            .post(format!("{}/v1/station/access-tokens", signing.base))
8574            .bearer_auth("m-token-that-is-long-enough-for-testing")
8575            .json(&serde_json::json!({"person_id": "alice-id", "ttl_seconds": 101}))
8576            .send()
8577            .await
8578            .unwrap();
8579        assert_eq!(issued.status(), StatusCode::BAD_REQUEST);
8580    }
8581
8582    #[tokio::test]
8583    async fn a_revoked_or_expired_token_cannot_renew() {
8584        let signing = Signing::new(|_| {}).await;
8585        let now = unix_timestamp().ok().unwrap();
8586        let expired = signing.token(now - 7_200.0, now - 3_600.0);
8587        assert_eq!(
8588            signing.renew(&expired).await.status(),
8589            StatusCode::UNAUTHORIZED
8590        );
8591        assert_eq!(
8592            signing.session(&expired).await.status(),
8593            StatusCode::UNAUTHORIZED,
8594            "and it is still over"
8595        );
8596
8597        let signed_in: serde_json::Value = signing.login(None).await.json().await.unwrap();
8598        let token = signed_in["token"].as_str().unwrap();
8599        assert_eq!(signing.renew(token).await.status(), StatusCode::OK);
8600        let signed_out = reqwest::Client::new()
8601            .post(format!("{}/v1/auth/logout", signing.base))
8602            .bearer_auth(token)
8603            .send()
8604            .await
8605            .unwrap();
8606        assert_eq!(signed_out.status(), StatusCode::NO_CONTENT);
8607        assert_eq!(
8608            signing.renew(token).await.status(),
8609            StatusCode::UNAUTHORIZED
8610        );
8611        assert_eq!(
8612            signing.session(token).await.status(),
8613            StatusCode::UNAUTHORIZED,
8614            "and it stays revoked"
8615        );
8616
8617        assert_eq!(
8618            signing.renew("made-up").await.status(),
8619            StatusCode::UNAUTHORIZED
8620        );
8621        let no_token = reqwest::Client::new()
8622            .post(format!("{}/v1/auth/renew", signing.base))
8623            .send()
8624            .await
8625            .unwrap();
8626        assert_eq!(no_token.status(), StatusCode::UNAUTHORIZED);
8627    }
8628
8629    #[tokio::test]
8630    async fn a_person_gone_from_the_directory_cannot_renew() {
8631        let signing = Signing::new(|_| {}).await;
8632        let now = unix_timestamp().ok().unwrap();
8633        let first = now + 600.0;
8634        let token = signing.token(now - 10.0, first);
8635        assert_eq!(signing.renew(&token).await.status(), StatusCode::OK);
8636        let held = time_in(&body_of(signing.session(&token).await).await, "expires_at");
8637
8638        signing
8639            .gone
8640            .store(true, std::sync::atomic::Ordering::SeqCst);
8641        assert_eq!(
8642            signing.renew(&token).await.status(),
8643            StatusCode::UNAUTHORIZED
8644        );
8645        let unmoved = time_in(&body_of(signing.session(&token).await).await, "expires_at");
8646        assert!((unmoved - held).abs() < 1e-3, "nothing moved");
8647    }
8648
8649    #[tokio::test]
8650    async fn a_web_login_sets_exactly_the_session_cookie_and_keeps_only_its_digest() {
8651        let signing = Signing::new(|gateway| gateway.session_max = TimeLimit::secs(7_200)).await;
8652        let response = signing
8653            .page_post("/v1/auth/login")
8654            .json(&serde_json::json!({"name": "alice", "secret": "right"}))
8655            .send()
8656            .await
8657            .unwrap();
8658        assert_eq!(response.status(), StatusCode::CREATED);
8659        let set = set_cookie_of(&response).unwrap();
8660        let mut parts = set.split("; ");
8661        let (name, value) = parts.next().unwrap().split_once('=').unwrap();
8662        assert_eq!(name, "ai6_session");
8663        assert_eq!(value.len(), 64, "{set}");
8664        assert_eq!(
8665            parts.collect::<Vec<_>>(),
8666            [
8667                "Path=/v1/auth",
8668                "HttpOnly",
8669                "Secure",
8670                "SameSite=Strict",
8671                "Max-Age=7200"
8672            ]
8673        );
8674        let body: serde_json::Value = response.json().await.unwrap();
8675        let token = body["token"].as_str().unwrap();
8676        assert_ne!(token, value);
8677
8678        // Its record ends with the sign-in and holds only the digest, and the bearer names it.
8679        let record = signing
8680            .registry
8681            .find_session_cookie(&session_cookie_digest(value))
8682            .unwrap()
8683            .unwrap();
8684        assert!((record.expires_at() - (record.issued_at() + 7_200.0)).abs() < 1e-3);
8685        let bearer = signing.record_of(token).unwrap();
8686        assert_eq!(bearer.sign_in(), Some(record.token_id()));
8687        assert!((bearer.issued_at() - record.issued_at()).abs() < 1e-6);
8688        for entry in std::fs::read_dir(signing._directory.path().join("access-tokens")).unwrap() {
8689            let text = std::fs::read_to_string(entry.unwrap().path()).unwrap();
8690            assert!(!text.contains(value), "the value is never written");
8691        }
8692
8693        // A client that is no browser, and a page that asks not to, get none.
8694        let api = signing.login(None).await;
8695        assert_eq!(api.status(), StatusCode::CREATED);
8696        assert!(set_cookie_of(&api).is_none());
8697        let api: serde_json::Value = api.json().await.unwrap();
8698        let bearer = signing.record_of(api["token"].as_str().unwrap()).unwrap();
8699        assert_eq!(bearer.sign_in(), None);
8700        let declined = signing
8701            .page_post("/v1/auth/login")
8702            .json(&serde_json::json!({
8703                "name": "alice", "secret": "right", "session_cookie": false
8704            }))
8705            .send()
8706            .await
8707            .unwrap();
8708        assert_eq!(declined.status(), StatusCode::CREATED);
8709        assert!(set_cookie_of(&declined).is_none());
8710
8711        // A failed sign-in gets none.
8712        let refused = signing
8713            .page_post("/v1/auth/login")
8714            .json(&serde_json::json!({"name": "alice", "secret": "wrong"}))
8715            .send()
8716            .await
8717            .unwrap();
8718        assert_eq!(refused.status(), StatusCode::UNAUTHORIZED);
8719        assert!(set_cookie_of(&refused).is_none());
8720    }
8721
8722    #[tokio::test]
8723    async fn a_resume_answers_as_login_does_with_a_new_token_of_the_same_sign_in() {
8724        let signing = Signing::new(|gateway| {
8725            gateway.access_token_ttl = ai6::Seconds::new(3_600);
8726            gateway.session_max = TimeLimit::secs(7_200);
8727        })
8728        .await;
8729        let (signed_in, cookie) = signing.web_login().await;
8730        let first = signed_in["token"].as_str().unwrap();
8731
8732        let resumed = signing.resume(&cookie).await;
8733        assert_eq!(resumed.status(), StatusCode::CREATED);
8734        assert!(
8735            set_cookie_of(&resumed).is_none(),
8736            "the cookie stays as it is"
8737        );
8738        let resumed: serde_json::Value = resumed.json().await.unwrap();
8739        let second = resumed["token"].as_str().unwrap();
8740        assert_ne!(second, first);
8741        assert!((3_590.0..=3_600.0).contains(&time_in(&resumed, "expires_in")));
8742        assert!(time_in(&resumed, "expires_at") > time_in(&signed_in, "expires_at") - 1e-3);
8743        assert!(
8744            (time_in(&resumed, "ends_at") - time_in(&signed_in, "ends_at")).abs() < 1e-3,
8745            "it ends when the sign-in does: {resumed}"
8746        );
8747        let run = body_of(signing.session(second).await).await;
8748        assert_eq!(run["person_id"], "alice-id");
8749        assert_eq!(run["token_id"], resumed["token_id"]);
8750        assert_eq!(
8751            signing.session(first).await.status(),
8752            StatusCode::OK,
8753            "another tab's token carries on"
8754        );
8755        let first = signing.record_of(first).unwrap();
8756        let second = signing.record_of(second).unwrap();
8757        assert_eq!(second.sign_in(), first.sign_in());
8758        assert!((second.issued_at() - first.issued_at()).abs() < 1e-6);
8759    }
8760
8761    #[tokio::test]
8762    async fn a_resume_cannot_pass_the_cap_of_the_original_sign_in() {
8763        let signing = Signing::new(|gateway| {
8764            gateway.access_token_ttl = ai6::Seconds::new(3_600);
8765            gateway.session_max = TimeLimit::secs(7_200);
8766        })
8767        .await;
8768        let now = unix_timestamp().ok().unwrap();
8769
8770        // A hundred seconds of the sign-in left: the token gets those and no more, however many
8771        // times it is resumed, and renewing it cannot move it past them.
8772        let issued_at = now - 7_100.0;
8773        let ends = issued_at + 7_200.0;
8774        let cookie = signing.cookie(issued_at, ends);
8775        for _ in 0..2 {
8776            let resumed = signing.resume(&cookie).await;
8777            assert_eq!(resumed.status(), StatusCode::CREATED);
8778            let resumed: serde_json::Value = resumed.json().await.unwrap();
8779            assert!(
8780                (time_in(&resumed, "expires_at") - ends).abs() < 1e-3,
8781                "{resumed}"
8782            );
8783            assert!(
8784                (time_in(&resumed, "ends_at") - ends).abs() < 1e-3,
8785                "{resumed}"
8786            );
8787            assert!(time_in(&resumed, "expires_in") <= 100.0, "{resumed}");
8788            let renewed = body_of(signing.renew(resumed["token"].as_str().unwrap()).await).await;
8789            assert!(
8790                (time_in(&renewed, "expires_at") - ends).abs() < 1e-3,
8791                "{renewed}"
8792            );
8793        }
8794
8795        // Past it: refused and cleared.
8796        let over = signing.cookie(now - 7_300.0, now - 100.0);
8797        let refused = signing.resume(&over).await;
8798        assert_eq!(refused.status(), StatusCode::UNAUTHORIZED);
8799        assert_clears_cookie(&refused);
8800
8801        // A cookie written to last longer stops when `session_max` now says, lowered since.
8802        let lowered = signing.cookie(now - 7_300.0, now + 10_000.0);
8803        assert_eq!(
8804            signing.resume(&lowered).await.status(),
8805            StatusCode::UNAUTHORIZED
8806        );
8807
8808        // With no bound there is nothing to pass, and the cookie says the longest it can.
8809        let unbound = Signing::new(|gateway| gateway.session_max = TimeLimit::UNBOUNDED).await;
8810        let response = unbound
8811            .page_post("/v1/auth/login")
8812            .json(&serde_json::json!({"name": "alice", "secret": "right"}))
8813            .send()
8814            .await
8815            .unwrap();
8816        let set = set_cookie_of(&response).unwrap();
8817        assert!(set.ends_with(&format!("Max-Age={}", u32::MAX)), "{set}");
8818        let cookie = set.split(';').next().unwrap();
8819        let resumed = unbound.resume(cookie).await;
8820        assert_eq!(resumed.status(), StatusCode::CREATED);
8821        let resumed: serde_json::Value = resumed.json().await.unwrap();
8822        assert!(resumed["ends_at"].is_null(), "{resumed}");
8823    }
8824
8825    #[tokio::test]
8826    async fn a_revoked_sign_in_or_a_person_gone_cannot_resume() {
8827        let signing = Signing::new(|_| {}).await;
8828        let (signed_in, cookie) = signing.web_login().await;
8829        let resumed: serde_json::Value = signing.resume(&cookie).await.json().await.unwrap();
8830
8831        // What Stations revoke by: the ID of any token of the sign-in.
8832        let revoked = reqwest::Client::new()
8833            .delete(format!(
8834                "{}/v1/station/access-tokens/{}",
8835                signing.base,
8836                signed_in["token_id"].as_str().unwrap()
8837            ))
8838            .bearer_auth("m-token-that-is-long-enough-for-testing")
8839            .send()
8840            .await
8841            .unwrap();
8842        assert_eq!(revoked.status(), StatusCode::OK);
8843        let refused = signing.resume(&cookie).await;
8844        assert_eq!(refused.status(), StatusCode::UNAUTHORIZED);
8845        assert_clears_cookie(&refused);
8846        assert_eq!(
8847            signing
8848                .session(resumed["token"].as_str().unwrap())
8849                .await
8850                .status(),
8851            StatusCode::UNAUTHORIZED,
8852            "the token a resume gave goes with it"
8853        );
8854
8855        let (_, cookie) = signing.web_login().await;
8856        signing
8857            .gone
8858            .store(true, std::sync::atomic::Ordering::SeqCst);
8859        let refused = signing.resume(&cookie).await;
8860        assert_eq!(refused.status(), StatusCode::UNAUTHORIZED);
8861        assert_clears_cookie(&refused);
8862    }
8863
8864    #[tokio::test]
8865    async fn renewals_within_the_idle_limit_keep_a_sign_in_alive_past_twelve_hours() {
8866        let signing = Signing::new(|gateway| {
8867            gateway.access_token_ttl = ai6::Seconds::new(3_600);
8868            gateway.session_idle = TimeLimit::secs(1_800);
8869            gateway.session_max = TimeLimit::UNBOUNDED;
8870        })
8871        .await;
8872        let now = unix_timestamp().ok().unwrap();
8873
8874        // A token lasts the idle limit when that is shorter than its lifetime, and says when
8875        // the sign-in goes idle.
8876        let signed_in: serde_json::Value = signing.login(None).await.json().await.unwrap();
8877        assert!(
8878            (time_in(&signed_in, "expires_in") - 1_800.0).abs() < 1e-3,
8879            "{signed_in}"
8880        );
8881        assert!(
8882            (time_in(&signed_in, "idle_ends_at") - time_in(&signed_in, "expires_at")).abs() < 1.0,
8883            "{signed_in}"
8884        );
8885        assert!(signed_in["ends_at"].is_null(), "no fixed cut: {signed_in}");
8886
8887        // Thirteen hours after signing in, a renewal still within the limit goes on.
8888        let token = signing.token(now - 13.0 * 3_600.0, now + 120.0);
8889        let renewed = body_of(signing.renew(&token).await).await;
8890        assert!(renewed["ends_at"].is_null(), "{renewed}");
8891        let left = time_in(&renewed, "expires_in");
8892        assert!((1_790.0..=1_800.0).contains(&left), "{renewed}");
8893        assert!(
8894            (time_in(&renewed, "idle_ends_at") - (now + 1_800.0)).abs() < 5.0,
8895            "{renewed}"
8896        );
8897        // And again, so a person who keeps working is never cut off.
8898        assert_eq!(signing.renew(&token).await.status(), StatusCode::OK);
8899    }
8900
8901    #[tokio::test]
8902    async fn a_renewal_after_the_idle_deadline_is_refused() {
8903        let signing = Signing::new(|gateway| gateway.session_idle = TimeLimit::secs(1_800)).await;
8904        let now = unix_timestamp().ok().unwrap();
8905        let idle = signing.token(now - 2_000.0, now - 10.0);
8906        assert_eq!(
8907            signing.renew(&idle).await.status(),
8908            StatusCode::UNAUTHORIZED
8909        );
8910        let live = signing.token(now - 100.0, now + 100.0);
8911        assert_eq!(signing.renew(&live).await.status(), StatusCode::OK);
8912    }
8913
8914    #[tokio::test]
8915    async fn a_set_run_max_still_ends_a_sign_in_that_keeps_working() {
8916        let signing = Signing::new(|gateway| {
8917            gateway.session_idle = TimeLimit::secs(1_800);
8918            gateway.session_max = TimeLimit::secs(7_200);
8919        })
8920        .await;
8921        let now = unix_timestamp().ok().unwrap();
8922        let issued_at = now - 7_000.0;
8923        let token = signing.token(issued_at, now + 120.0);
8924        let capped = body_of(signing.renew(&token).await).await;
8925        assert!(
8926            (time_in(&capped, "expires_at") - (issued_at + 7_200.0)).abs() < 1e-3,
8927            "{capped}"
8928        );
8929        assert!(
8930            (time_in(&capped, "idle_ends_at") - (issued_at + 7_200.0)).abs() < 1e-3,
8931            "{capped}"
8932        );
8933        let past = signing.token(now - 8_000.0, now + 120.0);
8934        let ended = body_of(signing.renew(&past).await).await;
8935        assert!(
8936            time_in(&ended, "expires_at") < now + 130.0,
8937            "it does not go on: {ended}"
8938        );
8939    }
8940
8941    #[tokio::test]
8942    async fn a_cookie_resume_follows_the_idle_limit_and_a_renewal_keeps_the_cookie() {
8943        let signing = Signing::new(|gateway| {
8944            gateway.session_idle = TimeLimit::secs(1_800);
8945            gateway.session_max = TimeLimit::UNBOUNDED;
8946        })
8947        .await;
8948        let now = unix_timestamp().ok().unwrap();
8949
8950        // A cookie nobody renewed has gone idle.
8951        let idle = signing.cookie(now - 13.0 * 3_600.0, now - 10.0);
8952        assert_eq!(
8953            signing.resume(&idle).await.status(),
8954            StatusCode::UNAUTHORIZED
8955        );
8956
8957        // One still within the limit signs back in, however long ago the sign-in began, and is
8958        // kept for another idle limit from the resume.
8959        let value = new_secret();
8960        let record = AccessTokenRecord::try_new(
8961            Uuid::new_v4().to_string(),
8962            session_cookie_digest(&value),
8963            "alice-id",
8964            now - 13.0 * 3_600.0,
8965            now + 600.0,
8966            None,
8967        )
8968        .unwrap()
8969        .with_factors(password_steps())
8970        .into_session_cookie();
8971        signing.registry.store_access_token(&record).unwrap();
8972        let resumed = signing.resume(&format!("{SESSION_COOKIE}={value}")).await;
8973        assert_eq!(resumed.status(), StatusCode::CREATED);
8974        let body: serde_json::Value = resumed.json().await.unwrap();
8975        assert!(
8976            (time_in(&body, "expires_in") - 1_800.0).abs() < 5.0,
8977            "{body}"
8978        );
8979        let kept = signing
8980            .registry
8981            .find_session_cookie(&session_cookie_digest(&value))
8982            .unwrap()
8983            .unwrap();
8984        assert!((kept.expires_at() - (now + 1_800.0)).abs() < 5.0);
8985
8986        // A renewal of a browser's sign-in moves its cookie on too.
8987        let cookie_id = Uuid::new_v4().to_string();
8988        let cookie_value = new_secret();
8989        let cookie = AccessTokenRecord::try_new(
8990            cookie_id.clone(),
8991            session_cookie_digest(&cookie_value),
8992            "alice-id",
8993            now - 100.0,
8994            now + 100.0,
8995            None,
8996        )
8997        .unwrap()
8998        .with_factors(password_steps())
8999        .into_session_cookie();
9000        signing.registry.store_access_token(&cookie).unwrap();
9001        let token = new_secret();
9002        let bearer = AccessTokenRecord::try_new(
9003            Uuid::new_v4().to_string(),
9004            access_token_digest(&token),
9005            "alice-id",
9006            now - 100.0,
9007            now + 100.0,
9008            None,
9009        )
9010        .unwrap()
9011        .with_factors(password_steps())
9012        .in_sign_in(cookie_id)
9013        .unwrap();
9014        signing.registry.store_access_token(&bearer).unwrap();
9015        assert_eq!(signing.renew(&token).await.status(), StatusCode::OK);
9016        let after = signing
9017            .registry
9018            .find_session_cookie(&session_cookie_digest(&cookie_value))
9019            .unwrap()
9020            .unwrap();
9021        assert!((after.expires_at() - (now + 1_800.0)).abs() < 5.0);
9022    }
9023
9024    #[tokio::test]
9025    async fn a_resume_needs_the_public_origin() {
9026        let signing = Signing::new(|_| {}).await;
9027        let (_, cookie) = signing.web_login().await;
9028        let post = || {
9029            reqwest::Client::new()
9030                .post(format!("{}/v1/auth/resume", signing.base))
9031                .header(COOKIE, &cookie)
9032        };
9033        for (request, what) in [
9034            (
9035                post()
9036                    .header(ORIGIN, "https://elsewhere.example")
9037                    .header("x-forwarded-proto", "https"),
9038                "another site",
9039            ),
9040            (
9041                post()
9042                    .header(ORIGIN, "null")
9043                    .header("x-forwarded-proto", "https"),
9044                "a sandboxed page of Moneypenny's",
9045            ),
9046            (post().header("x-forwarded-proto", "https"), "no origin"),
9047            (post().header(ORIGIN, "https://localhost"), "not over HTTPS"),
9048            (
9049                post()
9050                    .header(ORIGIN, "https://localhost")
9051                    .header("x-forwarded-proto", "http"),
9052                "said to be HTTP",
9053            ),
9054        ] {
9055            let refused = request.send().await.unwrap();
9056            assert_eq!(refused.status(), StatusCode::FORBIDDEN, "{what}");
9057            assert!(set_cookie_of(&refused).is_none(), "{what} clears nothing");
9058            assert!(!refused.text().await.unwrap().contains("token"), "{what}");
9059        }
9060        assert_eq!(
9061            signing.resume(&cookie).await.status(),
9062            StatusCode::CREATED,
9063            "and it still works from the page"
9064        );
9065        let none = signing.page_post("/v1/auth/resume").send().await.unwrap();
9066        assert_eq!(none.status(), StatusCode::UNAUTHORIZED, "no cookie");
9067        assert!(set_cookie_of(&none).is_none());
9068    }
9069
9070    #[tokio::test]
9071    async fn the_cookie_is_no_bearer_and_no_other_route_takes_it() {
9072        let signing = Signing::new(|_| {}).await;
9073        let (signed_in, cookie) = signing.web_login().await;
9074        let value = cookie.split_once('=').unwrap().1;
9075        let client = reqwest::Client::new();
9076
9077        // Its value as a bearer token, everywhere one is taken.
9078        assert_eq!(
9079            signing.session(value).await.status(),
9080            StatusCode::UNAUTHORIZED
9081        );
9082        assert_eq!(
9083            signing.renew(value).await.status(),
9084            StatusCode::UNAUTHORIZED
9085        );
9086        for (path, post) in [
9087            ("/v1/user/profile", false),
9088            ("/v1/stations", false),
9089            ("/v1/auth/logout", true),
9090        ] {
9091            let url = format!("{}{path}", signing.base);
9092            let request = if post {
9093                client.post(url)
9094            } else {
9095                client.get(url)
9096            };
9097            let answer = request.bearer_auth(value).send().await.unwrap();
9098            assert_eq!(answer.status(), StatusCode::UNAUTHORIZED, "{path}");
9099        }
9100        // The cookie alone, as a route that wants a bearer sees it.
9101        for (path, post) in [
9102            ("/v1/auth/session", false),
9103            ("/v1/auth/renew", true),
9104            ("/v1/user/profile", false),
9105            ("/v1/stations", false),
9106        ] {
9107            let url = format!("{}{path}", signing.base);
9108            let request = if post {
9109                client.post(url)
9110            } else {
9111                client.get(url)
9112            };
9113            let answer = request
9114                .header(COOKIE, &cookie)
9115                .header(ORIGIN, "https://localhost")
9116                .header("x-forwarded-proto", "https")
9117                .send()
9118                .await
9119                .unwrap();
9120            assert_eq!(answer.status(), StatusCode::UNAUTHORIZED, "{path}");
9121        }
9122        // A bearer token is no cookie either.
9123        let token = signed_in["token"].as_str().unwrap();
9124        let as_cookie = format!("{SESSION_COOKIE}={token}");
9125        assert_eq!(
9126            signing.resume(&as_cookie).await.status(),
9127            StatusCode::UNAUTHORIZED
9128        );
9129        // None of that ended anything.
9130        assert_eq!(signing.session(token).await.status(), StatusCode::OK);
9131        assert_eq!(signing.resume(&cookie).await.status(), StatusCode::CREATED);
9132    }
9133
9134    #[tokio::test]
9135    async fn signing_out_ends_the_cookie_and_every_token_of_that_sign_in() {
9136        let signing = Signing::new(|_| {}).await;
9137        let (signed_in, cookie) = signing.web_login().await;
9138        let first = signed_in["token"].as_str().unwrap();
9139        let resumed: serde_json::Value = signing.resume(&cookie).await.json().await.unwrap();
9140        let second = resumed["token"].as_str().unwrap();
9141        let (other, other_cookie) = signing.web_login().await;
9142
9143        let signed_out = signing
9144            .page_post("/v1/auth/logout")
9145            .header(COOKIE, &cookie)
9146            .bearer_auth(second)
9147            .send()
9148            .await
9149            .unwrap();
9150        assert_eq!(signed_out.status(), StatusCode::NO_CONTENT);
9151        assert_clears_cookie(&signed_out);
9152        for token in [first, second] {
9153            assert_eq!(
9154                signing.session(token).await.status(),
9155                StatusCode::UNAUTHORIZED
9156            );
9157        }
9158        assert_eq!(
9159            signing.resume(&cookie).await.status(),
9160            StatusCode::UNAUTHORIZED
9161        );
9162
9163        // That sign-in alone: one elsewhere carries on.
9164        assert_eq!(
9165            signing
9166                .session(other["token"].as_str().unwrap())
9167                .await
9168                .status(),
9169            StatusCode::OK
9170        );
9171        assert_eq!(
9172            signing.resume(&other_cookie).await.status(),
9173            StatusCode::CREATED
9174        );
9175    }
9176
9177    #[tokio::test]
9178    async fn signing_out_with_a_token_past_its_time_still_ends_the_cookie() {
9179        let signing = Signing::new(|_| {}).await;
9180        let (signed_in, cookie) = signing.web_login().await;
9181        let token = signed_in["token"].as_str().unwrap();
9182
9183        // From another site the cookie counts for nothing, and the person stays signed in.
9184        let foreign = reqwest::Client::new()
9185            .post(format!("{}/v1/auth/logout", signing.base))
9186            .header(COOKIE, &cookie)
9187            .header(ORIGIN, "https://elsewhere.example")
9188            .header("x-forwarded-proto", "https")
9189            .send()
9190            .await
9191            .unwrap();
9192        assert_eq!(foreign.status(), StatusCode::UNAUTHORIZED);
9193        assert_eq!(signing.session(token).await.status(), StatusCode::OK);
9194
9195        let signed_out = signing
9196            .page_post("/v1/auth/logout")
9197            .header(COOKIE, &cookie)
9198            .bearer_auth("a-token-long-over")
9199            .send()
9200            .await
9201            .unwrap();
9202        assert_eq!(signed_out.status(), StatusCode::NO_CONTENT);
9203        assert_clears_cookie(&signed_out);
9204        assert_eq!(
9205            signing.resume(&cookie).await.status(),
9206            StatusCode::UNAUTHORIZED
9207        );
9208        assert_eq!(
9209            signing.session(token).await.status(),
9210            StatusCode::UNAUTHORIZED,
9211            "and the token that was still good goes with it"
9212        );
9213    }
9214
9215    #[tokio::test]
9216    async fn with_the_setting_off_a_sign_in_lives_in_memory_alone() {
9217        for off in [
9218            Signing::new(|gateway| gateway.session_cookie = false).await,
9219            Signing::new(|gateway| gateway.session_max = TimeLimit::secs(0)).await,
9220        ] {
9221            let response = off
9222                .page_post("/v1/auth/login")
9223                .json(&serde_json::json!({"name": "alice", "secret": "right"}))
9224                .send()
9225                .await
9226                .unwrap();
9227            assert_eq!(response.status(), StatusCode::CREATED);
9228            assert!(set_cookie_of(&response).is_none());
9229            let body: serde_json::Value = response.json().await.unwrap();
9230            let token = body["token"].as_str().unwrap();
9231            assert_eq!(off.record_of(token).unwrap().sign_in(), None);
9232
9233            // One from before the setting changed is refused and cleared.
9234            let now = unix_timestamp().ok().unwrap();
9235            let refused = off.resume(&off.cookie(now - 10.0, now + 3_600.0)).await;
9236            assert_eq!(refused.status(), StatusCode::UNAUTHORIZED);
9237            assert_clears_cookie(&refused);
9238        }
9239    }
9240
9241    #[tokio::test]
9242    async fn refused_resumes_are_counted_apart_from_login_tries() {
9243        let signing = Signing::built(
9244            |_| {},
9245            LoginLimits {
9246                per_address: std::num::NonZeroU32::new(3).unwrap(),
9247                per_name: std::num::NonZeroU32::new(3).unwrap(),
9248                address_header: None,
9249                ..LoginLimits::default()
9250            },
9251            |providers| providers,
9252        )
9253        .await;
9254        let (_, good) = signing.web_login().await;
9255
9256        // No cookie is what every signed-out page sends: it is not counted.
9257        for _ in 0..5 {
9258            let none = signing.page_post("/v1/auth/resume").send().await.unwrap();
9259            assert_eq!(none.status(), StatusCode::UNAUTHORIZED);
9260        }
9261        let bad = format!("{SESSION_COOKIE}=made-up");
9262        for _ in 0..3 {
9263            assert_eq!(
9264                signing.resume(&bad).await.status(),
9265                StatusCode::UNAUTHORIZED
9266            );
9267        }
9268        let held = signing.resume(&bad).await;
9269        assert_eq!(held.status(), StatusCode::TOO_MANY_REQUESTS);
9270        assert!(held.headers().contains_key(RETRY_AFTER));
9271        assert_clears_cookie(&held);
9272
9273        // Nobody behind that address pays for it: a good cookie resumes, the person's password
9274        // tries are untouched, and resuming spends none of them.
9275        for _ in 0..4 {
9276            assert_eq!(signing.resume(&good).await.status(), StatusCode::CREATED);
9277        }
9278        for _ in 0..2 {
9279            let (_, again) = signing.web_login().await;
9280            assert_eq!(signing.resume(&again).await.status(), StatusCode::CREATED);
9281        }
9282    }
9283
9284    #[tokio::test]
9285    async fn a_resume_stops_when_the_front_proxy_says_this_is_someone_else() {
9286        let signing = Signing::built(
9287            |_| {},
9288            LoginLimits::default(),
9289            |providers| {
9290                providers
9291                    .with_proxy_identity(HeaderName::from_static("x-forwarded-user"), "name")
9292                    .with_proxy_secret(PROXY_TEST_SECRET, 32)
9293                    .unwrap()
9294            },
9295        )
9296        .await;
9297        let (_, cookie) = signing.web_login().await;
9298        let as_user = |user: &'static str| {
9299            signing
9300                .page_post("/v1/auth/resume")
9301                .header(COOKIE, &cookie)
9302                .header("x-forwarded-user", user)
9303                .header(PROXY_SECRET_HEADER, PROXY_TEST_SECRET)
9304        };
9305        let same = as_user("alice").send().await.unwrap();
9306        assert_eq!(same.status(), StatusCode::CREATED);
9307        let other = as_user("bob").send().await.unwrap();
9308        assert_eq!(other.status(), StatusCode::UNAUTHORIZED);
9309        assert_clears_cookie(&other);
9310        // A claim nobody can prove means nothing, and costs the person nothing.
9311        let forged = signing
9312            .page_post("/v1/auth/resume")
9313            .header(COOKIE, &cookie)
9314            .header("x-forwarded-user", "bob")
9315            .send()
9316            .await
9317            .unwrap();
9318        assert_eq!(forged.status(), StatusCode::UNAUTHORIZED);
9319        assert!(set_cookie_of(&forged).is_none());
9320        assert_eq!(signing.resume(&cookie).await.status(), StatusCode::CREATED);
9321    }
9322
9323    #[tokio::test]
9324    async fn login_is_refused_without_being_judged_past_the_tries_of_an_address() {
9325        let (base, server, _directory) = login_gateway(LoginLimits {
9326            per_address: std::num::NonZeroU32::new(3).unwrap(),
9327            per_name: std::num::NonZeroU32::new(100).unwrap(),
9328            address_header: None,
9329            ..LoginLimits::default()
9330        })
9331        .await;
9332        let client = reqwest::Client::new();
9333        for _ in 0..3 {
9334            let wrong = try_login(&client, &base, "alice", "wrong", None).await;
9335            assert_eq!(wrong.status(), StatusCode::UNAUTHORIZED);
9336        }
9337        // The right secret is refused too: past the count nothing is judged.
9338        let limited = try_login(&client, &base, "alice", "right", None).await;
9339        assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
9340        let wait: u64 = limited
9341            .headers()
9342            .get(RETRY_AFTER)
9343            .expect("a refused try says how long to wait")
9344            .to_str()
9345            .unwrap()
9346            .parse()
9347            .unwrap();
9348        assert!((1..=60).contains(&wait));
9349        server.abort();
9350    }
9351
9352    #[tokio::test]
9353    async fn login_counts_a_name_across_addresses_and_addresses_the_proxy_names() {
9354        let (base, server, _directory) = login_gateway(LoginLimits {
9355            per_address: std::num::NonZeroU32::new(100).unwrap(),
9356            per_name: std::num::NonZeroU32::new(2).unwrap(),
9357            address_header: Some(HeaderName::from_static("x-forwarded-for")),
9358            ..LoginLimits::default()
9359        })
9360        .await;
9361        let client = reqwest::Client::new();
9362        for address in ["198.51.100.1", "198.51.100.2"] {
9363            let wrong = try_login(&client, &base, "alice", "wrong", Some(address)).await;
9364            assert_eq!(wrong.status(), StatusCode::UNAUTHORIZED);
9365        }
9366        let by_name = try_login(&client, &base, "ALICE", "right", Some("198.51.100.3")).await;
9367        assert_eq!(by_name.status(), StatusCode::TOO_MANY_REQUESTS);
9368        // Another account from a fresh address is unaffected, and a right secret still works.
9369        let other = try_login(&client, &base, "bob", "wrong", Some("198.51.100.4")).await;
9370        assert_eq!(other.status(), StatusCode::UNAUTHORIZED);
9371        server.abort();
9372
9373        let (base, server, _directory) = login_gateway(LoginLimits {
9374            per_address: std::num::NonZeroU32::new(1).unwrap(),
9375            per_name: std::num::NonZeroU32::new(100).unwrap(),
9376            address_header: Some(HeaderName::from_static("x-forwarded-for")),
9377            ..LoginLimits::default()
9378        })
9379        .await;
9380        let first = try_login(&client, &base, "alice", "right", Some("198.51.100.1")).await;
9381        assert_eq!(first.status(), StatusCode::CREATED);
9382        let same = try_login(&client, &base, "alice", "right", Some("198.51.100.1")).await;
9383        assert_eq!(same.status(), StatusCode::TOO_MANY_REQUESTS);
9384        let elsewhere = try_login(&client, &base, "alice", "right", Some("198.51.100.9")).await;
9385        assert_eq!(elsewhere.status(), StatusCode::CREATED);
9386        server.abort();
9387    }
9388
9389    #[tokio::test]
9390    async fn user_access_filters_stations_and_scopes_attach_grants() {
9391        struct TestAuthenticator;
9392
9393        impl Authenticator for TestAuthenticator {
9394            fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
9395                match (attempt.name.as_deref(), attempt.secret.as_deref()) {
9396                    (Some("viewer"), Some("secret"))
9397                    | (Some("operator"), Some("secret"))
9398                    | (Some("creator"), Some("secret")) => Ok(Verdict::Valid(Lookup {
9399                        by: "name".to_owned(),
9400                        value: attempt.name.unwrap(),
9401                        ..Default::default()
9402                    })),
9403                    _ => Ok(Verdict::Invalid),
9404                }
9405            }
9406        }
9407
9408        struct TestDirectory;
9409
9410        impl Directory for TestDirectory {
9411            fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
9412                let person = match lookup.value.as_str() {
9413                    "viewer" => Some(("viewer-007", "viewer", vec!["field"])),
9414                    "operator" => Some(("operator-007", "operator", Vec::new())),
9415                    "viewer-007" => Some(("viewer-007", "viewer", vec!["field"])),
9416                    "operator-007" => Some(("operator-007", "operator", Vec::new())),
9417                    "creator" | "creator-007" => Some(("creator-007", "creator", Vec::new())),
9418                    _ => None,
9419                };
9420                Ok(person.map(|(id, name, groups)| Person {
9421                    id: id.to_owned(),
9422                    name: name.to_owned(),
9423                    display_name: None,
9424                    email: None,
9425                    groups: groups.into_iter().map(str::to_owned).collect(),
9426                    attributes: BTreeMap::new(),
9427                }))
9428            }
9429        }
9430
9431        let authorizer = ai6::access_from_text(ai6::bootstrap::format::Format::Toml,
9432            r#"
9433                [role.viewer]
9434                actions = ["mission.read", "run.read"]
9435
9436                [role.operator]
9437                actions = ["mission.read", "mission.create", "run.read", "run.input", "audit.read", "agent.read", "agent.configure"]
9438
9439                [role.creator]
9440                actions = ["mission.read", "mission.create"]
9441
9442                [role.station-operator]
9443                actions = ["station.read", "station.configure", "audit.read"]
9444
9445                [[rule]]
9446                subject = "person:creator-007"
9447                scope = "operation:G"
9448                role = "creator"
9449
9450                [[rule]]
9451                subject = "person:viewer-007"
9452                scope = "operation:G"
9453                role = "viewer"
9454
9455                [[rule]]
9456                subject = "person:operator-007"
9457                scope = "operation:G"
9458                role = "operator"
9459
9460                [[rule]]
9461                subject = "person:operator-007"
9462                scope = "station:worker"
9463                role = "station-operator"
9464
9465                [[rule]]
9466                subject = "person:operator-007"
9467                scope = "station:hq"
9468                role = "station-operator"
9469            "#, ai6::Limit::UNBOUNDED,
9470        )
9471        .unwrap();
9472        let directory = tempfile::tempdir().unwrap();
9473        let registry = FileRegistry::open(directory.path());
9474        let mut hq_info = BTreeMap::new();
9475        hq_info.insert("operations".to_owned(), serde_json::json!([]));
9476        hq_info.insert(
9477            "agent_roles".to_owned(),
9478            serde_json::json!([{
9479                "id": "case-officer",
9480                "purpose": "Coordinate routine work.",
9481                "policy": "Follow the global policy."
9482            }]),
9483        );
9484        hq_info.insert("roles".to_owned(), serde_json::json!(["control"]));
9485        hq_info.insert("capacity".to_owned(), serde_json::json!(0));
9486        hq_info.insert("running".to_owned(), serde_json::json!(0));
9487        hq_info.insert("host".to_owned(), serde_json::json!("private-host"));
9488        hq_info.insert("process_id".to_owned(), serde_json::json!(7132));
9489        registry
9490            .check_in(
9491                "hq",
9492                serde_json::from_value(serde_json::to_value(hq_info).unwrap()).unwrap(),
9493            )
9494            .unwrap();
9495        registry.elect("hq", Duration::from_secs(120)).unwrap();
9496        let mut worker_info = BTreeMap::new();
9497        worker_info.insert("operations".to_owned(), serde_json::json!(["G", "L"]));
9498        worker_info.insert("roles".to_owned(), serde_json::json!(["execution"]));
9499        worker_info.insert("capacity".to_owned(), serde_json::json!(4));
9500        worker_info.insert("running".to_owned(), serde_json::json!(2));
9501        worker_info.insert(
9502            "config".to_owned(),
9503            serde_json::json!({
9504                "revision": "18446744073709551615",
9505                "refused": ["roster revision 7: Agent \"009\": clearance"],
9506                "needs_restart": ["theater"]
9507            }),
9508        );
9509        worker_info.insert(
9510            "resources".to_owned(),
9511            serde_json::json!({
9512                "cpus": 8.0, "cpu_percent": 25.0, "load_1m": 1.5, "memory_total_mb": 16384,
9513                "memory_available_mb": 12288, "sampled_at": 1_700_000_000
9514            }),
9515        );
9516        worker_info.insert(
9517            "theaters".to_owned(),
9518            serde_json::json!([
9519                {
9520                    "id": "local", "access": "local", "labels": {},
9521                    "agents": "auto", "egress": "direct"
9522                },
9523                {
9524                    "id": "build-box", "access": "ssh", "host": "build.example.net",
9525                    "labels": {"os": "linux"}, "agents": "auto", "egress": "direct",
9526                    "capabilities": {
9527                        "terminal": true, "run": true, "files": true, "forward": true,
9528                        "os": "linux", "arch": "x86_64"
9529                    },
9530                    "harnesses": ["claude"],
9531                    "resources": {
9532                        "cpus": 1.5, "load_1m": 0.5, "memory_total_mb": 4096,
9533                        "memory_available_mb": 2048, "sampled_at": 1_700_000_010
9534                    },
9535                    "runs": 1
9536                }
9537            ]),
9538        );
9539        worker_info.insert("handlers".to_owned(), serde_json::json!(["claude"]));
9540        worker_info.insert(
9541            "head_of_station".to_owned(),
9542            serde_json::json!({
9543                "station": "worker", "at": 1_700_000_100,
9544                "summary": "Disk at 12% free; two safe houses hold 40 GB of caches.",
9545                "findings": [{
9546                    "kind": "disk", "severity": "warning",
9547                    "text": "12% free under the state directory"
9548                }],
9549                "mission": "round-1", "agent": "M"
9550            }),
9551        );
9552        worker_info.insert(
9553            "operation_policies".to_owned(),
9554            serde_json::json!({"G": {
9555                "operation": "G",
9556                "checkout": true,
9557                "agents": [
9558                    {"id": "007", "handler": "claude", "priority": 10, "roles": ["case-officer"]},
9559                    {"id": "008", "handler": "codex", "priority": 5, "roles": ["case-officer"]}
9560                ]
9561            }}),
9562        );
9563        registry
9564            .check_in(
9565                "worker",
9566                serde_json::from_value(serde_json::to_value(worker_info).unwrap()).unwrap(),
9567            )
9568            .unwrap();
9569        let make_proposal = |retry_key: &str, title: &str| {
9570            MissionProposal::try_new(
9571                "G",
9572                ai6::directorates::m::identity::MissionId::try_new("parent-mission").unwrap(),
9573                "coordinator",
9574                ai6::directorates::m::identity::RunId::try_new("provider-id").unwrap(),
9575                retry_key,
9576                Brief {
9577                    title: title.to_owned(),
9578                    body: "Review this delegated work.".to_owned(),
9579                    id: "proposal".to_owned(),
9580                    mission_id: None,
9581                    handle: None,
9582                    name: None,
9583                    source: "agent".to_owned(),
9584                    operation: None,
9585                    agent: None,
9586                    role: Some("case-officer".to_owned()),
9587                    tags: vec!["review".to_owned()],
9588                    stations: Vec::new(),
9589                    priority: 1,
9590                    url: None,
9591                    data: ai6::BriefData::default(),
9592                    created: String::new(),
9593                    version: 1,
9594                    provenance: None,
9595                },
9596                &Default::default(),
9597            )
9598            .unwrap()
9599        };
9600        let proposal_approval = make_proposal("approval-test", "Approve this delegated work");
9601        let proposal_rejection = make_proposal("rejection-test", "Reject this delegated work");
9602        registry
9603            .submit_mission_proposal(&proposal_approval)
9604            .unwrap();
9605        registry
9606            .submit_mission_proposal(&proposal_rejection)
9607            .unwrap();
9608        let approval_proposal_id = proposal_approval.id.clone();
9609        let rejection_proposal_id = proposal_rejection.id.clone();
9610        let gateway = Gateway::with_access(
9611            GatewayConfig::new(
9612                "https://localhost",
9613                "m-token-that-is-long-enough-for-testing",
9614                test_limits(),
9615                Duration::from_secs(30),
9616                Duration::from_secs(30),
9617            )
9618            .unwrap(),
9619            Arc::new(registry),
9620            AccessProviders::new(
9621                Arc::new(TestAuthenticator),
9622                Arc::new(TestDirectory),
9623                Arc::new(authorizer),
9624            )
9625            .with_proxy_identity(HeaderName::from_static("x-forwarded-user"), "name")
9626            .with_proxy_secret(PROXY_TEST_SECRET, 32)
9627            .unwrap(),
9628        )
9629        .with_degraded(vec![ai6::Degradation::new(
9630            "config-record",
9631            "operation H",
9632            "refused, it cannot be read: workspace.mystery is not a declared field",
9633            Vec::new(),
9634        )]);
9635        for (station, mission, run) in [("G", "mission-g", "run-g"), ("L", "mission-l", "run-l")] {
9636            gateway
9637                .register_run(
9638                    "m-token-that-is-long-enough-for-testing",
9639                    OperationId::new(station).unwrap(),
9640                    MissionId::new(mission).unwrap(),
9641                    RunId::new(run).unwrap(),
9642                )
9643                .await
9644                .unwrap();
9645        }
9646        gateway
9647            .publish_mission_brief(
9648                "m-token-that-is-long-enough-for-testing",
9649                OperationId::new("G").unwrap(),
9650                MissionId::new("mission-g").unwrap(),
9651                LaunchManifest {
9652                    name: None,
9653                    prompt: "Review the requested change".to_owned(),
9654                    agent_id: Some("technical-officer".to_owned()),
9655                    role_id: Some("case-officer".to_owned()),
9656                    handler_provider: "claude".to_owned(),
9657                    terminal_provider: "pty".to_owned(),
9658                    working_directory: "C:/stations/field".to_owned(),
9659                    model: Some("claude-sonnet".to_owned()),
9660                    effort: Some("high".to_owned()),
9661                    environment_keys: vec!["API_TOKEN".to_owned()],
9662                    station_id: "worker".to_owned(),
9663                    theater_id: Some("local".to_owned()),
9664                    mode: ai6::ExecutionMode::RemoteHands,
9665                    provenance: Some(Provenance::new(
9666                        Origin::RegistryDrop,
9667                        &serde_json::from_value::<Brief>(
9668                            serde_json::json!({"title": "Review the requested change"}),
9669                        )
9670                        .unwrap(),
9671                        "worker",
9672                        1_792_922_400,
9673                    )),
9674                },
9675            )
9676            .await
9677            .unwrap();
9678
9679        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
9680        let address = listener.local_addr().unwrap();
9681        let server = tokio::spawn(async move { axum::serve(listener, gateway.router()).await });
9682        let base = format!("http://{address}");
9683        let client = reqwest::Client::new();
9684        let login = |name: &'static str| {
9685            client
9686                .post(format!("{base}/v1/auth/login"))
9687                .header("origin", "https://localhost")
9688                .header("x-forwarded-proto", "https")
9689                .json(&serde_json::json!({"name": name, "secret": "secret"}))
9690        };
9691
9692        // A client that reaches the port without the proxy sets every header but the secret.
9693        for secret in [None, Some("wrong"), Some(&PROXY_TEST_SECRET[1..])] {
9694            let mut forged = client
9695                .post(format!("{base}/v1/auth/login"))
9696                .header("origin", "https://localhost")
9697                .header("x-forwarded-proto", "https")
9698                .header("x-forwarded-user", "viewer");
9699            if let Some(secret) = secret {
9700                forged = forged.header(PROXY_SECRET_HEADER, secret);
9701            }
9702            let forged = forged.json(&serde_json::json!({})).send().await.unwrap();
9703            assert_eq!(forged.status(), StatusCode::UNAUTHORIZED, "{secret:?}");
9704        }
9705        let proxy_login = client
9706            .post(format!("{base}/v1/auth/login"))
9707            .header("origin", "https://localhost")
9708            .header("x-forwarded-proto", "https")
9709            .header("x-forwarded-user", "viewer")
9710            .header(PROXY_SECRET_HEADER, PROXY_TEST_SECRET)
9711            .json(&serde_json::json!({}))
9712            .send()
9713            .await
9714            .unwrap();
9715        assert_eq!(proxy_login.status(), StatusCode::CREATED);
9716        let proxy_token: String = proxy_login.json::<serde_json::Value>().await.unwrap()["token"]
9717            .as_str()
9718            .unwrap()
9719            .to_owned();
9720        let proxy_board = client
9721            .get(format!("{base}/v1/board"))
9722            .bearer_auth(&proxy_token)
9723            .send()
9724            .await
9725            .unwrap();
9726        assert_eq!(proxy_board.status(), StatusCode::OK);
9727        let proxy_board: serde_json::Value = proxy_board.json().await.unwrap();
9728        assert_eq!(proxy_board.as_array().unwrap().len(), 1);
9729        assert_eq!(proxy_board[0]["operation_id"], "G");
9730        let unknown_proxy_identity = client
9731            .post(format!("{base}/v1/auth/login"))
9732            .header("origin", "https://localhost")
9733            .header("x-forwarded-proto", "https")
9734            .header("x-forwarded-user", "unknown-account")
9735            .header(PROXY_SECRET_HEADER, PROXY_TEST_SECRET)
9736            .json(&serde_json::json!({}))
9737            .send()
9738            .await
9739            .unwrap();
9740        assert_eq!(unknown_proxy_identity.status(), StatusCode::UNAUTHORIZED);
9741        let proxy_identity_without_origin = client
9742            .post(format!("{base}/v1/auth/login"))
9743            .header("x-forwarded-user", "viewer")
9744            .json(&serde_json::json!({}))
9745            .send()
9746            .await
9747            .unwrap();
9748        assert_eq!(
9749            proxy_identity_without_origin.status(),
9750            StatusCode::FORBIDDEN
9751        );
9752        let wrong_proto = client
9753            .post(format!("{base}/v1/auth/login"))
9754            .header("origin", "https://localhost")
9755            .header("x-forwarded-proto", "http")
9756            .header("x-forwarded-user", "viewer")
9757            .json(&serde_json::json!({}))
9758            .send()
9759            .await
9760            .unwrap();
9761        assert_eq!(wrong_proto.status(), StatusCode::FORBIDDEN);
9762        assert_eq!(
9763            wrong_proto.text().await.unwrap(),
9764            "request is not authorized"
9765        );
9766        let journaled = JOURNALED.lock().unwrap().join("\n");
9767        for check in [
9768            "proxy secret does not match",
9769            "directory has no such person",
9770            "origin header missing",
9771            "forwarded protocol is not https",
9772        ] {
9773            assert!(journaled.contains(check), "{check}: {journaled}");
9774        }
9775        assert!(!journaled.contains(PROXY_TEST_SECRET), "{journaled}");
9776        assert!(!journaled.contains(&PROXY_TEST_SECRET[1..]), "{journaled}");
9777        assert!(!journaled.contains("wrong"), "{journaled}");
9778
9779        let viewer_login = login("viewer").send().await.unwrap();
9780        assert_eq!(viewer_login.status(), StatusCode::CREATED);
9781        let viewer_token: String = viewer_login.json::<serde_json::Value>().await.unwrap()["token"]
9782            .as_str()
9783            .unwrap()
9784            .to_owned();
9785        let viewer_profile = client
9786            .get(format!("{base}/v1/user/profile"))
9787            .bearer_auth(&viewer_token)
9788            .send()
9789            .await
9790            .unwrap();
9791        assert_eq!(viewer_profile.status(), StatusCode::OK);
9792        let viewer_profile: serde_json::Value = viewer_profile.json().await.unwrap();
9793        assert_eq!(viewer_profile["person_id"], "viewer-007");
9794        assert_eq!(viewer_profile["operations"][0]["operation_id"], "G");
9795        assert_eq!(
9796            viewer_profile["operations"][0]["actions"],
9797            serde_json::json!(["mission.read", "run.read"])
9798        );
9799        assert!(viewer_profile["stations"].as_array().unwrap().is_empty());
9800        assert_eq!(viewer_profile["moneypenny"], false);
9801        let viewer_settings = client
9802            .get(format!("{base}/v1/user/stations/worker/settings"))
9803            .bearer_auth(&viewer_token)
9804            .send()
9805            .await
9806            .unwrap();
9807        assert_eq!(viewer_settings.status(), StatusCode::FORBIDDEN);
9808        let viewer_create = client
9809            .post(format!("{base}/v1/user/operations/G/missions"))
9810            .bearer_auth(&viewer_token)
9811            .json(&serde_json::json!({
9812                "title": "Unauthorized brief",
9813                "prompt": "This must not enter the queue"
9814            }))
9815            .send()
9816            .await
9817            .unwrap();
9818        assert_eq!(viewer_create.status(), StatusCode::FORBIDDEN);
9819
9820        let operator_login = login("operator").send().await.unwrap();
9821        assert_eq!(operator_login.status(), StatusCode::CREATED);
9822        let operator_token: String =
9823            operator_login.json::<serde_json::Value>().await.unwrap()["token"]
9824                .as_str()
9825                .unwrap()
9826                .to_owned();
9827        // Pinning the Agent and route a trial spends takes `agent.configure`, not only
9828        // `mission.create`.
9829        let creator_login = login("creator").send().await.unwrap();
9830        let creator_token: String =
9831            creator_login.json::<serde_json::Value>().await.unwrap()["token"]
9832                .as_str()
9833                .unwrap()
9834                .to_owned();
9835        let trial_request = serde_json::json!({
9836            "agent": "007",
9837            "route": {"handler": "claude", "model": "stand-in"},
9838            "work": {"kind": "suite", "suite": "none", "case": "none"}
9839        });
9840        let creator_trial = client
9841            .post(format!("{base}/v1/user/operations/G/trials"))
9842            .bearer_auth(&creator_token)
9843            .json(&trial_request)
9844            .send()
9845            .await
9846            .unwrap();
9847        assert_eq!(creator_trial.status(), StatusCode::FORBIDDEN);
9848        let operator_trial = client
9849            .post(format!("{base}/v1/user/operations/G/trials"))
9850            .bearer_auth(&operator_token)
9851            .json(&trial_request)
9852            .send()
9853            .await
9854            .unwrap();
9855        assert_ne!(operator_trial.status(), StatusCode::FORBIDDEN);
9856        let operator_profile = client
9857            .get(format!("{base}/v1/user/profile"))
9858            .bearer_auth(&operator_token)
9859            .send()
9860            .await
9861            .unwrap();
9862        assert_eq!(operator_profile.status(), StatusCode::OK);
9863        let operator_profile: serde_json::Value = operator_profile.json().await.unwrap();
9864        assert_eq!(operator_profile["person_id"], "operator-007");
9865        assert_eq!(operator_profile["operations"][0]["operation_id"], "G");
9866        assert_eq!(
9867            operator_profile["operations"][0]["actions"],
9868            serde_json::json!([
9869                "agent.configure",
9870                "agent.read",
9871                "audit.read",
9872                "mission.create",
9873                "mission.read",
9874                "run.input",
9875                "run.read",
9876            ])
9877        );
9878        let station_access = operator_profile["stations"].as_array().unwrap();
9879        let worker_access = station_access
9880            .iter()
9881            .find(|station| station["station_id"] == "worker")
9882            .unwrap();
9883        assert_eq!(
9884            worker_access["actions"],
9885            serde_json::json!(["audit.read", "station.configure", "station.read"])
9886        );
9887        let initial_settings = client
9888            .get(format!("{base}/v1/user/stations/worker/settings"))
9889            .bearer_auth(&operator_token)
9890            .send()
9891            .await
9892            .unwrap();
9893        assert_eq!(initial_settings.status(), StatusCode::OK);
9894        let initial_settings: serde_json::Value = initial_settings.json().await.unwrap();
9895        assert_eq!(initial_settings["max_concurrent_missions"], 4);
9896        assert_eq!(initial_settings["configured"], false);
9897        assert_eq!(initial_settings["execution_enabled"], true);
9898        let control_station_settings = client
9899            .get(format!("{base}/v1/user/stations/hq/settings"))
9900            .bearer_auth(&operator_token)
9901            .send()
9902            .await
9903            .unwrap();
9904        assert_eq!(control_station_settings.status(), StatusCode::OK);
9905        let control_station_settings: serde_json::Value =
9906            control_station_settings.json().await.unwrap();
9907        assert_eq!(control_station_settings["execution_enabled"], false);
9908        let control_station_update = client
9909            .put(format!("{base}/v1/user/stations/hq/settings"))
9910            .bearer_auth(&operator_token)
9911            .json(&serde_json::json!({"max_concurrent_missions": 8}))
9912            .send()
9913            .await
9914            .unwrap();
9915        assert_eq!(control_station_update.status(), StatusCode::CONFLICT);
9916        let invalid_settings = client
9917            .put(format!("{base}/v1/user/stations/worker/settings"))
9918            .bearer_auth(&operator_token)
9919            .json(&serde_json::json!({"max_concurrent_missions": 0}))
9920            .send()
9921            .await
9922            .unwrap();
9923        assert_eq!(invalid_settings.status(), StatusCode::BAD_REQUEST);
9924        let updated_settings = client
9925            .put(format!("{base}/v1/user/stations/worker/settings"))
9926            .bearer_auth(&operator_token)
9927            .json(&serde_json::json!({"max_concurrent_missions": 8}))
9928            .send()
9929            .await
9930            .unwrap();
9931        assert_eq!(updated_settings.status(), StatusCode::NO_CONTENT);
9932        let updated_settings = client
9933            .get(format!("{base}/v1/user/stations/worker/settings"))
9934            .bearer_auth(&operator_token)
9935            .send()
9936            .await
9937            .unwrap();
9938        let updated_settings: serde_json::Value = updated_settings.json().await.unwrap();
9939        assert_eq!(updated_settings["max_concurrent_missions"], 8);
9940        assert_eq!(updated_settings["configured"], true);
9941        assert_eq!(
9942            (
9943                &updated_settings["min_free_memory_mb"],
9944                &updated_settings["max_cpu_percent"]
9945            ),
9946            (&serde_json::json!(512), &serde_json::json!(95)),
9947            "resource limits start at their defaults"
9948        );
9949        let put_settings = |body: serde_json::Value| {
9950            client
9951                .put(format!("{base}/v1/user/stations/worker/settings"))
9952                .bearer_auth(&operator_token)
9953                .json(&body)
9954                .send()
9955        };
9956        assert_eq!(
9957            put_settings(serde_json::json!({"max_concurrent_missions": 8, "max_cpu_percent": 101}))
9958                .await
9959                .unwrap()
9960                .status(),
9961            StatusCode::BAD_REQUEST
9962        );
9963        assert_eq!(
9964            put_settings(
9965                serde_json::json!({"max_concurrent_missions": 8, "min_free_memory_mb": 0})
9966            )
9967            .await
9968            .unwrap()
9969            .status(),
9970            StatusCode::NO_CONTENT
9971        );
9972        assert_eq!(
9973            put_settings(serde_json::json!({"max_concurrent_missions": 6, "max_cpu_percent": 100}))
9974                .await
9975                .unwrap()
9976                .status(),
9977            StatusCode::NO_CONTENT
9978        );
9979        let loosened: serde_json::Value = client
9980            .get(format!("{base}/v1/user/stations/worker/settings"))
9981            .bearer_auth(&operator_token)
9982            .send()
9983            .await
9984            .unwrap()
9985            .json()
9986            .await
9987            .unwrap();
9988        assert_eq!(
9989            (
9990                &loosened["max_concurrent_missions"],
9991                &loosened["min_free_memory_mb"],
9992                &loosened["max_cpu_percent"]
9993            ),
9994            (
9995                &serde_json::json!(6),
9996                &serde_json::json!(0),
9997                &serde_json::json!(100)
9998            ),
9999            "a limit left out keeps the value set before"
10000        );
10001        let station_audit = client
10002            .get(format!("{base}/v1/user/audit?station_id=worker"))
10003            .bearer_auth(&operator_token)
10004            .send()
10005            .await
10006            .unwrap();
10007        assert_eq!(station_audit.status(), StatusCode::OK);
10008        let station_audit: serde_json::Value = station_audit.json().await.unwrap();
10009        assert_eq!(station_audit[0]["action"], "station.settings.update");
10010        assert_eq!(station_audit[0]["resource"], "station:worker");
10011        assert_eq!(station_audit[0]["operation"], "");
10012        let created_mission = client
10013            .post(format!("{base}/v1/user/operations/G/missions"))
10014            .bearer_auth(&operator_token)
10015            .json(&serde_json::json!({
10016                "title": "Inspect the board",
10017                "prompt": "Check operation context and report findings."
10018            }))
10019            .send()
10020            .await
10021            .unwrap();
10022        assert_eq!(created_mission.status(), StatusCode::ACCEPTED);
10023        let created: serde_json::Value = created_mission.json().await.unwrap();
10024        assert_eq!(created["operation_id"], "G");
10025        assert_eq!(created["state"], "queued");
10026        let queued = FileRegistry::open(directory.path()).list_new().unwrap();
10027        assert_eq!(queued.len(), 1);
10028        assert_eq!(queued[0].title, "Inspect the board");
10029        assert_eq!(
10030            queued[0].body,
10031            "Check operation context and report findings."
10032        );
10033        assert_eq!(queued[0].operation.as_deref(), Some("G"));
10034        assert_eq!(queued[0].source, "universal-exports");
10035        assert!(queued[0].created.ends_with('Z'));
10036        let provenance = queued[0]
10037            .provenance
10038            .as_ref()
10039            .expect("the gateway records the asker");
10040        assert_eq!(provenance.origin, Origin::Operator);
10041        assert_eq!(provenance.received_by, GATEWAY_RECEIVER);
10042        assert!(provenance.principal.is_some());
10043        assert!(provenance.matches(&queued[0]));
10044        assert_eq!(created["mission_id"], queued[0].key());
10045        assert!(!created.to_string().contains("Check operation context"));
10046
10047        let operator_audit = client
10048            .get(format!("{base}/v1/user/audit?operation_id=G"))
10049            .bearer_auth(&operator_token)
10050            .send()
10051            .await
10052            .unwrap();
10053        assert_eq!(operator_audit.status(), StatusCode::OK);
10054        let operator_audit: serde_json::Value = operator_audit.json().await.unwrap();
10055        assert_eq!(operator_audit.as_array().unwrap().len(), 1);
10056        assert_eq!(operator_audit[0]["actor"], "operator-007");
10057        assert_eq!(operator_audit[0]["action"], "mission.create.requested");
10058        assert_eq!(operator_audit[0]["operation"], "G");
10059        assert_eq!(operator_audit[0]["target"], created["mission_id"]);
10060        assert!(operator_audit[0]["at"].as_f64().unwrap() > 0.0);
10061        assert!(
10062            !operator_audit
10063                .to_string()
10064                .contains("Check operation context")
10065        );
10066
10067        let viewer_audit = client
10068            .get(format!("{base}/v1/user/audit?operation_id=G"))
10069            .bearer_auth(&viewer_token)
10070            .send()
10071            .await
10072            .unwrap();
10073        assert_eq!(viewer_audit.status(), StatusCode::FORBIDDEN);
10074
10075        let viewer_proposals = client
10076            .get(format!("{base}/v1/user/operations/G/mission-proposals"))
10077            .bearer_auth(&viewer_token)
10078            .send()
10079            .await
10080            .unwrap();
10081        assert_eq!(viewer_proposals.status(), StatusCode::FORBIDDEN);
10082        let viewer_approval = client
10083            .post(format!(
10084                "{base}/v1/user/operations/G/mission-proposals/{approval_proposal_id}/approve"
10085            ))
10086            .bearer_auth(&viewer_token)
10087            .send()
10088            .await
10089            .unwrap();
10090        assert_eq!(viewer_approval.status(), StatusCode::FORBIDDEN);
10091
10092        let proposals = client
10093            .get(format!("{base}/v1/user/operations/G/mission-proposals"))
10094            .bearer_auth(&operator_token)
10095            .send()
10096            .await
10097            .unwrap();
10098        assert_eq!(proposals.status(), StatusCode::OK);
10099        let proposals: serde_json::Value = proposals.json().await.unwrap();
10100        assert_eq!(proposals.as_array().unwrap().len(), 2);
10101        assert!(
10102            proposals
10103                .to_string()
10104                .contains("Review this delegated work.")
10105        );
10106        assert!(!proposals.to_string().contains("operator secret"));
10107
10108        let approved = client
10109            .post(format!(
10110                "{base}/v1/user/operations/G/mission-proposals/{approval_proposal_id}/approve"
10111            ))
10112            .bearer_auth(&operator_token)
10113            .send()
10114            .await
10115            .unwrap();
10116        assert_eq!(approved.status(), StatusCode::ACCEPTED);
10117        let approved: serde_json::Value = approved.json().await.unwrap();
10118        assert_eq!(approved["proposal_id"], approval_proposal_id);
10119        assert_eq!(approved["state"], "queued");
10120        assert_eq!(
10121            FileRegistry::open(directory.path())
10122                .list_new()
10123                .unwrap()
10124                .len(),
10125            2
10126        );
10127        let cleared = FileRegistry::open(directory.path())
10128            .clearance(approved["mission_id"].as_str().unwrap())
10129            .unwrap()
10130            .expect("an operator's approval clears the promoted brief");
10131        assert!(cleared.kinds.contains(&ai6::FindingKind::Screening));
10132        assert!(!cleared.kinds.contains(&ai6::FindingKind::Malformed));
10133        assert_eq!(cleared.by, "operator-007");
10134        let rejected = client
10135            .post(format!(
10136                "{base}/v1/user/operations/G/mission-proposals/{rejection_proposal_id}/reject"
10137            ))
10138            .bearer_auth(&operator_token)
10139            .send()
10140            .await
10141            .unwrap();
10142        assert_eq!(rejected.status(), StatusCode::OK);
10143        let rejected: serde_json::Value = rejected.json().await.unwrap();
10144        assert_eq!(rejected["state"], "rejected");
10145        assert!(
10146            FileRegistry::open(directory.path())
10147                .list_mission_proposals("G", 10)
10148                .unwrap()
10149                .is_empty()
10150        );
10151        let proposal_audit = client
10152            .get(format!("{base}/v1/user/audit?operation_id=G"))
10153            .bearer_auth(&operator_token)
10154            .send()
10155            .await
10156            .unwrap();
10157        assert_eq!(proposal_audit.status(), StatusCode::OK);
10158        let proposal_audit: serde_json::Value = proposal_audit.json().await.unwrap();
10159        for (action, proposal_id) in [
10160            ("mission.proposal.approved", approval_proposal_id.as_str()),
10161            ("mission.proposal.rejected", rejection_proposal_id.as_str()),
10162        ] {
10163            assert!(proposal_audit.as_array().unwrap().iter().any(|entry| {
10164                entry["actor"] == "operator-007"
10165                    && entry["action"] == action
10166                    && entry["target"] == proposal_id
10167                    && entry["at"].as_f64().is_some_and(|at| at > 0.0)
10168            }));
10169        }
10170
10171        let role = serde_json::json!({
10172            "id": "reviewer",
10173            "purpose": "Review Operation changes",
10174            "policy": "Follow the configured Operation rules."
10175        });
10176        let viewer_role_update = client
10177            .put(format!("{base}/v1/user/operations/G/agent-roles/reviewer"))
10178            .bearer_auth(&viewer_token)
10179            .json(&role)
10180            .send()
10181            .await
10182            .unwrap();
10183        assert_eq!(viewer_role_update.status(), StatusCode::FORBIDDEN);
10184        let viewer_role_list = client
10185            .get(format!("{base}/v1/user/operations/G/agent-roles"))
10186            .bearer_auth(&viewer_token)
10187            .send()
10188            .await
10189            .unwrap();
10190        assert_eq!(viewer_role_list.status(), StatusCode::FORBIDDEN);
10191
10192        let role_form = format!("{base}/v1/user/operations/G/agent-role-form");
10193        let refused = client
10194            .get(&role_form)
10195            .bearer_auth(&viewer_token)
10196            .send()
10197            .await
10198            .unwrap();
10199        assert_eq!(refused.status(), StatusCode::FORBIDDEN);
10200        let form = client
10201            .get(&role_form)
10202            .bearer_auth(&operator_token)
10203            .send()
10204            .await
10205            .unwrap();
10206        assert_eq!(form.status(), StatusCode::OK);
10207        let form: serde_json::Value = form.json().await.unwrap();
10208        assert_eq!(form["schema"]["properties"]["id"]["title"], "Role ID");
10209        assert_eq!(form["form"]["fields"]["policy"]["widget"], "textarea");
10210
10211        let operator_role_update = client
10212            .put(format!("{base}/v1/user/operations/G/agent-roles/reviewer"))
10213            .bearer_auth(&operator_token)
10214            .json(&role)
10215            .send()
10216            .await
10217            .unwrap();
10218        assert_eq!(operator_role_update.status(), StatusCode::NO_CONTENT);
10219        let roles = client
10220            .get(format!("{base}/v1/user/operations/G/agent-roles"))
10221            .bearer_auth(&operator_token)
10222            .send()
10223            .await
10224            .unwrap();
10225        assert_eq!(roles.status(), StatusCode::OK);
10226        let roles: serde_json::Value = roles.json().await.unwrap();
10227        assert_eq!(roles.as_array().unwrap().len(), 2);
10228        assert_eq!(roles[0]["id"], "case-officer");
10229        assert_eq!(roles[0]["operation_override"], false);
10230        assert_eq!(roles[1]["id"], "reviewer");
10231        assert_eq!(roles[1]["operation_override"], true);
10232        assert!(
10233            roles
10234                .to_string()
10235                .contains("Follow the configured Operation rules.")
10236        );
10237
10238        let role_audit = client
10239            .get(format!("{base}/v1/user/audit?operation_id=G"))
10240            .bearer_auth(&operator_token)
10241            .send()
10242            .await
10243            .unwrap();
10244        assert_eq!(role_audit.status(), StatusCode::OK);
10245        let role_audit: serde_json::Value = role_audit.json().await.unwrap();
10246        assert!(role_audit.as_array().unwrap().iter().any(|entry| {
10247            entry["actor"] == "operator-007"
10248                && entry["action"] == "agent.role.update"
10249                && entry["target"] == "reviewer"
10250                && entry["at"].as_f64().is_some_and(|at| at > 0.0)
10251        }));
10252        assert!(
10253            !role_audit
10254                .to_string()
10255                .contains("Follow the configured Operation rules.")
10256        );
10257
10258        let role_delete = client
10259            .delete(format!("{base}/v1/user/operations/G/agent-roles/reviewer"))
10260            .bearer_auth(&operator_token)
10261            .send()
10262            .await
10263            .unwrap();
10264        assert_eq!(role_delete.status(), StatusCode::NO_CONTENT);
10265        let roles_after_delete = client
10266            .get(format!("{base}/v1/user/operations/G/agent-roles"))
10267            .bearer_auth(&operator_token)
10268            .send()
10269            .await
10270            .unwrap();
10271        let roles_after_delete: serde_json::Value = roles_after_delete.json().await.unwrap();
10272        assert_eq!(roles_after_delete.as_array().unwrap().len(), 1);
10273        assert_eq!(roles_after_delete[0]["id"], "case-officer");
10274
10275        let quarantine = format!("{base}/v1/user/operations/G/quarantine");
10276        let forbidden = client
10277            .post(format!("{quarantine}/007"))
10278            .bearer_auth(&viewer_token)
10279            .json(&serde_json::json!({ "reason": "looping" }))
10280            .send()
10281            .await
10282            .unwrap();
10283        assert_eq!(forbidden.status(), StatusCode::FORBIDDEN);
10284        let quarantined = client
10285            .post(format!("{quarantine}/007"))
10286            .bearer_auth(&operator_token)
10287            .json(&serde_json::json!({ "reason": "looping" }))
10288            .send()
10289            .await
10290            .unwrap();
10291        assert_eq!(quarantined.status(), StatusCode::CREATED);
10292        let listed: serde_json::Value = client
10293            .get(&quarantine)
10294            .bearer_auth(&operator_token)
10295            .send()
10296            .await
10297            .unwrap()
10298            .json()
10299            .await
10300            .unwrap();
10301        assert_eq!(listed[0]["agent"], "007");
10302        assert_eq!(listed[0]["operation"], "G");
10303        assert_eq!(listed[0]["by"], "operator-007");
10304        let viewer_release = client
10305            .post(format!("{quarantine}/007/release"))
10306            .bearer_auth(&viewer_token)
10307            .json(&serde_json::json!({ "reason": "cleared" }))
10308            .send()
10309            .await
10310            .unwrap();
10311        assert_eq!(viewer_release.status(), StatusCode::FORBIDDEN);
10312        let released = client
10313            .post(format!("{quarantine}/007/release"))
10314            .bearer_auth(&operator_token)
10315            .json(&serde_json::json!({ "reason": "cleared" }))
10316            .send()
10317            .await
10318            .unwrap();
10319        assert_eq!(released.status(), StatusCode::OK);
10320        let again = client
10321            .post(format!("{quarantine}/007/release"))
10322            .bearer_auth(&operator_token)
10323            .json(&serde_json::json!({ "reason": "cleared" }))
10324            .send()
10325            .await
10326            .unwrap();
10327        assert_eq!(again.status(), StatusCode::NOT_FOUND);
10328        let empty: serde_json::Value = client
10329            .get(&quarantine)
10330            .bearer_auth(&operator_token)
10331            .send()
10332            .await
10333            .unwrap()
10334            .json()
10335            .await
10336            .unwrap();
10337        assert!(empty.as_array().unwrap().is_empty());
10338
10339        let anonymous_board = client.get(format!("{base}/v1/board")).send().await.unwrap();
10340        assert_eq!(anonymous_board.status(), StatusCode::UNAUTHORIZED);
10341        let anonymous_missions = client
10342            .get(format!("{base}/v1/missions"))
10343            .send()
10344            .await
10345            .unwrap();
10346        assert_eq!(anonymous_missions.status(), StatusCode::UNAUTHORIZED);
10347        let anonymous_stations = client
10348            .get(format!("{base}/v1/stations"))
10349            .send()
10350            .await
10351            .unwrap();
10352        assert_eq!(anonymous_stations.status(), StatusCode::UNAUTHORIZED);
10353        let anonymous_profile = client
10354            .get(format!("{base}/v1/user/profile"))
10355            .send()
10356            .await
10357            .unwrap();
10358        assert_eq!(anonymous_profile.status(), StatusCode::UNAUTHORIZED);
10359        let anonymous_audit = client
10360            .get(format!("{base}/v1/user/audit"))
10361            .send()
10362            .await
10363            .unwrap();
10364        assert_eq!(anonymous_audit.status(), StatusCode::UNAUTHORIZED);
10365
10366        let station_board = client
10367            .get(format!("{base}/v1/stations"))
10368            .bearer_auth(&viewer_token)
10369            .send()
10370            .await
10371            .unwrap();
10372        assert_eq!(station_board.status(), StatusCode::OK);
10373        let station_board: serde_json::Value = station_board.json().await.unwrap();
10374        assert!(station_board["headquarters_station"].is_null());
10375        assert_eq!(
10376            station_board["gateway_degraded"],
10377            serde_json::json!([]),
10378            "a person who reads no Station is not told what is wrong with the gateway"
10379        );
10380        assert_eq!(station_board["stations"].as_array().unwrap().len(), 1);
10381        assert_eq!(station_board["stations"][0]["station_id"], "worker");
10382        assert_eq!(station_board["stations"][0]["healthy"], true);
10383        assert_eq!(station_board["stations"][0]["headquarters"], false);
10384        assert_eq!(station_board["stations"][0]["operations"][0], "G");
10385        assert!(
10386            station_board["stations"][0]["head_of_station"].is_null(),
10387            "the report covers every Operation: a viewer of one does not see it"
10388        );
10389        let operator_board: serde_json::Value = client
10390            .get(format!("{base}/v1/stations"))
10391            .bearer_auth(&operator_token)
10392            .send()
10393            .await
10394            .unwrap()
10395            .json()
10396            .await
10397            .unwrap();
10398        let worker = operator_board["stations"]
10399            .as_array()
10400            .unwrap()
10401            .iter()
10402            .find(|station| station["station_id"] == "worker")
10403            .unwrap();
10404        let control = operator_board["stations"]
10405            .as_array()
10406            .unwrap()
10407            .iter()
10408            .find(|station| station["station_id"] == "hq")
10409            .expect("station.read shows a Station that holds no checkout");
10410        assert_eq!(control["operations"], serde_json::json!([]));
10411        assert_eq!(operator_board["headquarters_station"], "hq");
10412        assert_eq!(
10413            operator_board["gateway_degraded"][0]["kind"],
10414            "config-record"
10415        );
10416        assert_eq!(
10417            operator_board["gateway_degraded"][0]["subject"],
10418            "operation H"
10419        );
10420        assert_eq!(
10421            worker["head_of_station"],
10422            serde_json::json!({
10423                "station": "worker", "at": 1_700_000_100,
10424                "summary": "Disk at 12% free; two safe houses hold 40 GB of caches.",
10425                "findings": [{
10426                    "kind": "disk", "severity": "warning",
10427                    "text": "12% free under the state directory"
10428                }],
10429                "mission": "round-1", "agent": "M"
10430            }),
10431            "the Station's latest Head of Station report"
10432        );
10433
10434        let anonymous_preview = client
10435            .get(format!("{base}/v1/user/operations/G/placement-preview"))
10436            .send()
10437            .await
10438            .unwrap();
10439        assert_eq!(anonymous_preview.status(), StatusCode::UNAUTHORIZED);
10440        let unauthorized_preview = client
10441            .get(format!("{base}/v1/user/operations/L/placement-preview"))
10442            .bearer_auth(&viewer_token)
10443            .send()
10444            .await
10445            .unwrap();
10446        assert_eq!(unauthorized_preview.status(), StatusCode::FORBIDDEN);
10447        let preview = client
10448            .get(format!("{base}/v1/user/operations/G/placement-preview"))
10449            .bearer_auth(&viewer_token)
10450            .send()
10451            .await
10452            .unwrap();
10453        assert_eq!(preview.status(), StatusCode::OK);
10454        let preview: serde_json::Value = preview.json().await.unwrap();
10455        assert_eq!(preview["operation_id"], "G");
10456        assert_eq!(preview["policy_station"], "worker");
10457        assert_eq!(
10458            preview["choices"],
10459            serde_json::json!([{
10460                "station": "worker", "theater": "local", "agent": "007", "handler": "claude",
10461                "mode": "field", "score": 1.0
10462            }]),
10463            "half its capacity running, a quarter of its CPU busy and its memory in use"
10464        );
10465        let rejections = preview["rejections"].as_array().unwrap();
10466        assert!(rejections.iter().any(|r| {
10467            r["theater"] == "build-box"
10468                && r["reason"]
10469                    .as_str()
10470                    .is_some_and(|reason| reason.contains("has no `workdir`"))
10471        }));
10472        assert!(
10473            rejections
10474                .iter()
10475                .any(|r| r["station"] == "hq" && r["reason"] == "it has no execution role")
10476        );
10477        assert!(rejections.iter().any(|r| r["station"] == "worker"
10478            && r["agent"] == "008"
10479            && r["reason"] == "handler \"codex\" is not available on this Station"));
10480        let narrowed = client
10481            .get(format!(
10482                "{base}/v1/user/operations/G/placement-preview?stations=hq&agent=007"
10483            ))
10484            .bearer_auth(&viewer_token)
10485            .send()
10486            .await
10487            .unwrap();
10488        let narrowed: serde_json::Value = narrowed.json().await.unwrap();
10489        assert!(narrowed["choices"].as_array().unwrap().is_empty());
10490        assert!(narrowed["rejections"].as_array().unwrap().iter().any(|r| {
10491            r["station"] == "worker"
10492                && r["reason"] == "the Mission narrows placement to Stations [hq]"
10493        }));
10494        let bad_query = client
10495            .get(format!(
10496                "{base}/v1/user/operations/G/placement-preview?unknown=1"
10497            ))
10498            .bearer_auth(&viewer_token)
10499            .send()
10500            .await
10501            .unwrap();
10502        assert_eq!(bad_query.status(), StatusCode::BAD_REQUEST);
10503        assert_eq!(
10504            station_board["stations"][0]["theaters"],
10505            serde_json::json!([
10506                {"id": "local", "access": "local", "labels": {}, "agents": "auto", "egress": "direct"},
10507                {
10508                    "id": "build-box", "access": "ssh", "host": "build.example.net",
10509                    "labels": {"os": "linux"},
10510                    "capabilities": {
10511                        "terminal": true, "run": true, "files": true, "forward": true,
10512                        "os": "linux", "arch": "x86_64"
10513                    },
10514                    "agents": "auto", "egress": "direct", "harnesses": ["claude"],
10515                    "resources": {
10516                        "cpus": 1.5, "load_1m": 0.5, "memory_total_mb": 4096,
10517                        "memory_available_mb": 2048, "sampled_at": 1_700_000_010
10518                    },
10519                    "runs": 1
10520                }
10521            ]),
10522            "a Theater without resources or Runs carries neither key"
10523        );
10524        assert_eq!(
10525            station_board["stations"][0]["resources"],
10526            serde_json::json!({
10527                "cpus": 8.0, "cpu_percent": 25.0, "load_1m": 1.5, "memory_total_mb": 16384,
10528                "memory_available_mb": 12288, "sampled_at": 1_700_000_000
10529            })
10530        );
10531        assert_eq!(
10532            station_board["stations"][0]["config"],
10533            serde_json::json!({
10534                "revision": "18446744073709551615",
10535                "refused": ["roster revision 7: Agent \"009\": clearance"],
10536                "needs_restart": ["theater"]
10537            }),
10538            "the configuration a Station runs, as it reported it"
10539        );
10540        assert!(
10541            !serde_json::to_string(&station_board)
10542                .unwrap()
10543                .contains("private-host")
10544        );
10545        // A substring test would also match the digits of a live timestamp.
10546        fn holds_number(value: &serde_json::Value, wanted: u64) -> bool {
10547            match value {
10548                serde_json::Value::Number(number) => number.as_u64() == Some(wanted),
10549                serde_json::Value::Array(items) => {
10550                    items.iter().any(|item| holds_number(item, wanted))
10551                }
10552                serde_json::Value::Object(fields) => {
10553                    fields.values().any(|item| holds_number(item, wanted))
10554                }
10555                _ => false,
10556            }
10557        }
10558        assert!(
10559            !serde_json::to_string(&station_board)
10560                .unwrap()
10561                .contains("process_id")
10562        );
10563        assert!(!holds_number(&station_board, 7132));
10564
10565        FileRegistry::open(directory.path())
10566            .record_usage(
10567                Some("G"),
10568                "mission-g",
10569                "run-g",
10570                &ai6::UsageTotals {
10571                    input: 120,
10572                    output: 30,
10573                    cost_micro_usd: 4_500,
10574                    ..ai6::UsageTotals::default()
10575                },
10576                1_790_000_000,
10577            )
10578            .unwrap();
10579        FileRegistry::open(directory.path())
10580            .record_usage(
10581                Some("G"),
10582                "mission-g",
10583                "attempt-2",
10584                &ai6::UsageTotals {
10585                    output: 10,
10586                    cache_write: 40,
10587                    cache_read: 9_000,
10588                    ..ai6::UsageTotals::default()
10589                },
10590                1_790_000_000,
10591            )
10592            .unwrap();
10593        // The first run was lost with its Station; the second runs elsewhere.
10594        let registry = FileRegistry::open(directory.path());
10595        registry
10596            .open_run(
10597                ai6::NewRun::new("attempt-1", "mission-g", "hq").with_theater("local"),
10598                Duration::from_nanos(1),
10599            )
10600            .unwrap();
10601        std::thread::sleep(Duration::from_millis(5));
10602        registry
10603            .lose_run("attempt-1", "Station \"hq\" went dark")
10604            .unwrap();
10605        registry
10606            .open_run(
10607                ai6::NewRun::new("attempt-2", "mission-g", "worker")
10608                    .with_theater("local")
10609                    .with_provider_id("run-g")
10610                    .with_number(2, Some("attempt-1".to_owned()))
10611                    .with_account(ai6::AccountRef::new("gateway", "key"))
10612                    .with_launch(
10613                        ai6::RunLaunch::new("claude", "pipe", "/work")
10614                            .with_model(Some("gemini-free".to_owned()), None)
10615                            .with_pool(Some("gateway".to_owned())),
10616                    ),
10617                Duration::from_secs(60),
10618            )
10619            .unwrap();
10620        let mission_detail = client
10621            .get(format!("{base}/v1/operations/G/missions/mission-g"))
10622            .bearer_auth(&viewer_token)
10623            .send()
10624            .await
10625            .unwrap();
10626        assert_eq!(mission_detail.status(), StatusCode::OK);
10627        let mission_detail: serde_json::Value = mission_detail.json().await.unwrap();
10628        assert_eq!(
10629            mission_detail["history"],
10630            serde_json::json!([
10631                {
10632                    "number": 1, "run_id": "attempt-1", "handle": null,
10633                    "provider_id": null,
10634                    "predecessor": null, "station": "hq", "theater": "local",
10635                    "status": "lost", "lost": "Station \"hq\" went dark",
10636                    "checkpoint_branch": null, "route": null, "account": null, "state": "queued"
10637                },
10638                {
10639                    "number": 2, "run_id": "attempt-2", "handle": null,
10640                    "provider_id": "run-g",
10641                    "predecessor": "attempt-1", "station": "worker", "theater": "local",
10642                    "status": "active", "lost": null, "checkpoint_branch": null,
10643                    "route": {"handler": "claude", "model": "gemini-free", "pool": "gateway"},
10644                    "account": {"pool": "gateway", "account": "key"}
10645                }
10646            ])
10647        );
10648        assert_eq!(mission_detail["usage"]["total"]["input"], 120);
10649        assert_eq!(mission_detail["usage"]["total"]["cost_micro_usd"], 4_500);
10650        assert_eq!(mission_detail["usage"]["runs"]["run-g"]["output"], 30);
10651        assert_eq!(
10652            mission_detail["conversation_tokens"], 50,
10653            "the latest run's own tokens: the run before it had no provider session to share"
10654        );
10655        assert_eq!(
10656            mission_detail["brief"]["prompt"],
10657            "Review the requested change"
10658        );
10659        assert_eq!(mission_detail["brief"]["role_id"], "case-officer");
10660        assert_eq!(mission_detail["brief"]["environment_keys"][0], "API_TOKEN");
10661        assert_eq!(mission_detail["brief"]["station_id"], "worker");
10662        assert_eq!(mission_detail["brief"]["theater_id"], "local");
10663        assert_eq!(mission_detail["brief"]["mode"], "remote-hands");
10664        assert_eq!(
10665            mission_detail["brief"]["provenance"]["origin"],
10666            "registry_drop"
10667        );
10668        assert_eq!(
10669            mission_detail["brief"]["provenance"]["received_by"],
10670            "worker"
10671        );
10672        assert!(
10673            !serde_json::to_string(&mission_detail)
10674                .unwrap()
10675                .contains("secret-value")
10676        );
10677        let hidden_mission = client
10678            .get(format!("{base}/v1/operations/L/missions/mission-l"))
10679            .bearer_auth(&viewer_token)
10680            .send()
10681            .await
10682            .unwrap();
10683        assert_eq!(hidden_mission.status(), StatusCode::NOT_FOUND);
10684
10685        let registry = FileRegistry::open(directory.path());
10686        registry
10687            .open_run(
10688                ai6::NewRun::new("record-g", "mission-g", "worker")
10689                    .with_provider_id("run-g")
10690                    .with_number(3, None)
10691                    .with_exposure(vec![ai6::Exposure {
10692                        source: "tool:WebFetch".to_owned(),
10693                        at: 1_790_000_000.0,
10694                    }]),
10695                std::time::Duration::from_secs(60),
10696            )
10697            .unwrap();
10698        let viewer_board = client
10699            .get(format!("{base}/v1/board"))
10700            .bearer_auth(&viewer_token)
10701            .send()
10702            .await
10703            .unwrap();
10704        assert_eq!(viewer_board.status(), StatusCode::OK);
10705        let viewer_board: serde_json::Value = viewer_board.json().await.unwrap();
10706        assert_eq!(viewer_board.as_array().unwrap().len(), 1);
10707        assert_eq!(viewer_board[0]["operation_id"], "G");
10708        assert_eq!(
10709            viewer_board[0]["exposure"],
10710            serde_json::json!(["tool:WebFetch"])
10711        );
10712        assert_eq!(
10713            viewer_board[0]["station_id"], "worker",
10714            "from its Registry record"
10715        );
10716        assert_eq!(
10717            viewer_board[0]["agent"], "technical-officer",
10718            "from its Mission's brief"
10719        );
10720
10721        let viewer_missions = client
10722            .get(format!("{base}/v1/missions"))
10723            .bearer_auth(&viewer_token)
10724            .send()
10725            .await
10726            .unwrap();
10727        assert_eq!(viewer_missions.status(), StatusCode::OK);
10728        let viewer_missions: serde_json::Value = viewer_missions.json().await.unwrap();
10729        // The briefs the operator queued above are listed too, each with its `pending`.
10730        let (started, queued): (Vec<_>, Vec<_>) = viewer_missions
10731            .as_array()
10732            .unwrap()
10733            .iter()
10734            .partition(|mission| !mission["runs"].as_array().unwrap().is_empty());
10735        assert_eq!(started.len(), 1);
10736        assert_eq!(started[0]["operation_id"], "G");
10737        assert_eq!(started[0]["mission_id"], "mission-g");
10738        assert_eq!(started[0]["runs"][0]["run_id"], "run-g");
10739        assert!(
10740            queued.iter().all(|mission| mission["operation_id"] == "G"
10741                && mission["pending"]["kind"] == "unplaced")
10742        );
10743
10744        let viewer_read = client
10745            .post(format!("{base}/v1/user/attach-grants"))
10746            .bearer_auth(&viewer_token)
10747            .json(&serde_json::json!({
10748                "operation_id": "G",
10749                "mission_id": "mission-g",
10750                "run_id": "run-g",
10751                "mode": "read"
10752            }))
10753            .send()
10754            .await
10755            .unwrap();
10756        assert_eq!(viewer_read.status(), StatusCode::OK);
10757        let read_token = viewer_read.json::<serde_json::Value>().await.unwrap()["token"]
10758            .as_str()
10759            .unwrap()
10760            .to_owned();
10761        let exchanged = client
10762            .post(format!("{base}/v1/attach"))
10763            .header("origin", "https://localhost")
10764            .header("x-forwarded-proto", "https")
10765            .json(&serde_json::json!({"token": read_token.clone()}))
10766            .send()
10767            .await
10768            .unwrap();
10769        assert_eq!(exchanged.status(), StatusCode::NO_CONTENT);
10770        let set_cookie = exchanged
10771            .headers()
10772            .get(SET_COOKIE)
10773            .unwrap()
10774            .to_str()
10775            .unwrap();
10776        assert!(set_cookie.contains("HttpOnly"));
10777        assert!(set_cookie.contains("Secure"));
10778        assert!(set_cookie.contains("SameSite=Strict"));
10779        let cookie = set_cookie.split(';').next().unwrap().to_owned();
10780        let replayed = client
10781            .post(format!("{base}/v1/attach"))
10782            .header("origin", "https://localhost")
10783            .header("x-forwarded-proto", "https")
10784            .json(&serde_json::json!({"token": read_token}))
10785            .send()
10786            .await
10787            .unwrap();
10788        assert_eq!(replayed.status(), StatusCode::UNAUTHORIZED);
10789        let mut request = format!("ws://{address}/v1/socket/run-g?after=0")
10790            .into_client_request()
10791            .unwrap();
10792        request
10793            .headers_mut()
10794            .insert(ORIGIN, HeaderValue::from_static("https://localhost"));
10795        request
10796            .headers_mut()
10797            .insert("x-forwarded-proto", HeaderValue::from_static("https"));
10798        request
10799            .headers_mut()
10800            .insert(COOKIE, HeaderValue::from_str(&cookie).unwrap());
10801        let (mut socket, response) = tokio_tungstenite::connect_async(request).await.unwrap();
10802        assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
10803        socket.close(None).await.unwrap();
10804
10805        let viewer_write = client
10806            .post(format!("{base}/v1/user/attach-grants"))
10807            .bearer_auth(&viewer_token)
10808            .json(&serde_json::json!({
10809                "operation_id": "G",
10810                "mission_id": "mission-g",
10811                "run_id": "run-g",
10812                "mode": "write"
10813            }))
10814            .send()
10815            .await
10816            .unwrap();
10817        assert_eq!(viewer_write.status(), StatusCode::FORBIDDEN);
10818
10819        let operator_login = login("operator").send().await.unwrap();
10820        assert_eq!(operator_login.status(), StatusCode::CREATED);
10821        let operator_token: String =
10822            operator_login.json::<serde_json::Value>().await.unwrap()["token"]
10823                .as_str()
10824                .unwrap()
10825                .to_owned();
10826        let operator_g_write = client
10827            .post(format!("{base}/v1/user/attach-grants"))
10828            .bearer_auth(&operator_token)
10829            .json(&serde_json::json!({
10830                "operation_id": "G",
10831                "mission_id": "mission-g",
10832                "run_id": "run-g",
10833                "mode": "write"
10834            }))
10835            .send()
10836            .await
10837            .unwrap();
10838        assert_eq!(operator_g_write.status(), StatusCode::OK);
10839        let operator_l_write = client
10840            .post(format!("{base}/v1/user/attach-grants"))
10841            .bearer_auth(&operator_token)
10842            .json(&serde_json::json!({
10843                "operation_id": "L",
10844                "mission_id": "mission-l",
10845                "run_id": "run-l",
10846                "mode": "write"
10847            }))
10848            .send()
10849            .await
10850            .unwrap();
10851        assert_eq!(operator_l_write.status(), StatusCode::FORBIDDEN);
10852
10853        let signed_out = client
10854            .post(format!("{base}/v1/auth/logout"))
10855            .bearer_auth(&viewer_token)
10856            .send()
10857            .await
10858            .unwrap();
10859        assert_eq!(signed_out.status(), StatusCode::NO_CONTENT);
10860        let expired_board = client
10861            .get(format!("{base}/v1/board"))
10862            .bearer_auth(&viewer_token)
10863            .send()
10864            .await
10865            .unwrap();
10866        assert_eq!(expired_board.status(), StatusCode::UNAUTHORIZED);
10867
10868        server.abort();
10869    }
10870
10871    #[tokio::test]
10872    async fn issued_access_token_is_shared_across_gateways_and_revocation_propagates() {
10873        let directory = tempfile::tempdir().unwrap();
10874        let registry = FileRegistry::open(directory.path());
10875        let first = Gateway::with_registry(
10876            GatewayConfig::new(
10877                "https://localhost",
10878                "m-token-that-is-long-enough-for-testing",
10879                test_limits(),
10880                Duration::from_secs(30),
10881                Duration::from_secs(30),
10882            )
10883            .unwrap(),
10884            Arc::new(registry.clone()),
10885        );
10886        let second = Gateway::with_registry(
10887            GatewayConfig::new(
10888                "https://localhost",
10889                "m-token-that-is-long-enough-for-testing",
10890                test_limits(),
10891                Duration::from_secs(30),
10892                Duration::from_secs(30),
10893            )
10894            .unwrap(),
10895            Arc::new(registry),
10896        );
10897        let listener_a = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
10898        let listener_b = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
10899        let base_a = format!("http://{}", listener_a.local_addr().unwrap());
10900        let base_b = format!("http://{}", listener_b.local_addr().unwrap());
10901        let server_a = tokio::spawn(async move { axum::serve(listener_a, first.router()).await });
10902        let server_b = tokio::spawn(async move { axum::serve(listener_b, second.router()).await });
10903        let client = reqwest::Client::new();
10904        let station_token = "m-token-that-is-long-enough-for-testing";
10905
10906        let issued = client
10907            .post(format!("{base_a}/v1/station/access-tokens"))
10908            .bearer_auth(station_token)
10909            .json(&serde_json::json!({"person_id":"person-007","ttl_seconds":600}))
10910            .send()
10911            .await
10912            .unwrap();
10913        assert_eq!(issued.status(), StatusCode::CREATED);
10914        let issued: serde_json::Value = issued.json().await.unwrap();
10915        let token_id = issued["token_id"].as_str().unwrap().to_owned();
10916        let secret = issued["token"].as_str().unwrap().to_owned();
10917
10918        let run = client
10919            .get(format!("{base_b}/v1/auth/session"))
10920            .bearer_auth(&secret)
10921            .send()
10922            .await
10923            .unwrap();
10924        assert_eq!(run.status(), StatusCode::OK);
10925        let run: serde_json::Value = run.json().await.unwrap();
10926        assert_eq!(run["token_id"], token_id);
10927        assert_eq!(run["person_id"], "person-007");
10928
10929        let revoked = client
10930            .delete(format!("{base_a}/v1/station/access-tokens/{token_id}"))
10931            .bearer_auth(station_token)
10932            .send()
10933            .await
10934            .unwrap();
10935        assert_eq!(revoked.status(), StatusCode::OK);
10936        assert_eq!(
10937            revoked.json::<serde_json::Value>().await.unwrap()["revoked"],
10938            true
10939        );
10940
10941        let rejected = client
10942            .get(format!("{base_b}/v1/auth/session"))
10943            .bearer_auth(&secret)
10944            .send()
10945            .await
10946            .unwrap();
10947        assert_eq!(rejected.status(), StatusCode::UNAUTHORIZED);
10948        server_a.abort();
10949        server_b.abort();
10950    }
10951
10952    #[tokio::test]
10953    async fn http_ingress_and_websocket_replay_work_over_loopback() {
10954        let gateway = gateway();
10955        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
10956        let address = listener.local_addr().unwrap();
10957        let observed = gateway.clone();
10958        let server = tokio::spawn(async move { axum::serve(listener, gateway.router()).await });
10959        let base = format!("http://{address}");
10960        let client = reqwest::Client::new();
10961
10962        let unauthorized = client
10963            .post(format!("{base}/v1/station/runs"))
10964            .json(&serde_json::json!({"operation_id":"station-a","mission_id":"mission-a","run_id":"provider-id-a"}))
10965            .send()
10966            .await
10967            .unwrap();
10968        assert_eq!(unauthorized.status(), StatusCode::UNAUTHORIZED);
10969
10970        let authorized = client
10971            .post(format!("{base}/v1/station/runs"))
10972            .bearer_auth("m-token-that-is-long-enough-for-testing")
10973            .json(&serde_json::json!({"operation_id":"station-a","mission_id":"mission-a","run_id":"provider-id-a"}))
10974            .send()
10975            .await
10976            .unwrap();
10977        assert_eq!(authorized.status(), StatusCode::CREATED);
10978
10979        let grant = client
10980            .post(format!("{base}/v1/station/attach-grants"))
10981            .bearer_auth("m-token-that-is-long-enough-for-testing")
10982            .json(&serde_json::json!({"operation_id":"station-a","mission_id":"mission-a","run_id":"provider-id-a","mode":"read"}))
10983            .send()
10984            .await
10985            .unwrap();
10986        assert_eq!(grant.status(), StatusCode::OK);
10987        let token: serde_json::Value = grant.json().await.unwrap();
10988
10989        let wrong_origin = client
10990            .post(format!("{base}/v1/attach"))
10991            .header("origin", "https://other.example")
10992            .header("x-forwarded-proto", "https")
10993            .json(&serde_json::json!({"token":token["token"]}))
10994            .send()
10995            .await
10996            .unwrap();
10997        assert_eq!(wrong_origin.status(), StatusCode::FORBIDDEN);
10998
10999        let exchanged = client
11000            .post(format!("{base}/v1/attach"))
11001            .header("origin", "https://localhost")
11002            .header("x-forwarded-proto", "https")
11003            .json(&serde_json::json!({"token":token["token"]}))
11004            .send()
11005            .await
11006            .unwrap();
11007        assert_eq!(exchanged.status(), StatusCode::NO_CONTENT);
11008        let cookie = exchanged
11009            .headers()
11010            .get("set-cookie")
11011            .unwrap()
11012            .to_str()
11013            .unwrap();
11014        assert!(cookie.contains("HttpOnly"));
11015        assert!(cookie.contains("Secure"));
11016        assert!(cookie.contains("SameSite=Strict"));
11017        assert!(cookie.contains("Path=/v1/socket"));
11018        let cookie = cookie.split(';').next().unwrap();
11019
11020        let run = RunId::new("provider-id-a").unwrap();
11021        let event = LifecycleEvent {
11022            operation_id: OperationId::new("station-a").unwrap(),
11023            mission_id: MissionId::new("mission-a").unwrap(),
11024            run_id: run.clone(),
11025            state: RunState::Working,
11026            reason: None,
11027            sequence: 1,
11028        };
11029        let (schema, value) = lifecycle_frames(&event).unwrap();
11030        let terminal = TerminalData::new(
11031            run.clone(),
11032            2,
11033            TerminalDirection::Output,
11034            vec![0xff, 0x00, 0x80],
11035        )
11036        .unwrap();
11037        let (terminal_schema, terminal_value) = terminal_frames(&terminal).unwrap();
11038        for (sequence, frame) in [
11039            (0, schema),
11040            (1, value),
11041            (0, terminal_schema),
11042            (2, terminal_value.clone()),
11043        ] {
11044            let ingested = client
11045                .post(format!("{base}/v1/station/runs/{run}/events/{sequence}"))
11046                .bearer_auth("m-token-that-is-long-enough-for-testing")
11047                .body(frame)
11048                .send()
11049                .await
11050                .unwrap();
11051            assert_eq!(ingested.status(), StatusCode::ACCEPTED);
11052        }
11053
11054        let request = format!("ws://{address}/v1/socket/{run}?after=0")
11055            .into_client_request()
11056            .unwrap();
11057        let mut request = request;
11058        request
11059            .headers_mut()
11060            .insert("origin", "https://localhost".parse().unwrap());
11061        request
11062            .headers_mut()
11063            .insert("x-forwarded-proto", "https".parse().unwrap());
11064        request
11065            .headers_mut()
11066            .insert("cookie", cookie.parse().unwrap());
11067        let (mut socket, response) = tokio_tungstenite::connect_async(request).await.unwrap();
11068        assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
11069        let mut received_frames = Vec::new();
11070        for _ in 0..4 {
11071            let message = tokio::time::timeout(Duration::from_secs(60), socket.next())
11072                .await
11073                .unwrap()
11074                .unwrap()
11075                .unwrap();
11076            let tokio_tungstenite::tungstenite::Message::Binary(frame) = message else {
11077                panic!("websocket replay must use binary frames");
11078            };
11079            received_frames.push(frame.to_vec());
11080        }
11081        assert!(received_frames.contains(&terminal_value));
11082        socket.close(None).await.unwrap();
11083        tokio::time::timeout(Duration::from_secs(60), async {
11084            loop {
11085                if observed
11086                    .inner
11087                    .lock()
11088                    .await
11089                    .runs
11090                    .get(&run)
11091                    .is_some_and(|record| record.active_clients == 0)
11092                {
11093                    break;
11094                }
11095                tokio::time::sleep(Duration::from_millis(5)).await;
11096            }
11097        })
11098        .await
11099        .unwrap();
11100        server.abort();
11101    }
11102
11103    #[test]
11104    fn configuration_requires_https_and_finite_bounds() {
11105        assert!(
11106            GatewayConfig::new(
11107                "https://localhost",
11108                "m-token-that-is-long-enough-for-testing",
11109                GatewayLimits::default(),
11110                Duration::from_secs(30),
11111                Duration::from_secs(30),
11112            )
11113            .is_ok()
11114        );
11115        assert!(
11116            GatewayConfig::new(
11117                "http://localhost",
11118                "m-token-that-is-long-enough-for-testing",
11119                test_limits(),
11120                Duration::from_secs(1),
11121                Duration::from_secs(1),
11122            )
11123            .is_err()
11124        );
11125        assert!(
11126            format!(
11127                "{:?}",
11128                GatewayConfig::new(
11129                    "https://localhost",
11130                    "very-secret-token-value-0123456789",
11131                    test_limits(),
11132                    Duration::from_secs(1),
11133                    Duration::from_secs(1),
11134                )
11135                .unwrap()
11136            )
11137            .contains("[REDACTED]")
11138        );
11139    }
11140
11141    #[test]
11142    fn the_former_ceilings_are_settings() {
11143        let token = "m-token-that-is-long-enough-for-testing";
11144        let mut limits = GatewayLimits {
11145            max_frame_bytes: 4 * 1024 * 1024,
11146            buffer_budget_bytes: ai6::Limit::UNBOUNDED,
11147            ..GatewayLimits::default()
11148        };
11149        // A frame past 1 MiB and a lease past five minutes are refused by no ceiling now.
11150        assert!(
11151            GatewayConfig::new(
11152                "https://localhost",
11153                token,
11154                limits,
11155                Duration::from_secs(3_600),
11156                Duration::from_secs(900),
11157            )
11158            .is_ok()
11159        );
11160        // The budget is still a bound while it is one: the same frames overrun 512 MiB.
11161        limits.buffer_budget_bytes = GatewayLimits::default().buffer_budget_bytes;
11162        assert!(
11163            GatewayConfig::new(
11164                "https://localhost",
11165                token,
11166                limits,
11167                Duration::from_secs(30),
11168                Duration::from_secs(30),
11169            )
11170            .is_err()
11171        );
11172        // The Station token's least size is a setting too.
11173        let short = GatewayLimits {
11174            station_token_min_bytes: 4,
11175            ..GatewayLimits::default()
11176        };
11177        assert!(
11178            GatewayConfig::new(
11179                "https://localhost",
11180                "abcd",
11181                short,
11182                Duration::from_secs(30),
11183                Duration::from_secs(30),
11184            )
11185            .is_ok()
11186        );
11187    }
11188
11189    #[tokio::test]
11190    async fn full_agent_input_queue_rejects_new_input_without_growing() {
11191        let mut limits = test_limits();
11192        limits.input_queue_capacity = 1;
11193        let gateway = Gateway::new(
11194            GatewayConfig::new(
11195                "https://localhost",
11196                "m-token-that-is-long-enough-for-testing",
11197                limits,
11198                Duration::from_secs(30),
11199                Duration::from_secs(30),
11200            )
11201            .unwrap(),
11202        );
11203        let (_, _, run) = register(&gateway).await;
11204        let token = grant(&gateway, AttachMode::Write).await;
11205        let ticket = gateway.exchange_attach_token(&token).await.unwrap();
11206        let writer = gateway.attach(&run, &ticket, 0).await.unwrap();
11207
11208        for sequence in [1, 2] {
11209            let input = TerminalData::new(
11210                run.clone(),
11211                sequence,
11212                TerminalDirection::Input,
11213                vec![sequence as u8],
11214            )
11215            .unwrap();
11216            let (_, frame) = terminal_frames(&input).unwrap();
11217            let result = gateway
11218                .submit_input(&run, &writer.connection_id, frame)
11219                .await;
11220            if sequence == 1 {
11221                result.unwrap();
11222            } else {
11223                assert_eq!(result.unwrap_err(), GatewayError::Backpressure);
11224            }
11225        }
11226        assert!(gateway.receive_agent_input().await.is_some());
11227        assert!(
11228            gateway
11229                .receive_agent_input_within(Duration::from_millis(10))
11230                .await
11231                .is_none(),
11232            "an idle poll ends with nothing instead of waiting for ever"
11233        );
11234        gateway.disconnect(writer).await;
11235    }
11236}