forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

main.rs478 lines, 17.3 KiBHistoryRawDownload
1//! im — the Dizey SSO. Server by default; the CLI covers bootstrapping
2//! (the first admin invite) and the two admin actions that must work even
3//! when the panel cannot be reached. Everything else lives in /admin.
4
5use std::sync::Arc;
6
7use im_core::store::Store;
8use topcoat::Result;
9use topcoat::asset::RouterBuilderAssetExt;
10use topcoat::cookie::RouterBuilderCookieExt;
11use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route};
12
13mod admin;
14mod auth;
15mod config;
16mod directory;
17mod dropdown;
18mod health;
19mod i18n;
20mod layout;
21mod live;
22mod mailer;
23mod oidc;
24mod pack;
25mod pages;
26mod people;
27mod photo;
28mod server;
29
30use config::Config;
31
32#[route(GET "/healthz")]
33async fn healthz() -> Result<&'static str> {
34 // The build's commit, baked by build.rs — the deploy asserts the exact
35 // body after the restart, so a stale process holding the port cannot
36 // pass for this one.
37 Ok(concat!("ok ", env!("IM_BUILD_SHA")))
38}
39
40#[tokio::main]
41async fn main() {
42 let args: Vec<String> = std::env::args().collect();
43 let config = match Config::load() {
44 Ok(config) => config,
45 Err(problem) => {
46 eprintln!("im: {problem}");
47 std::process::exit(2);
48 }
49 };
50
51 match args.get(1).map(String::as_str) {
52 None => serve(config).await,
53 Some("invite") => {
54 let mut email = None;
55 let mut admin = false;
56 for arg in &args[2..] {
57 match arg.as_str() {
58 "--admin" => admin = true,
59 other if email.is_none() => email = Some(other.to_string()),
60 other => {
61 eprintln!("usage: im-web invite <email> [--admin]");
62 eprintln!("im: unexpected argument {other}");
63 std::process::exit(2);
64 }
65 }
66 }
67 let Some(email) = email else {
68 eprintln!("usage: im-web invite <email> [--admin]");
69 std::process::exit(2);
70 };
71 invite(config, &email, admin).await;
72 }
73 Some("revoke") => {
74 let Some(email) = args.get(2) else {
75 eprintln!("usage: im-web revoke <email>");
76 std::process::exit(2);
77 };
78 revoke(config, email).await;
79 }
80 Some("create-client") => {
81 let (Some(name), uris) = (args.get(2), args.get(3..).unwrap_or(&[])) else {
82 eprintln!("usage: im-web create-client <name> <redirect-uri> [more-uris...]");
83 std::process::exit(2);
84 };
85 if uris.is_empty() {
86 eprintln!("usage: im-web create-client <name> <redirect-uri> [more-uris...]");
87 std::process::exit(2);
88 }
89 create_client(config, name, uris).await;
90 }
91 Some("promote") => {
92 let Some(email) = args.get(2) else {
93 eprintln!("usage: im-web promote <email>");
94 std::process::exit(2);
95 };
96 set_admin_cli(config, email, true).await;
97 }
98 Some("demote") => {
99 let Some(email) = args.get(2) else {
100 eprintln!("usage: im-web demote <email>");
101 std::process::exit(2);
102 };
103 set_admin_cli(config, email, false).await;
104 }
105 Some("rotate-client") => {
106 let Some(id) = args.get(2) else {
107 eprintln!("usage: im-web rotate-client <client_id>");
108 std::process::exit(2);
109 };
110 rotate_client(config, id).await;
111 }
112 Some("revoke-client") => {
113 let Some(id) = args.get(2) else {
114 eprintln!("usage: im-web revoke-client <client_id>");
115 std::process::exit(2);
116 };
117 revoke_client(config, id).await;
118 }
119 Some("pack") => {
120 let mut root = None;
121 let mut out = None;
122 let mut rest = args[2..].iter();
123 while let Some(arg) = rest.next() {
124 match arg.as_str() {
125 "--root" => match rest.next() {
126 Some(value) => root = Some(value.clone()),
127 None => {
128 eprintln!("usage: im-web pack [--root DIR] [--out FILE]");
129 eprintln!("im: --root needs a directory");
130 std::process::exit(2);
131 }
132 },
133 "--out" => match rest.next() {
134 Some(value) => out = Some(value.clone()),
135 None => {
136 eprintln!("usage: im-web pack [--root DIR] [--out FILE]");
137 eprintln!("im: --out needs a file");
138 std::process::exit(2);
139 }
140 },
141 other => {
142 eprintln!("usage: im-web pack [--root DIR] [--out FILE]");
143 eprintln!("im: unexpected argument {other}");
144 std::process::exit(2);
145 }
146 }
147 }
148 pack::pack_command(&config, root.as_deref(), out.as_deref()).await;
149 }
150 Some("unpack") => {
151 let Some(archive) = args.get(2) else {
152 eprintln!("usage: im-web unpack FILE [--root DIR] [--force]");
153 std::process::exit(2);
154 };
155 let mut root: Option<String> = None;
156 let mut force = false;
157 let mut rest = args[3..].iter();
158 while let Some(arg) = rest.next() {
159 match arg.as_str() {
160 "--force" => force = true,
161 "--root" => match rest.next() {
162 Some(value) => root = Some(value.clone()),
163 None => {
164 eprintln!("usage: im-web unpack FILE [--root DIR] [--force]");
165 eprintln!("im: --root needs a directory");
166 std::process::exit(2);
167 }
168 },
169 other => {
170 eprintln!("usage: im-web unpack FILE [--root DIR] [--force]");
171 eprintln!("im: unexpected argument {other}");
172 std::process::exit(2);
173 }
174 }
175 }
176 pack::unpack_command(archive, root.as_deref(), force);
177 }
178 Some(other) => {
179 eprintln!(
180 "im: unknown command {other:?} (expected: invite, revoke, promote, demote, create-client, rotate-client, revoke-client, pack, unpack, or none to serve)"
181 );
182 std::process::exit(2);
183 }
184 }
185}
186
187/// `im-web promote|demote <email>`: the admin flag for an account that
188/// already exists — the migration path's way in, since invites refuse
189/// addresses with accounts.
190async fn set_admin_cli(config: Config, email: &str, admin: bool) {
191 let store = open_store(&config).await;
192 let Some(user) = im_core::accounts::user_by_email(&store, email)
193 .await
194 .expect("failed to read users")
195 else {
196 eprintln!("im: no account for {email}");
197 std::process::exit(1);
198 };
199 im_core::accounts::set_admin(&store, &user.id, admin)
200 .await
201 .expect("failed to update");
202 im_core::events::log(
203 &store,
204 if admin {
205 "user_promoted"
206 } else {
207 "user_demoted"
208 },
209 Some("cli"),
210 Some(email),
211 )
212 .await;
213 println!("im {email}: admin = {admin}");
214}
215
216async fn open_store(config: &Config) -> Arc<Store> {
217 Arc::new(
218 Store::open(&config.database)
219 .await
220 .expect("failed to open the database"),
221 )
222}
223
224/// The one-time seed: a database with no services yet takes the config's
225/// `[[services]]` list as the family's starting rows. Afterwards the admin
226/// panel owns the list and the same file lines are dead letters — the seed
227/// only fires again if the table is emptied.
228async fn seed_services(store: &Store, config: &Config) {
229 if config.services.is_empty() {
230 return;
231 }
232 let seed: Vec<im_core::services::Service> = config
233 .services
234 .iter()
235 .map(|service| im_core::services::Service {
236 key: service.key.clone(),
237 name: service.name.clone(),
238 url: service.url.clone(),
239 owner: None,
240 client_id: None,
241 storage_limit_bytes: None,
242 })
243 .collect();
244 match im_core::services::seed_from(store, &seed).await {
245 Ok(true) => println!(
246 "im services seeded from config ({} entries)",
247 seed.len()
248 ),
249 Ok(false) => {}
250 Err(e) => eprintln!("im: seeding services from config failed: {e}"),
251 }
252}
253
254/// im's own row of the family, written on every boot from `issuer`: the
255/// address is the running app's, not a config line someone edits once and
256/// forgets. A seeded `im` row is claimed here (its name stays the admin's);
257/// afterwards the panel can rename and reorder it, but not re-point or
258/// remove it. Never a reason to refuse boot — the family is a convenience,
259/// the sign-in is not.
260async fn register_self(store: &Store, config: &Config) {
261 match im_core::services::register(
262 store,
263 im_core::services::SELF_OWNER,
264 "Account",
265 &config.issuer,
266 im_core::services::SELF_OWNER,
267 // im is nobody's client: its own row carries no credential stamp.
268 None,
269 )
270 .await
271 {
272 Ok(service) => println!("im registered itself in the family at {}", service.url),
273 Err(e) => eprintln!("im: registering itself in the family failed: {e}"),
274 }
275}
276
277/// `im-web invite <email> [--admin]`: creates the invite, mails it when the
278/// panel has configured a sender, prints the link otherwise (dev mode).
279///
280/// Needs the server stopped: Turso is a single-writer engine, and this
281/// process would hold the same file.
282async fn invite(config: Config, email: &str, admin: bool) {
283 let store = open_store(&config).await;
284 let token = match im_core::accounts::create_invite(&store, email, None, admin).await {
285 Ok(token) => token,
286 Err(im_core::accounts::AccountError::EmailTaken) => {
287 eprintln!(
288 "im: {email} already has an account — `im-web promote {email}` if you mean admin"
289 );
290 std::process::exit(1);
291 }
292 Err(e) => panic!("failed to create the invite: {e}"),
293 };
294 im_core::events::log(
295 &store,
296 "invite_created",
297 Some("cli"),
298 Some(&format!(
299 "for {email}{}",
300 if admin { " (admin)" } else { "" }
301 )),
302 )
303 .await;
304 match mailer::send_invite(&store, &config.issuer, email, token.expose()).await {
305 Ok(link) => println!("im invite mailed to {email}\nim {link}"),
306 Err(_) => println!(
307 "im invite for {email}: {}/invite/{}",
308 config.issuer,
309 token.expose()
310 ),
311 }
312}
313
314/// `im-web revoke <email>`: signs the person out everywhere — central
315/// sessions, refresh tokens, and the app sessions introspection answers for.
316async fn revoke(config: Config, email: &str) {
317 let store = open_store(&config).await;
318 let Some(user) = im_core::accounts::user_by_email(&store, email)
319 .await
320 .expect("failed to read users")
321 else {
322 eprintln!("im: no account for {email}");
323 std::process::exit(1);
324 };
325 let count = im_core::sessions::revoke_user_sessions(&store, &user.id)
326 .await
327 .expect("failed to revoke");
328 im_core::events::log(&store, "sessions_revoked", Some("cli"), Some(email)).await;
329 println!("im {email}: {count} session(s) revoked, everywhere, now");
330}
331
332/// `im-web create-client <name> <uris...>`: registers a relying party and
333/// prints the secret exactly once.
334async fn create_client(config: Config, name: &str, uris: &[String]) {
335 let store = open_store(&config).await;
336 let (id, secret) = im_core::oidc::create_client(&store, name, uris.to_vec())
337 .await
338 .expect("failed to create the client");
339 println!("im client {name}");
340 println!(" client_id {id}");
341 println!(" client_secret {}", secret.expose());
342 println!(" (the secret is shown once; its digest is all the database keeps)");
343}
344
345/// `im-web rotate-client <client_id>`: replaces the client's secret and
346/// prints the new one exactly once — the app's old pair dies with the write.
347///
348/// Needs the server stopped, like every CLI arm: Turso is a single-writer
349/// engine, and this process would hold the same file.
350async fn rotate_client(config: Config, id: &str) {
351 let store = open_store(&config).await;
352 let name = client_name(&store, id).await;
353 match im_core::oidc::rotate_client_secret(&store, id)
354 .await
355 .expect("failed to rotate the client secret")
356 {
357 Some(secret) => {
358 im_core::events::log(&store, "client_rotated", Some("cli"), Some(&name)).await;
359 println!("im client {id} ({name})");
360 println!(" client_secret {}", secret.expose());
361 println!(" (the secret is shown once; its digest is all the database keeps)");
362 }
363 None => {
364 eprintln!("im: no client {id}");
365 std::process::exit(1);
366 }
367 }
368}
369
370/// `im-web revoke-client <client_id>`: deletes the registry row and every
371/// refresh token and app session minted under it; the person's own sign-in
372/// sessions stay.
373///
374/// Needs the server stopped, like every CLI arm: Turso is a single-writer
375/// engine, and this process would hold the same file.
376async fn revoke_client(config: Config, id: &str) {
377 let store = open_store(&config).await;
378 // The name rides the log line and the goodbye, so it comes off the row
379 // before the row goes.
380 let name = client_name(&store, id).await;
381 match im_core::oidc::revoke_client(&store, id)
382 .await
383 .expect("failed to revoke the client")
384 {
385 true => {
386 println!(
387 "im client {id} ({name}) revoked — its tokens and app sessions went with it"
388 );
389 }
390 false => {
391 eprintln!("im: no client {id}");
392 std::process::exit(1);
393 }
394 }
395}
396
397/// The client's display name, or its id when no row stands behind it — the
398/// log's detail is the name when there is one.
399async fn client_name(store: &Arc<im_core::store::Store>, id: &str) -> String {
400 im_core::oidc::client_by_id(store, id)
401 .await
402 .expect("failed to read the client")
403 .map(|client| client.name)
404 .unwrap_or_else(|| id.to_string())
405}
406
407async fn serve(config: Config) {
408 for line in config.report() {
409 println!("im {line}");
410 }
411 let store = open_store(&config).await;
412 seed_services(&store, &config).await;
413 register_self(&store, &config).await;
414 let (live, _) = tokio::sync::broadcast::channel(64);
415 // Told when the process is stopping, so the live streams end instead of
416 // being waited out — see `live::Shutdown`.
417 let (stop, stopping) = tokio::sync::watch::channel(false);
418 let app = server::App {
419 store,
420 config: config.clone(),
421 live,
422 };
423
424 let bundle = topcoat::asset::AssetBundle::load().unwrap_or_else(|err| {
425 eprintln!("im: the asset bundle beside the executable failed to load: {err}");
426 eprintln!("im: run `topcoat asset bundle -p im-web` first");
427 std::process::exit(2);
428 });
429
430 let router = Router::builder()
431 .discover()
432 // Headroom over the photo cap: the boundary and part headers ride
433 // inside the body limit, so the handler's byte cap — not this layer —
434 // stays the one that says "over 5 MB".
435 .layer(BodyLimit::max(photo::PHOTO_LIMIT_BYTES as usize + 4096).at("/api/profile_photo"))
436 .cookies()
437 .assets(bundle)
438 .trusted_proxies(server::trusted_proxies())
439 .app_context(app)
440 .app_context(live::Shutdown(stopping))
441 .build();
442
443 // `topcoat::start` binds HOST/PORT from the environment; the listen
444 // address is a config/im.toml decision, so the listener is bound
445 // explicitly against the same value the boot log just printed.
446 let listener = tokio::net::TcpListener::bind(config.listen)
447 .await
448 .expect("failed to bind the listen address");
449 topcoat::serve_until(listener, router, shutdown_signal(stop))
450 .await
451 .expect("server error");
452}
453
454/// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a
455/// service manager. The live streams hear it first, so the graceful shutdown
456/// does not sit waiting on one long-lived connection per open tab.
457async fn shutdown_signal(stop: tokio::sync::watch::Sender<bool>) {
458 let ctrl_c = async {
459 tokio::signal::ctrl_c()
460 .await
461 .expect("failed to install the Ctrl+C handler");
462 };
463 #[cfg(unix)]
464 let terminate = async {
465 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
466 .expect("failed to install the SIGTERM handler")
467 .recv()
468 .await;
469 };
470 #[cfg(not(unix))]
471 let terminate = std::future::pending::<()>();
472 tokio::select! {
473 () = ctrl_c => {},
474 () = terminate => {},
475 }
476 // Streams end on their own; the browser reconnects when we are back.
477 let _ = stop.send(true);
478}