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
23use std::collections::HashMap;
24use std::net::SocketAddr;
25use std::sync::atomic::{AtomicU64, Ordering};
26use std::sync::{Arc, Mutex, MutexGuard};
27
28use printobserver_core::{OpenedTurn, TurnAuthority};
29use printobserver_supervisor_api::{SupervisorError, TurnAccess, TurnPass, TurnSession};
30use printobserver_types::PrintId;
31use sha2::{Digest as _, Sha256};
32
33/// How many random bytes a turn's credential is drawn from: the same as every
34/// credential this program generates.
35pub const GENERATED_TURN_CREDENTIAL_BYTES: usize = crate::config::GENERATED_CREDENTIAL_BYTES;
36
37/// Who one turn credential authenticates as.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct TurnBinding {
40    /// The session the run that holds it is in.
41    session: TurnSession,
42    /// The print the turn is about.
43    print_id: PrintId,
44}
45
46impl TurnBinding {
47    /// The session the run holding this credential is in, as a request's
48    /// `Actor::Agent { session_name }` spells it.
49    #[must_use]
50    pub fn session_name(&self) -> &str {
51        self.session.as_str()
52    }
53
54    /// The print the turn holding this credential is about.
55    #[must_use]
56    pub const fn print_id(&self) -> PrintId {
57        self.print_id
58    }
59}
60
61/// One live credential, by the scope that issued it.
62#[derive(Debug)]
63struct Held {
64    /// The turn that issued it.
65    scope: u64,
66    /// Who it authenticates as.
67    binding: TurnBinding,
68}
69
70/// The registry behind every handle onto it.
71#[derive(Debug)]
72struct Registry {
73    /// The live credentials, keyed by the SHA-256 of each.
74    held: Mutex<HashMap<[u8; 32], Held>>,
75    /// The identifier the next scope takes.
76    next_scope: AtomicU64,
77    /// Where the server answers, as a turn's runs are told.
78    server: Option<SocketAddr>,
79}
80
81/// Every live turn credential, by its digest. Cloning it is another handle
82/// onto the same registry.
83#[derive(Debug, Clone)]
84pub struct TurnCredentials(Arc<Registry>);
85
86/// One credential's digest.
87fn digest(credential: &[u8]) -> [u8; 32] {
88    Sha256::digest(credential).into()
89}
90
91impl TurnCredentials {
92    /// An empty registry whose turns' runs are told the server is at `server`.
93    #[must_use]
94    pub fn new(server: Option<SocketAddr>) -> Self {
95        Self(Arc::new(Registry {
96            held: Mutex::new(HashMap::new()),
97            next_scope: AtomicU64::new(0),
98            server,
99        }))
100    }
101
102    /// The registry, held.
103    fn held(&self) -> MutexGuard<'_, HashMap<[u8; 32], Held>> {
104        self.0
105            .held
106            .lock()
107            .unwrap_or_else(std::sync::PoisonError::into_inner)
108    }
109
110    /// Who a presented credential authenticates as, when it is a live turn's.
111    #[must_use]
112    pub fn admit(&self, presented: &[u8]) -> Option<TurnBinding> {
113        self.held()
114            .get(&digest(presented))
115            .map(|held| held.binding.clone())
116    }
117
118    /// How many turn credentials are live.
119    #[must_use]
120    pub fn live(&self) -> usize {
121        self.held().len()
122    }
123
124    /// Forget every credential one scope issued.
125    fn revoke(&self, scope: u64) {
126        self.held().retain(|_, held| held.scope != scope);
127    }
128}
129
130impl TurnAuthority for TurnCredentials {
131    fn open(&self, print_id: PrintId) -> OpenedTurn {
132        let scope = Arc::new(Scope {
133            registry: self.clone(),
134            id: self.0.next_scope.fetch_add(1, Ordering::Relaxed),
135            print_id,
136            closed: Mutex::new(false),
137        });
138        let closing = Arc::clone(&scope);
139        OpenedTurn::new(scope, Box::new(move || closing.close()))
140    }
141}
142
143/// One turn's issuer, as the port is handed it.
144#[derive(Debug)]
145struct Scope {
146    /// Where the credentials it issues are admitted.
147    registry: TurnCredentials,
148    /// Which turn this is.
149    id: u64,
150    /// The print the turn is about.
151    print_id: PrintId,
152    /// Whether the turn has returned, after which nothing more is issued.
153    closed: Mutex<bool>,
154}
155
156impl Scope {
157    /// Revoke every credential this turn was issued, and issue no more.
158    fn close(&self) {
159        *self
160            .closed
161            .lock()
162            .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
163        self.registry.revoke(self.id);
164    }
165}
166
167impl TurnAccess for Scope {
168    fn issue(&self, session: &TurnSession) -> Result<TurnPass, SupervisorError> {
169        self.issue_drawn(session, getrandom::fill)
170    }
171}
172
173impl Scope {
174    /// Issue the run in `session` a credential, drawn by `draw` — the
175    /// operating system's random source, for every run this server starts.
176    /// A draw that is refused registers nothing.
177    fn issue_drawn(
178        &self,
179        session: &TurnSession,
180        draw: impl FnOnce(&mut [u8]) -> Result<(), getrandom::Error>,
181    ) -> Result<TurnPass, SupervisorError> {
182        use base64::Engine as _;
183
184        let mut drawn = [0_u8; GENERATED_TURN_CREDENTIAL_BYTES];
185        draw(&mut drawn).map_err(|error| SupervisorError::Unavailable {
186            detail: format!(
187                "no credential could be minted for the turn, because the operating system's \
188                 random source refused: {error}"
189            ),
190        })?;
191        let credential = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(drawn);
192        let digested = digest(credential.as_bytes());
193        let pass = TurnPass::new(self.registry.0.server, credential)?;
194        // Held across the insertion, so a turn that returns while a run is
195        // being issued its credential leaves nothing live behind it.
196        let closed = self
197            .closed
198            .lock()
199            .unwrap_or_else(std::sync::PoisonError::into_inner);
200        if *closed {
201            return Err(SupervisorError::Unavailable {
202                detail: "the turn this run belongs to has already returned".to_owned(),
203            });
204        }
205        let mut held = self.registry.held();
206        held.retain(|_, live| live.scope != self.id);
207        held.insert(
208            digested,
209            Held {
210                scope: self.id,
211                binding: TurnBinding {
212                    session: session.clone(),
213                    print_id: self.print_id,
214                },
215            },
216        );
217        drop(held);
218        drop(closed);
219        Ok(pass)
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use printobserver_core::TurnAuthority as _;
226    use printobserver_supervisor_api::{CREDENTIAL_ENV, SERVER_ENV, TurnPass, TurnSession};
227    use printobserver_types::PrintId;
228
229    use super::{GENERATED_TURN_CREDENTIAL_BYTES, TurnBinding, TurnCredentials};
230
231    /// One session, by a name that is one.
232    fn session(name: &str) -> TurnSession {
233        TurnSession::new(name).expect("a session")
234    }
235
236    /// The value one variable of a pass carries.
237    fn value_of(pass: &TurnPass, name: &str) -> String {
238        pass.environment()
239            .into_iter()
240            .find(|(named, _)| *named == name)
241            .map_or_else(|| panic!("the pass carries no {name}"), |(_, value)| value)
242    }
243
244    /// A credential is admitted as the session and print it was issued for
245    /// while its turn runs, a second issue replaces the first, and revoking
246    /// the turn admits none of them and issues no more.
247    #[test]
248    fn a_turns_credential_lives_exactly_as_long_as_its_turn() {
249        let registry = TurnCredentials::new(Some("127.0.0.1:1".parse().expect("an address")));
250        let print_id = PrintId::new();
251        let opened = registry.open(print_id);
252        let access = opened.access();
253        let pass = access.issue(&session("print-a")).expect("one is minted");
254        let first = value_of(&pass, CREDENTIAL_ENV);
255
256        assert_eq!(value_of(&pass, SERVER_ENV), "http://127.0.0.1:1");
257        // Unpadded URL-safe base64 of the drawn bytes.
258        assert_eq!(
259            first.len(),
260            (GENERATED_TURN_CREDENTIAL_BYTES * 4).div_ceil(3)
261        );
262        assert_eq!(
263            registry.admit(first.as_bytes()),
264            Some(TurnBinding {
265                session: session("print-a"),
266                print_id,
267            })
268        );
269        let second = value_of(
270            &access.issue(&session("print-a-2")).expect("minted"),
271            CREDENTIAL_ENV,
272        );
273        assert_ne!(first, second);
274        assert_eq!(registry.admit(first.as_bytes()), None);
275        assert_eq!(registry.live(), 1);
276
277        opened.revoke();
278        assert_eq!(registry.admit(second.as_bytes()), None);
279        assert!(access.issue(&session("print-a-3")).is_err());
280        assert_eq!(registry.live(), 0);
281    }
282
283    /// A draw the random source refuses issues nothing and registers nothing,
284    /// so the run it was for is not started.
285    #[test]
286    fn a_refused_draw_issues_and_registers_nothing() {
287        let registry = TurnCredentials::new(None);
288        let scope = super::Scope {
289            registry: registry.clone(),
290            id: 0,
291            print_id: PrintId::new(),
292            closed: std::sync::Mutex::new(false),
293        };
294
295        let Err(refused) =
296            scope.issue_drawn(&session("print-a"), |_| Err(getrandom::Error::UNSUPPORTED))
297        else {
298            panic!("a refused draw issued a credential");
299        };
300
301        assert!(
302            refused.to_string().contains("random source refused"),
303            "{refused}"
304        );
305        assert_eq!(registry.live(), 0);
306    }
307
308    /// Dropping one turn's opened issuer revokes it, and another turn's
309    /// credential is left alone.
310    #[test]
311    fn dropping_one_turn_revokes_its_own_credential_and_no_other() {
312        let registry = TurnCredentials::new(None);
313        let kept = registry.open(PrintId::new());
314        let kept_credential = value_of(
315            &kept.access().issue(&session("kept")).expect("minted"),
316            CREDENTIAL_ENV,
317        );
318        let dropped = registry.open(PrintId::new());
319        let dropped_credential = value_of(
320            &dropped.access().issue(&session("gone")).expect("minted"),
321            CREDENTIAL_ENV,
322        );
323        drop(dropped);
324
325        assert_eq!(registry.admit(dropped_credential.as_bytes()), None);
326        assert!(registry.admit(kept_credential.as_bytes()).is_some());
327    }
328}