printobserver_supervisor_api/access.rs
1//! How one supervision run reaches the server it runs under.
2//!
3//! # A run is handed a credential of its own, and nothing else
4//!
5//! Every run the port starts authenticates to the server's API with a
6//! credential minted for that run alone, bound to the agent class, the session
7//! the run is in and the print the turn is about. The core mints it at the turn
8//! boundary and revokes it when the turn returns; the port asks for it through
9//! [`TurnAccess::issue`] immediately before each run, naming the session that
10//! run is in — which is the port's own to know, because a harness that refuses
11//! to continue a session moves the turn into the next one.
12//!
13//! The run is handed it through its environment alone, as [`SERVER_ENV`] and
14//! [`CREDENTIAL_ENV`]: no file is written holding it, and the context command a
15//! turn is given names no configuration file, so the command-line program the
16//! agent runs reads no file either.
17
18use std::net::SocketAddr;
19
20use crate::SupervisorError;
21
22/// The variable a run is told where the server is in.
23pub const SERVER_ENV: &str = "PRINTOBSERVER_SERVER";
24
25/// The variable a run is handed its own credential in.
26pub const CREDENTIAL_ENV: &str = "PRINTOBSERVER_CREDENTIAL";
27
28/// What a pass renders as, wherever one is rendered.
29const REDACTED: &str = "<redacted>";
30
31/// What one run is handed to reach the server with: where the server is, and
32/// the credential minted for that run.
33///
34/// The credential is readable in exactly one place — [`Self::environment`],
35/// which is what a run's environment is built from — and neither rendering of
36/// this type shows it.
37pub struct TurnPass {
38 /// The address the server answers on.
39 server: Option<SocketAddr>,
40 /// The credential minted for this run.
41 credential: String,
42}
43
44impl TurnPass {
45 /// One pass: the server's address, when it is known, and a credential.
46 ///
47 /// # Errors
48 ///
49 /// Returns [`SupervisorError::Unavailable`], quoting nothing of it, when the
50 /// credential is not one an `Authorization` header carries intact: empty,
51 /// or carrying anything but printable ASCII without a space.
52 pub fn new(server: Option<SocketAddr>, credential: String) -> Result<Self, SupervisorError> {
53 if credential.is_empty() || !credential.bytes().all(|byte| byte.is_ascii_graphic()) {
54 return Err(SupervisorError::Unavailable {
55 detail: "the credential minted for this run is not one a request carries intact"
56 .to_owned(),
57 });
58 }
59 Ok(Self { server, credential })
60 }
61
62 /// The variables a run's environment carries, as `(name, value)` pairs:
63 /// the server's address, as a client spells it, when it is known, and the
64 /// credential.
65 #[must_use]
66 pub fn environment(&self) -> Vec<(&'static str, String)> {
67 let mut assigned = Vec::with_capacity(2);
68 if let Some(server) = self.server {
69 assigned.push((SERVER_ENV, format!("http://{server}")));
70 }
71 assigned.push((CREDENTIAL_ENV, self.credential.clone()));
72 assigned
73 }
74}
75
76impl core::fmt::Debug for TurnPass {
77 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
78 formatter
79 .debug_struct("TurnPass")
80 .field("server", &self.server)
81 .field("credential", &REDACTED)
82 .finish()
83 }
84}
85
86/// The session one run is in, as a turn credential is bound to it: never
87/// blank, because the session is what a turn's requests are held to claiming,
88/// and a run in no session is one no request could claim to be.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct TurnSession(String);
91
92impl TurnSession {
93 /// One session, by its name.
94 ///
95 /// # Errors
96 ///
97 /// Returns [`SupervisorError::Unavailable`] when the name is empty or only
98 /// whitespace.
99 pub fn new(name: impl Into<String>) -> Result<Self, SupervisorError> {
100 let name = name.into();
101 if name.trim().is_empty() {
102 return Err(SupervisorError::Unavailable {
103 detail: "a run in no session is issued no credential".to_owned(),
104 });
105 }
106 Ok(Self(name))
107 }
108
109 /// The session's name, as a request's `Actor::Agent { session_name }`
110 /// spells it.
111 #[must_use]
112 pub fn as_str(&self) -> &str {
113 &self.0
114 }
115}
116
117impl core::fmt::Display for TurnSession {
118 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
119 formatter.write_str(&self.0)
120 }
121}
122
123/// Issues the runs of one supervision turn their credentials.
124///
125/// The core hands one of these to [`crate::SupervisorPort::run_turn`] for the
126/// turn it starts, already bound to the agent class and that turn's print, and
127/// revokes everything it issued when the turn returns.
128pub trait TurnAccess: Send + Sync {
129 /// The pass the run in `session` presents.
130 ///
131 /// Issuing again within the same turn — a harness that refused to continue
132 /// one session moves the turn into the next — revokes the pass issued
133 /// before, so a turn holds one live credential at a time.
134 ///
135 /// # Errors
136 ///
137 /// Returns [`SupervisorError::Unavailable`] when no credential could be
138 /// minted, which is a run that could reach nothing and is not started.
139 fn issue(&self, session: &TurnSession) -> Result<TurnPass, SupervisorError>;
140
141 /// Whether this turn has asked for its print to be paused or cancelled,
142 /// whether the request was taken or refused: what an answer of
143 /// [`Disposition::Stop`](crate::Disposition::Stop) is held to, since an
144 /// answer stops nothing by itself. `false` when nothing says.
145 fn asked_to_stop(&self) -> bool {
146 false
147 }
148}
149
150#[cfg(test)]
151mod tests {
152 use super::{CREDENTIAL_ENV, SERVER_ENV, TurnPass, TurnSession};
153
154 /// A pass's environment carries the address and the credential, and
155 /// neither rendering of it shows the credential.
156 #[test]
157 fn a_pass_carries_both_variables_and_renders_no_credential() {
158 let pass = TurnPass::new(
159 Some("127.0.0.1:8420".parse().expect("an address")),
160 "qz7vk3xhw9mrbt2ycf5jdlgnps46auei".to_owned(),
161 )
162 .expect("a credential a header carries");
163
164 assert_eq!(
165 pass.environment(),
166 vec![
167 (SERVER_ENV, "http://127.0.0.1:8420".to_owned()),
168 (
169 CREDENTIAL_ENV,
170 "qz7vk3xhw9mrbt2ycf5jdlgnps46auei".to_owned()
171 ),
172 ]
173 );
174 assert!(!format!("{pass:?}").contains("qz7vk3xhw9mrbt2ycf5jdlgnps46auei"));
175 assert_eq!(
176 TurnPass::new(None, "c".to_owned())
177 .expect("one character is a credential")
178 .environment(),
179 vec![(CREDENTIAL_ENV, "c".to_owned())]
180 );
181 }
182
183 /// A session that names none is refused, and one that names one is kept as
184 /// it was named.
185 #[test]
186 fn a_blank_session_is_refused() {
187 for blank in ["", " ", "\t"] {
188 assert!(
189 TurnSession::new(blank).is_err(),
190 "{blank:?} was taken as a session"
191 );
192 }
193 let session = TurnSession::new("print-a-2").expect("a session");
194 assert_eq!(session.as_str(), "print-a-2");
195 assert_eq!(session.to_string(), "print-a-2");
196 }
197
198 /// A credential no header carries intact is refused, quoting nothing of it.
199 #[test]
200 fn a_credential_no_header_carries_is_refused() {
201 for refused in ["", "qx-two words", "qx-tab\there", "qx-caf\u{e9}"] {
202 let error = TurnPass::new(None, refused.to_owned())
203 .err()
204 .unwrap_or_else(|| panic!("{refused:?} was taken as a credential"));
205 assert!(!error.to_string().contains("qx-"), "{error}");
206 }
207 }
208}