steid

@jamesgill /

Rust12.4 KBCode·Blame·History·Raw
1//! The operator surface's two routes: what this instance is, and claiming it headlessly.
2//!
3//! Both are `#[route]` rather than `#[page]` — JSON in, JSON out, no layout, no cookie
4//! and no session. The caller is a control plane provisioning a machine per tenant, not
5//! a person: it polls `GET /api/instance` between booting the machine and handing its
6//! owner a link, and it may claim the instance itself with `POST /api/setup` rather than
7//! driving the form.
8
9use std::time::Instant;
10
11use serde::{Deserialize, Serialize};
12use topcoat::{
13 Result,
14 context::{Cx, try_app_context},
15 router::{
16 Body, IntoResponse, Response, StatusCode, content::Json, header::CONTENT_TYPE, route,
17 },
18};
19
20use crate::{
21 application::{OwnerSpec, claim_instance, describe_instance, instance_state, port::DiskReport},
22 infrastructure::{
23 password::Argon2Hasher,
24 repository::{SqliteMembershipRepo, SqliteOrgRepo, SqliteUserRepo},
25 },
26};
27
28use super::{
29 context::{disk_usage, git_features, pool, repos, setup_token, users},
30 operator::operator_authorized,
31 rate_limit::{instance_throttled, throttled},
32};
33
34/// When this process started, for `uptime_seconds`.
35///
36/// In app context because it is a fact about the process, not the request: constructed
37/// per request it would report zero every time. An `Instant` rather than a wall clock so
38/// the answer is a monotonic duration that a clock step cannot make negative.
39#[derive(Debug, Clone, Copy)]
40pub struct StartedAt(pub Instant);
41
42impl StartedAt {
43 /// Now. Called once, by `main`.
44 #[must_use]
45 pub fn now() -> Self {
46 Self(Instant::now())
47 }
48}
49
50/// What this instance is.
51///
52/// One struct with optional fields rather than two, so the public answer is provably a
53/// subset of the operator one: a field added below the line cannot leak by being put in
54/// the wrong struct, it can only be omitted. `claimed` is the only thing an anonymous
55/// caller is ever told.
56#[derive(Debug, Serialize)]
57struct Instance {
58 claimed: bool,
59
60 /// Steid's own version. Fingerprinting material — it names the vulnerabilities this
61 /// build has — so it is behind the token.
62 #[serde(skip_serializing_if = "Option::is_none")]
63 version: Option<&'static str>,
64
65 /// The git on the machine, `2.47`-shaped, or absent where it could not be read.
66 #[serde(skip_serializing_if = "Option::is_none")]
67 git_version: Option<String>,
68
69 /// Whether that git can merge a pull request from the web.
70 #[serde(skip_serializing_if = "Option::is_none")]
71 merge_supported: Option<bool>,
72
73 #[serde(skip_serializing_if = "Option::is_none")]
74 repositories: Option<u64>,
75
76 #[serde(skip_serializing_if = "Option::is_none")]
77 users: Option<u64>,
78
79 #[serde(skip_serializing_if = "Option::is_none")]
80 uptime_seconds: Option<u64>,
81
82 /// What the machine is costing on disk. Absent where it could not be measured, for
83 /// the reason `git_version` is.
84 #[serde(skip_serializing_if = "Option::is_none")]
85 disk: Option<Disk>,
86}
87
88/// The disk numbers, as JSON.
89///
90/// A nested object rather than three flat `disk_*` keys, so the whole group is present
91/// or absent together and a consumer can test one thing rather than three. Bytes, and
92/// only bytes: formatting "12 GB of 20 used" is the console's, and a number it can do
93/// arithmetic on is what it cannot get back from a formatted string.
94#[derive(Debug, Serialize)]
95struct Disk {
96 data_dir_bytes: u64,
97 filesystem_total_bytes: u64,
98 filesystem_free_bytes: u64,
99}
100
101impl From<DiskReport> for Disk {
102 fn from(report: DiskReport) -> Self {
103 Self {
104 data_dir_bytes: report.data_dir_bytes,
105 filesystem_total_bytes: report.filesystem_total_bytes,
106 filesystem_free_bytes: report.filesystem_free_bytes,
107 }
108 }
109}
110
111impl Instance {
112 /// The one fact that is safe to tell anybody.
113 fn public(claimed: bool) -> Self {
114 Self {
115 claimed,
116 version: None,
117 git_version: None,
118 merge_supported: None,
119 repositories: None,
120 users: None,
121 uptime_seconds: None,
122 disk: None,
123 }
124 }
125}
126
127/// What this instance is.
128///
129/// Unauthenticated it answers `{"claimed": true|false}` and nothing else — the one fact a
130/// provisioner needs before handing over a claim link, and the one fact that is not
131/// fingerprinting material. With the operator bearer it adds the version, what git can
132/// do, the size of the machine, how long the process has been up, and what it is costing
133/// on disk.
134///
135/// A wrong or absent operator token is not an error: it is the public answer. There is
136/// nothing to 401 about, because the unauthenticated form is a real answer rather than a
137/// truncated one — and answering 401 would confirm that a token exists to guess.
138///
139/// Rate limited only in its unauthenticated form: a caller holding the token has already
140/// proved it is the control plane.
141#[route(GET "/api/instance")]
142async fn instance(cx: &Cx) -> Result<Response> {
143 if operator_authorized(cx) {
144 let report = describe_instance(&users(cx), &repos(cx), disk_usage(cx))
145 .await
146 .map_err(super::context::server_error)?;
147 let features = git_features(cx);
148
149 return Json(Instance {
150 claimed: report.claimed,
151 version: Some(env!("CARGO_PKG_VERSION")),
152 git_version: features.version_string(),
153 merge_supported: Some(features.merge_tree),
154 repositories: Some(report.repositories),
155 users: Some(report.users),
156 uptime_seconds: Some(uptime_seconds(cx)),
157 disk: report.disk.map(Disk::from),
158 })
159 .into_response(cx);
160 }
161
162 if let Some(response) = instance_throttled(cx) {
163 return Ok(response);
164 }
165
166 let state = instance_state(&users(cx))
167 .await
168 .map_err(super::context::server_error)?;
169
170 Json(Instance::public(state.claimed)).into_response(cx)
171}
172
173/// How long this process has been up, in whole seconds.
174///
175/// Zero where `StartedAt` is absent, which is no context Steid builds — an instance that
176/// has been up for no time is a truthful-looking answer and a better failure than a panic
177/// on an operator's monitoring poll.
178fn uptime_seconds(cx: &Cx) -> u64 {
179 try_app_context::<StartedAt>(cx).map_or(0, |started| started.0.elapsed().as_secs())
180}
181
182/// The headless claim.
183#[derive(Debug, Deserialize)]
184struct SetupRequest {
185 setup_token: String,
186 email: String,
187 handle: String,
188 password: String,
189}
190
191/// What a successful claim answers with.
192///
193/// The handle and nothing else. No session — a control plane is not signing in — and no
194/// token of any kind, so the claim leaves the caller holding exactly what it already had.
195#[derive(Debug, Serialize)]
196struct Claimed {
197 handle: String,
198}
199
200/// Claims the instance without a browser.
201///
202/// The same rules as the form, reached through the same use case: the setup token is
203/// checked before any write, an already-claimed instance is refused, and the whole thing
204/// shares the sign-in limiter's budget because it is the same secret being guessed.
205///
206/// Every failure is the same 404 with the same body — a wrong token, an already-claimed
207/// instance, and a handle that will not validate all look identical from outside. A 401
208/// would say the token exists to guess; a 409 would say the instance is claimed. Both
209/// cases return before Argon2 runs, so their timing matches too.
210#[route(POST "/api/setup")]
211async fn setup(cx: &Cx, Json(request): Json<SetupRequest>) -> Result<Response> {
212 if let Some(response) = throttled(cx) {
213 return Ok(response);
214 }
215
216 // Absent once claimed, so a claimed instance answers here rather than reaching the
217 // use case at all.
218 let Some(token) = setup_token(cx) else {
219 return Ok(refused());
220 };
221
222 let pool = pool(cx).clone();
223 let users = SqliteUserRepo::new(pool.clone());
224 let orgs = SqliteOrgRepo::new(pool.clone());
225 let memberships = SqliteMembershipRepo::new(pool);
226
227 let handle = request.handle.clone();
228 let claim = claim_instance(
229 &request.setup_token,
230 token,
231 &OwnerSpec {
232 handle: request.handle,
233 email: request.email,
234 password: request.password,
235 },
236 &users,
237 &orgs,
238 &memberships,
239 &Argon2Hasher::new(),
240 )
241 .await;
242
243 match claim {
244 // Deliberately no session: `sign_in` is the form's job. A control plane holding a
245 // cookie would be a browser, and this is not one.
246 Ok(_) => (StatusCode::CREATED, Json(Claimed { handle })).into_response(cx),
247 Err(error) => {
248 // The reason goes to the log, where an operator can read it; the response
249 // says nothing. No field of the request is logged — one of them is a
250 // password.
251 eprintln!("steid: headless claim rejected: {error}");
252 Ok(refused())
253 }
254 }
255}
256
257/// The one refusal `/api/setup` ever gives. Byte-identical for every reason, so the
258/// response cannot be read as an oracle for the token or the instance's state.
259fn refused() -> Response {
260 let mut response = Response::new(Body::from("{\"error\":\"not found\"}\n"));
261 *response.status_mut() = StatusCode::NOT_FOUND;
262 response
263 .headers_mut()
264 .insert(CONTENT_TYPE, "application/json".parse().expect("static"));
265
266 response
267}
268
269#[cfg(test)]
270mod tests {
271 use super::*;
272
273 #[test]
274 fn the_public_answer_carries_nothing_but_claimed() {
275 let body = serde_json::to_string(&Instance::public(false)).expect("serialise");
276
277 assert_eq!(body, r#"{"claimed":false}"#);
278 }
279
280 #[test]
281 fn the_operator_answer_carries_every_field() {
282 let body = serde_json::to_string(&Instance {
283 claimed: true,
284 version: Some("0.4.0"),
285 git_version: Some("2.47".to_owned()),
286 merge_supported: Some(true),
287 repositories: Some(3),
288 users: Some(1),
289 uptime_seconds: Some(42),
290 disk: Some(Disk {
291 data_dir_bytes: 12_884_901_888,
292 filesystem_total_bytes: 21_474_836_480,
293 filesystem_free_bytes: 8_589_934_592,
294 }),
295 })
296 .expect("serialise");
297
298 assert_eq!(
299 body,
300 r#"{"claimed":true,"version":"0.4.0","git_version":"2.47","merge_supported":true,"repositories":3,"users":1,"uptime_seconds":42,"disk":{"data_dir_bytes":12884901888,"filesystem_total_bytes":21474836480,"filesystem_free_bytes":8589934592}}"#
301 );
302 }
303
304 #[test]
305 fn the_public_answer_never_carries_the_disk() {
306 // The whole shape is one struct so that a field can only be omitted, never put
307 // in the wrong place — this is the assertion that keeps that true for the one
308 // field that says how big somebody's machine is.
309 let body = serde_json::to_string(&Instance::public(true)).expect("serialise");
310
311 assert_eq!(body, r#"{"claimed":true}"#);
312 assert!(!body.contains("disk"), "{body}");
313 }
314
315 #[test]
316 fn a_disk_that_could_not_be_measured_omits_the_whole_group() {
317 let body = serde_json::to_string(&Instance {
318 claimed: true,
319 version: Some("0.7.0"),
320 git_version: Some("2.47".to_owned()),
321 merge_supported: Some(true),
322 repositories: Some(0),
323 users: Some(1),
324 uptime_seconds: Some(1),
325 disk: None,
326 })
327 .expect("serialise");
328
329 assert!(!body.contains("disk"), "{body}");
330 assert!(!body.contains("bytes"), "{body}");
331 }
332
333 #[test]
334 fn a_git_that_could_not_be_read_omits_its_version_rather_than_guessing() {
335 let body = serde_json::to_string(&Instance {
336 claimed: true,
337 version: Some("0.4.0"),
338 git_version: None,
339 merge_supported: Some(false),
340 repositories: Some(0),
341 users: Some(1),
342 uptime_seconds: Some(1),
343 disk: None,
344 })
345 .expect("serialise");
346
347 assert!(!body.contains("git_version"), "{body}");
348 assert!(body.contains(r#""merge_supported":false"#), "{body}");
349 }
350
351 #[test]
352 fn every_refusal_is_the_same_404() {
353 let first = refused();
354 let second = refused();
355
356 assert_eq!(first.status(), StatusCode::NOT_FOUND);
357 assert_eq!(first.status(), second.status());
358 assert_eq!(first.headers(), second.headers());
359 }
360}