| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use std::sync::Arc; |
| 6 | |
| 7 | use im_core::store::Store; |
| 8 | use topcoat::Result; |
| 9 | use topcoat::asset::RouterBuilderAssetExt; |
| 10 | use topcoat::cookie::RouterBuilderCookieExt; |
| 11 | use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route}; |
| 12 | |
| 13 | mod admin; |
| 14 | mod auth; |
| 15 | mod config; |
| 16 | mod directory; |
| 17 | mod dropdown; |
| 18 | mod health; |
| 19 | mod i18n; |
| 20 | mod layout; |
| 21 | mod live; |
| 22 | mod mailer; |
| 23 | mod oidc; |
| 24 | mod pack; |
| 25 | mod pages; |
| 26 | mod people; |
| 27 | mod photo; |
| 28 | mod server; |
| 29 | |
| 30 | use config::Config; |
| 31 | |
| 32 | #[route(GET "/healthz")] |
| 33 | async fn healthz() -> Result<&'static str> { |
| 34 | |
| 35 | |
| 36 | |
| 37 | Ok(concat!("ok ", env!("IM_BUILD_SHA"))) |
| 38 | } |
| 39 | |
| 40 | #[tokio::main] |
| 41 | async 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 | |
| 188 | |
| 189 | |
| 190 | async 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 | |
| 216 | async 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 | |
| 225 | |
| 226 | |
| 227 | |
| 228 | async 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 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | async 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 | |
| 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 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | async 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 | |
| 315 | |
| 316 | async 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 | |
| 333 | |
| 334 | async 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 | |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | async 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 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | async fn revoke_client(config: Config, id: &str) { |
| 377 | let store = open_store(&config).await; |
| 378 | |
| 379 | |
| 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 | |
| 398 | |
| 399 | async 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 | |
| 407 | async 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 | |
| 416 | |
| 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 | |
| 433 | |
| 434 | |
| 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 | |
| 444 | |
| 445 | |
| 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 | |
| 455 | |
| 456 | |
| 457 | async 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 | |
| 477 | let _ = stop.send(true); |
| 478 | } |