Skip to main content

printobserver_server/
turns.rs

1//! The credentials supervision turns authenticate with, held in memory alone.
2//!
3//! # One credential per run, bound before it exists
4//!
5//! A supervision turn's runs reach the server's API with a credential minted
6//! for that run: [`GENERATED_TURN_CREDENTIAL_BYTES`] bytes from the operating
7//! system's cryptographically secure random source, bound to the agent class,
8//! the session the run is in and the print the turn is about. The core opens
9//! one turn's issuer of them at the turn boundary through
10//! [`TurnAuthority::open`], hands it to the supervisor port, and revokes it
11//! when the turn returns — on success, failure and timeout alike, and when the
12//! turn is abandoned, because dropping what was opened revokes too.
13//!
14//! # Nothing here is persisted
15//!
16//! The registry is a map in this process's memory, keyed by the SHA-256 of each
17//! credential rather than by the credential itself: nothing is written, so a
18//! server that restarts admits none of the credentials the one before it
19//! minted, and no turn survives a restart for one to be owed to. Looking a
20//! presented credential up by its digest takes as long whatever was guessed:
21//! what varies is the digest, which says nothing about the credential.
22//!
23//! # A turn acknowledges only after it has looked
24//!
25//! The registry also notes which turns have taken a look at their print, so
26//! the API can refuse an acknowledgement from a turn that judged its event
27//! without one: the frames a turn's context names are already old when it
28//! reads them. The note is the turn's, shared by every run it issues, and goes
29//! with the turn's credentials when it returns.
30
31use std::collections::{HashMap, HashSet};
32use std::net::SocketAddr;
33use std::sync::atomic::{AtomicU64, Ordering};
34use std::sync::{Arc, Mutex, MutexGuard};
35
36use printobserver_core::{OpenedTurn, TurnAuthority};
37use printobserver_supervisor_api::{SupervisorError, TurnAccess, TurnPass, TurnSession};
38use printobserver_types::PrintId;
39use sha2::{Digest as _, Sha256};
40
41/// How many random bytes a turn's credential is drawn from: the same as every
42/// credential this program generates.
43pub const GENERATED_TURN_CREDENTIAL_BYTES: usize = crate::config::GENERATED_CREDENTIAL_BYTES;
44
45/// Who one turn credential authenticates as.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct TurnBinding {
48    /// The session the run that holds it is in.
49    session: TurnSession,
50    /// The print the turn is about.
51    print_id: PrintId,
52    /// The turn that issued it.
53    scope: u64,
54}
55
56impl TurnBinding {
57    /// The session the run holding this credential is in, as a request's
58    /// `Actor::Agent { session_name }` spells it.
59    #[must_use]
60    pub fn session_name(&self) -> &str {
61        self.session.as_str()
62    }
63
64    /// The print the turn holding this credential is about.
65    #[must_use]
66    pub const fn print_id(&self) -> PrintId {
67        self.print_id
68    }
69}
70
71/// One live credential, by the scope that issued it.
72#[derive(Debug)]
73struct Held {
74    /// The turn that issued it.
75    scope: u64,
76    /// Who it authenticates as.
77    binding: TurnBinding,
78}
79
80/// The registry behind every handle onto it.
81#[derive(Debug)]
82struct Registry {
83    /// The live credentials, keyed by the SHA-256 of each.
84    held: Mutex<HashMap<[u8; 32], Held>>,
85    /// The turns that have taken a look at their print, by scope.
86    looked: Mutex<HashSet<u64>>,
87    /// The identifier the next scope takes.
88    next_scope: AtomicU64,
89    /// Where the server answers, as a turn's runs are told.
90    server: Option<SocketAddr>,
91}
92
93/// Every live turn credential, by its digest. Cloning it is another handle
94/// onto the same registry.
95#[derive(Debug, Clone)]
96pub struct TurnCredentials(Arc<Registry>);
97
98/// One credential's digest.
99fn digest(credential: &[u8]) -> [u8; 32] {
100    Sha256::digest(credential).into()
101}
102
103impl TurnCredentials {
104    /// An empty registry whose turns' runs are told the server is at `server`.
105    #[must_use]
106    pub fn new(server: Option<SocketAddr>) -> Self {
107        Self(Arc::new(Registry {
108            held: Mutex::new(HashMap::new()),
109            looked: Mutex::new(HashSet::new()),
110            next_scope: AtomicU64::new(0),
111            server,
112        }))
113    }
114
115    /// The registry, held.
116    fn held(&self) -> MutexGuard<'_, HashMap<[u8; 32], Held>> {
117        self.0
118            .held
119            .lock()
120            .unwrap_or_else(std::sync::PoisonError::into_inner)
121    }
122
123    /// Who a presented credential authenticates as, when it is a live turn's.
124    #[must_use]
125    pub fn admit(&self, presented: &[u8]) -> Option<TurnBinding> {
126        self.held()
127            .get(&digest(presented))
128            .map(|held| held.binding.clone())
129    }
130
131    /// How many turn credentials are live.
132    #[must_use]
133    pub fn live(&self) -> usize {
134        self.held().len()
135    }
136
137    /// The turns that have looked, held.
138    fn looked_turns(&self) -> MutexGuard<'_, HashSet<u64>> {
139        self.0
140            .looked
141            .lock()
142            .unwrap_or_else(std::sync::PoisonError::into_inner)
143    }
144
145    /// Note that the turn `binding` belongs to has taken a look at its print.
146    pub fn note_look(&self, binding: &TurnBinding) {
147        self.looked_turns().insert(binding.scope);
148    }
149
150    /// Whether the turn `binding` belongs to has taken a look at its print.
151    #[must_use]
152    pub fn has_looked(&self, binding: &TurnBinding) -> bool {
153        self.looked_turns().contains(&binding.scope)
154    }
155
156    /// Forget every credential one scope issued, and that it looked.
157    fn revoke(&self, scope: u64) {
158        self.held().retain(|_, held| held.scope != scope);
159        self.looked_turns().remove(&scope);
160    }
161}
162
163impl TurnAuthority for TurnCredentials {
164    fn open(&self, print_id: PrintId) -> OpenedTurn {
165        let scope = Arc::new(Scope {
166            registry: self.clone(),
167            id: self.0.next_scope.fetch_add(1, Ordering::Relaxed),
168            print_id,
169            closed: Mutex::new(false),
170        });
171        let closing = Arc::clone(&scope);
172        OpenedTurn::new(scope, Box::new(move || closing.close()))
173    }
174}
175
176/// One turn's issuer, as the port is handed it.
177#[derive(Debug)]
178struct Scope {
179    /// Where the credentials it issues are admitted.
180    registry: TurnCredentials,
181    /// Which turn this is.
182    id: u64,
183    /// The print the turn is about.
184    print_id: PrintId,
185    /// Whether the turn has returned, after which nothing more is issued.
186    closed: Mutex<bool>,
187}
188
189impl Scope {
190    /// Revoke every credential this turn was issued, and issue no more.
191    fn close(&self) {
192        *self
193            .closed
194            .lock()
195            .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
196        self.registry.revoke(self.id);
197    }
198}
199
200impl TurnAccess for Scope {
201    fn issue(&self, session: &TurnSession) -> Result<TurnPass, SupervisorError> {
202        self.issue_drawn(session, getrandom::fill)
203    }
204}
205
206impl Scope {
207    /// Issue the run in `session` a credential, drawn by `draw` — the
208    /// operating system's random source, for every run this server starts.
209    /// A draw that is refused registers nothing.
210    fn issue_drawn(
211        &self,
212        session: &TurnSession,
213        draw: impl FnOnce(&mut [u8]) -> Result<(), getrandom::Error>,
214    ) -> Result<TurnPass, SupervisorError> {
215        use base64::Engine as _;
216
217        let mut drawn = [0_u8; GENERATED_TURN_CREDENTIAL_BYTES];
218        draw(&mut drawn).map_err(|error| SupervisorError::Unavailable {
219            detail: format!(
220                "no credential could be minted for the turn, because the operating system's \
221                 random source refused: {error}"
222            ),
223        })?;
224        let credential = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn);
225        let digested = digest(credential.as_bytes());
226        let pass = TurnPass::new(self.registry.0.server, credential)?;
227        // Held across the insertion, so a turn that returns while a run is
228        // being issued its credential leaves nothing live behind it.
229        let closed = self
230            .closed
231            .lock()
232            .unwrap_or_else(std::sync::PoisonError::into_inner);
233        if *closed {
234            return Err(SupervisorError::Unavailable {
235                detail: "the turn this run belongs to has already returned".to_owned(),
236            });
237        }
238        let mut held = self.registry.held();
239        held.retain(|_, live| live.scope != self.id);
240        held.insert(
241            digested,
242            Held {
243                scope: self.id,
244                binding: TurnBinding {
245                    session: session.clone(),
246                    print_id: self.print_id,
247                    scope: self.id,
248                },
249            },
250        );
251        drop(held);
252        drop(closed);
253        Ok(pass)
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use printobserver_core::TurnAuthority as _;
260    use printobserver_supervisor_api::{CREDENTIAL_ENV, SERVER_ENV, TurnPass, TurnSession};
261    use printobserver_types::PrintId;
262
263    use super::{GENERATED_TURN_CREDENTIAL_BYTES, TurnCredentials};
264
265    /// One session, by a name that is one.
266    fn session(name: &str) -> TurnSession {
267        TurnSession::new(name).expect("a session")
268    }
269
270    /// The value one variable of a pass carries.
271    fn value_of(pass: &TurnPass, name: &str) -> String {
272        pass.environment()
273            .into_iter()
274            .find(|(named, _)| *named == name)
275            .map_or_else(|| panic!("the pass carries no {name}"), |(_, value)| value)
276    }
277
278    /// A look one run of a turn took counts for every run the turn issues
279    /// after it, and for no other turn; it goes when the turn returns.
280    #[test]
281    fn a_look_is_the_turns_whichever_of_its_runs_took_it() {
282        let registry = TurnCredentials::new(None);
283        let print_id = PrintId::new();
284        let opened = registry.open(print_id);
285        let access = opened.access();
286        let first = value_of(
287            &access.issue(&session("print-a")).expect("minted"),
288            CREDENTIAL_ENV,
289        );
290        let looking = registry.admit(first.as_bytes()).expect("admitted");
291        assert!(!registry.has_looked(&looking));
292        registry.note_look(&looking);
293        let second = value_of(
294            &access.issue(&session("print-a-2")).expect("minted"),
295            CREDENTIAL_ENV,
296        );
297        let moved = registry.admit(second.as_bytes()).expect("admitted");
298        assert!(
299            registry.has_looked(&moved),
300            "the turn's second run lost its look"
301        );
302
303        let other = registry.open(print_id);
304        let elsewhere = value_of(
305            &other.access().issue(&session("print-b")).expect("minted"),
306            CREDENTIAL_ENV,
307        );
308        let unlooked = registry.admit(elsewhere.as_bytes()).expect("admitted");
309        assert!(
310            !registry.has_looked(&unlooked),
311            "another turn took this one's look"
312        );
313
314        drop(opened);
315        assert!(
316            !registry.has_looked(&moved),
317            "a returned turn's look outlived it"
318        );
319    }
320
321    /// A credential is admitted as the session and print it was issued for
322    /// while its turn runs, a second issue replaces the first, and revoking
323    /// the turn admits none of them and issues no more.
324    #[test]
325    fn a_turns_credential_lives_exactly_as_long_as_its_turn() {
326        let registry = TurnCredentials::new(Some("127.0.0.1:1".parse().expect("an address")));
327        let print_id = PrintId::new();
328        let opened = registry.open(print_id);
329        let access = opened.access();
330        let pass = access.issue(&session("print-a")).expect("one is minted");
331        let first = value_of(&pass, CREDENTIAL_ENV);
332
333        assert_eq!(value_of(&pass, SERVER_ENV), "http://127.0.0.1:1");
334        // Unpadded URL-safe base64 of the drawn bytes.
335        assert_eq!(
336            first.len(),
337            (GENERATED_TURN_CREDENTIAL_BYTES * 4).div_ceil(3)
338        );
339        assert_eq!(
340            registry
341                .admit(first.as_bytes())
342                .map(|binding| (binding.session_name().to_owned(), binding.print_id())),
343            Some(("print-a".to_owned(), print_id))
344        );
345        let second = value_of(
346            &access.issue(&session("print-a-2")).expect("minted"),
347            CREDENTIAL_ENV,
348        );
349        assert_ne!(first, second);
350        assert_eq!(registry.admit(first.as_bytes()), None);
351        assert_eq!(registry.live(), 1);
352
353        opened.revoke();
354        assert_eq!(registry.admit(second.as_bytes()), None);
355        assert!(access.issue(&session("print-a-3")).is_err());
356        assert_eq!(registry.live(), 0);
357    }
358
359    /// A draw the random source refuses issues nothing and registers nothing,
360    /// so the run it was for is not started.
361    #[test]
362    fn a_refused_draw_issues_and_registers_nothing() {
363        let registry = TurnCredentials::new(None);
364        let scope = super::Scope {
365            registry: registry.clone(),
366            id: 0,
367            print_id: PrintId::new(),
368            closed: std::sync::Mutex::new(false),
369        };
370
371        let Err(refused) =
372            scope.issue_drawn(&session("print-a"), |_| Err(getrandom::Error::UNSUPPORTED))
373        else {
374            panic!("a refused draw issued a credential");
375        };
376
377        assert!(
378            refused.to_string().contains("random source refused"),
379            "{refused}"
380        );
381        assert_eq!(registry.live(), 0);
382    }
383
384    /// Dropping one turn's opened issuer revokes it, and another turn's
385    /// credential is left alone.
386    #[test]
387    fn dropping_one_turn_revokes_its_own_credential_and_no_other() {
388        let registry = TurnCredentials::new(None);
389        let kept = registry.open(PrintId::new());
390        let kept_credential = value_of(
391            &kept.access().issue(&session("kept")).expect("minted"),
392            CREDENTIAL_ENV,
393        );
394        let dropped = registry.open(PrintId::new());
395        let dropped_credential = value_of(
396            &dropped.access().issue(&session("gone")).expect("minted"),
397            CREDENTIAL_ENV,
398        );
399        drop(dropped);
400
401        assert_eq!(registry.admit(dropped_credential.as_bytes()), None);
402        assert!(registry.admit(kept_credential.as_bytes()).is_some());
403    }
404}