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    /// A turn handed its event's image has looked from the start: it decides
165    /// on that image and is allowed no look of its own.
166    fn open(&self, print_id: PrintId, handed_image: bool) -> OpenedTurn {
167        let scope = Arc::new(Scope {
168            registry: self.clone(),
169            id: self.0.next_scope.fetch_add(1, Ordering::Relaxed),
170            print_id,
171            closed: Mutex::new(false),
172        });
173        if handed_image {
174            self.looked_turns().insert(scope.id);
175        }
176        let closing = Arc::clone(&scope);
177        OpenedTurn::new(scope, Box::new(move || closing.close()))
178    }
179}
180
181/// One turn's issuer, as the port is handed it.
182#[derive(Debug)]
183struct Scope {
184    /// Where the credentials it issues are admitted.
185    registry: TurnCredentials,
186    /// Which turn this is.
187    id: u64,
188    /// The print the turn is about.
189    print_id: PrintId,
190    /// Whether the turn has returned, after which nothing more is issued.
191    closed: Mutex<bool>,
192}
193
194impl Scope {
195    /// Revoke every credential this turn was issued, and issue no more.
196    fn close(&self) {
197        *self
198            .closed
199            .lock()
200            .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
201        self.registry.revoke(self.id);
202    }
203}
204
205impl TurnAccess for Scope {
206    fn issue(&self, session: &TurnSession) -> Result<TurnPass, SupervisorError> {
207        self.issue_drawn(session, getrandom::fill)
208    }
209}
210
211impl Scope {
212    /// Issue the run in `session` a credential, drawn by `draw` — the
213    /// operating system's random source, for every run this server starts.
214    /// A draw that is refused registers nothing.
215    fn issue_drawn(
216        &self,
217        session: &TurnSession,
218        draw: impl FnOnce(&mut [u8]) -> Result<(), getrandom::Error>,
219    ) -> Result<TurnPass, SupervisorError> {
220        use base64::Engine as _;
221
222        let mut drawn = [0_u8; GENERATED_TURN_CREDENTIAL_BYTES];
223        draw(&mut drawn).map_err(|error| SupervisorError::Unavailable {
224            detail: format!(
225                "no credential could be minted for the turn, because the operating system's \
226                 random source refused: {error}"
227            ),
228        })?;
229        let credential = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn);
230        let digested = digest(credential.as_bytes());
231        let pass = TurnPass::new(self.registry.0.server, credential)?;
232        // Held across the insertion, so a turn that returns while a run is
233        // being issued its credential leaves nothing live behind it.
234        let closed = self
235            .closed
236            .lock()
237            .unwrap_or_else(std::sync::PoisonError::into_inner);
238        if *closed {
239            return Err(SupervisorError::Unavailable {
240                detail: "the turn this run belongs to has already returned".to_owned(),
241            });
242        }
243        let mut held = self.registry.held();
244        held.retain(|_, live| live.scope != self.id);
245        held.insert(
246            digested,
247            Held {
248                scope: self.id,
249                binding: TurnBinding {
250                    session: session.clone(),
251                    print_id: self.print_id,
252                    scope: self.id,
253                },
254            },
255        );
256        drop(held);
257        drop(closed);
258        Ok(pass)
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use printobserver_core::TurnAuthority as _;
265    use printobserver_supervisor_api::{CREDENTIAL_ENV, SERVER_ENV, TurnPass, TurnSession};
266    use printobserver_types::PrintId;
267
268    use super::{GENERATED_TURN_CREDENTIAL_BYTES, TurnCredentials};
269
270    /// One session, by a name that is one.
271    fn session(name: &str) -> TurnSession {
272        TurnSession::new(name).expect("a session")
273    }
274
275    /// The value one variable of a pass carries.
276    fn value_of(pass: &TurnPass, name: &str) -> String {
277        pass.environment()
278            .into_iter()
279            .find(|(named, _)| *named == name)
280            .map_or_else(|| panic!("the pass carries no {name}"), |(_, value)| value)
281    }
282
283    /// A look one run of a turn took counts for every run the turn issues
284    /// after it, and for no other turn; it goes when the turn returns.
285    #[test]
286    fn a_look_is_the_turns_whichever_of_its_runs_took_it() {
287        let registry = TurnCredentials::new(None);
288        let print_id = PrintId::new();
289        let opened = registry.open(print_id, false);
290        let access = opened.access();
291        let first = value_of(
292            &access.issue(&session("print-a")).expect("minted"),
293            CREDENTIAL_ENV,
294        );
295        let looking = registry.admit(first.as_bytes()).expect("admitted");
296        assert!(!registry.has_looked(&looking));
297        registry.note_look(&looking);
298        let second = value_of(
299            &access.issue(&session("print-a-2")).expect("minted"),
300            CREDENTIAL_ENV,
301        );
302        let moved = registry.admit(second.as_bytes()).expect("admitted");
303        assert!(
304            registry.has_looked(&moved),
305            "the turn's second run lost its look"
306        );
307
308        let other = registry.open(print_id, false);
309        let elsewhere = value_of(
310            &other.access().issue(&session("print-b")).expect("minted"),
311            CREDENTIAL_ENV,
312        );
313        let unlooked = registry.admit(elsewhere.as_bytes()).expect("admitted");
314        assert!(
315            !registry.has_looked(&unlooked),
316            "another turn took this one's look"
317        );
318
319        drop(opened);
320        assert!(
321            !registry.has_looked(&moved),
322            "a returned turn's look outlived it"
323        );
324    }
325
326    /// A turn handed its event's image has looked from the start, on every
327    /// run it issues; a turn handed none has not.
328    #[test]
329    fn a_turn_handed_an_image_has_looked_from_the_start() {
330        let registry = TurnCredentials::new(None);
331        let print_id = PrintId::new();
332        for (handed_image, session_name) in [(true, "print-a"), (false, "print-b")] {
333            let opened = registry.open(print_id, handed_image);
334            let access = opened.access();
335            let credential = value_of(
336                &access.issue(&session(session_name)).expect("minted"),
337                CREDENTIAL_ENV,
338            );
339            let binding = registry.admit(credential.as_bytes()).expect("admitted");
340            assert_eq!(
341                registry.has_looked(&binding),
342                handed_image,
343                "handed an image: {handed_image}"
344            );
345        }
346    }
347
348    /// A credential is admitted as the session and print it was issued for
349    /// while its turn runs, a second issue replaces the first, and revoking
350    /// the turn admits none of them and issues no more.
351    #[test]
352    fn a_turns_credential_lives_exactly_as_long_as_its_turn() {
353        let registry = TurnCredentials::new(Some("127.0.0.1:1".parse().expect("an address")));
354        let print_id = PrintId::new();
355        let opened = registry.open(print_id, false);
356        let access = opened.access();
357        let pass = access.issue(&session("print-a")).expect("one is minted");
358        let first = value_of(&pass, CREDENTIAL_ENV);
359
360        assert_eq!(value_of(&pass, SERVER_ENV), "http://127.0.0.1:1");
361        // Unpadded URL-safe base64 of the drawn bytes.
362        assert_eq!(
363            first.len(),
364            (GENERATED_TURN_CREDENTIAL_BYTES * 4).div_ceil(3)
365        );
366        assert_eq!(
367            registry
368                .admit(first.as_bytes())
369                .map(|binding| (binding.session_name().to_owned(), binding.print_id())),
370            Some(("print-a".to_owned(), print_id))
371        );
372        let second = value_of(
373            &access.issue(&session("print-a-2")).expect("minted"),
374            CREDENTIAL_ENV,
375        );
376        assert_ne!(first, second);
377        assert_eq!(registry.admit(first.as_bytes()), None);
378        assert_eq!(registry.live(), 1);
379
380        opened.revoke();
381        assert_eq!(registry.admit(second.as_bytes()), None);
382        assert!(access.issue(&session("print-a-3")).is_err());
383        assert_eq!(registry.live(), 0);
384    }
385
386    /// A draw the random source refuses issues nothing and registers nothing,
387    /// so the run it was for is not started.
388    #[test]
389    fn a_refused_draw_issues_and_registers_nothing() {
390        let registry = TurnCredentials::new(None);
391        let scope = super::Scope {
392            registry: registry.clone(),
393            id: 0,
394            print_id: PrintId::new(),
395            closed: std::sync::Mutex::new(false),
396        };
397
398        let Err(refused) =
399            scope.issue_drawn(&session("print-a"), |_| Err(getrandom::Error::UNSUPPORTED))
400        else {
401            panic!("a refused draw issued a credential");
402        };
403
404        assert!(
405            refused.to_string().contains("random source refused"),
406            "{refused}"
407        );
408        assert_eq!(registry.live(), 0);
409    }
410
411    /// Dropping one turn's opened issuer revokes it, and another turn's
412    /// credential is left alone.
413    #[test]
414    fn dropping_one_turn_revokes_its_own_credential_and_no_other() {
415        let registry = TurnCredentials::new(None);
416        let kept = registry.open(PrintId::new(), false);
417        let kept_credential = value_of(
418            &kept.access().issue(&session("kept")).expect("minted"),
419            CREDENTIAL_ENV,
420        );
421        let dropped = registry.open(PrintId::new(), false);
422        let dropped_credential = value_of(
423            &dropped.access().issue(&session("gone")).expect("minted"),
424            CREDENTIAL_ENV,
425        );
426        drop(dropped);
427
428        assert_eq!(registry.admit(dropped_credential.as_bytes()), None);
429        assert!(registry.admit(kept_credential.as_bytes()).is_some());
430    }
431}