the family maintains its own addresses: services rows carry an owner, im writes its own row from issuer on every boot, and a sibling writes its own over the new POST /family/register behind the same client pair as GET /family — a key nobody holds is appended or claimed keeping the admin's name, the same app's next boot moves the address only, another app's key is a 409 — while the admin panel keeps names and order but can neither remove nor re-point a row an app keeps, since the next boot would undo it; the seed stays first-boot-only and the toml comment says so
Browse files at this commite75961512d76233d7511046de76e12c2dc3dc2ceParent: ec7fa5c8 changed files +608 -76
- config/im.toml +7 -0
- crates/im-core/src/services.rs +241 -29
- crates/im-core/src/store.rs +20 -4
- crates/im-web/src/admin.rs +46 -17
- crates/im-web/src/directory.rs +249 -7
- crates/im-web/src/i18n.rs +3 -0
- crates/im-web/src/main.rs +24 -1
- crates/im-web/src/server.rs +18 -18
config/im.tomlmodified+7 -0
| @@ -5,6 +5,13 @@ issuer = "http://127.0.0.1:7650" | |||
| 5 | # The sibling apps of the switcher and the landing's services home, in | 5 | # The sibling apps of the switcher and the landing's services home, in |
| 6 | # wordmark order. Prod uses https://<key>.dizey.sh — deploy-side config, | 6 | # wordmark order. Prod uses https://<key>.dizey.sh — deploy-side config, |
| 7 | # not committed here. | 7 | # not committed here. |
| 8 | +# | ||
| 9 | +# This list is a FIRST-BOOT seed only: once the services table has rows, the | ||
| 10 | +# file's lines are dead letters and the admin panel owns names and order. | ||
| 11 | +# The addresses maintain themselves — im rewrites its own row from `issuer` | ||
| 12 | +# on every boot, and a sibling registers itself over POST /family/register | ||
| 13 | +# with its client pair. A row an app keeps can be renamed and reordered in | ||
| 14 | +# the panel, but not re-pointed or removed there. | ||
| 8 | [[services]] | 15 | [[services]] |
| 9 | key = "in" | 16 | key = "in" |
| 10 | name = "Files" | 17 | name = "Files" |
crates/im-core/src/services.rsmodified+241 -29
| @@ -1,9 +1,13 @@ | |||
| 1 | //! The family: the services every topbar shows as wordmarks and the | 1 | //! The family: the services every topbar shows as wordmarks and the |
| 2 | -//! landing's services home. The list lives in the database and the admin | 2 | +//! landing's services home. The list lives in the database, seeded once from |
| 3 | -//! panel owns it — seeded once from the config's `[[services]]` on first | 3 | +//! the config's `[[services]]` on first boot and served to the sibling apps |
| 4 | -//! boot, edited from the admin panel (add, rename, reorder, remove), and served | 4 | +//! over `GET /family`, which each mirrors into its own database. |
| 5 | -//! to the sibling apps over `GET /family`, which each mirrors into its own | 5 | +//! |
| 6 | -//! database. | 6 | +//! Names and order are the admin panel's. Addresses maintain themselves: an |
| 7 | +//! app writes its own row through [`register`] — im from its `issuer` on | ||
| 8 | +//! every boot, a sibling over `POST /family/register` — and a row an app | ||
| 9 | +//! keeps is neither removed nor re-pointed from the panel, because the next | ||
| 10 | +//! boot would undo it. | ||
| 7 | 11 | ||
| 8 | use serde::Serialize; | 12 | use serde::Serialize; |
| 9 | 13 | ||
| @@ -19,8 +23,18 @@ pub struct Service { | |||
| 19 | pub key: String, | 23 | pub key: String, |
| 20 | pub name: String, | 24 | pub name: String, |
| 21 | pub url: String, | 25 | pub url: String, |
| 26 | + /// The app that keeps this row — `SELF_OWNER` for im's own entry, a | ||
| 27 | + /// client id for a sibling that registered itself, `None` for a row the | ||
| 28 | + /// seed or the panel made. Never serialized: `/family`'s shape is the | ||
| 29 | + /// three public fields the siblings mirror, and nothing more. | ||
| 30 | + #[serde(skip)] | ||
| 31 | + pub owner: Option<String>, | ||
| 22 | } | 32 | } |
| 23 | 33 | ||
| 34 | +/// The owner im writes on its own row, registered from `issuer` on every | ||
| 35 | +/// boot — not a client id, because im is nobody's client. | ||
| 36 | +pub const SELF_OWNER: &str = "im"; | ||
| 37 | + | ||
| 24 | /// The form-level rules every stored row obeys: a key of lowercase ASCII | 38 | /// The form-level rules every stored row obeys: a key of lowercase ASCII |
| 25 | /// letters, digits, and dashes; a non-empty name; an absolute http(s) URL. | 39 | /// letters, digits, and dashes; a non-empty name; an absolute http(s) URL. |
| 26 | /// Returns the reason a value is refused — the panel shows it as its one | 40 | /// Returns the reason a value is refused — the panel shows it as its one |
| @@ -49,10 +63,7 @@ pub fn validate(key: &str, name: &str, url: &str) -> std::result::Result<(), Str | |||
| 49 | if authority.is_empty() { | 63 | if authority.is_empty() { |
| 50 | return Err(format!("url {url:?} must name a host")); | 64 | return Err(format!("url {url:?} must name a host")); |
| 51 | } | 65 | } |
| 52 | - if trimmed | 66 | + if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) { |
| 53 | - .chars() | ||
| 54 | - .any(|c| c.is_whitespace() || c.is_control()) | ||
| 55 | - { | ||
| 56 | return Err(format!( | 67 | return Err(format!( |
| 57 | "url {url:?} must not carry spaces or control characters" | 68 | "url {url:?} must not carry spaces or control characters" |
| 58 | )); | 69 | )); |
| @@ -73,7 +84,7 @@ pub async fn list(store: &Store) -> Result<Vec<Service>> { | |||
| 73 | let conn = store.conn.lock().await; | 84 | let conn = store.conn.lock().await; |
| 74 | let mut rows = conn | 85 | let mut rows = conn |
| 75 | .query( | 86 | .query( |
| 76 | - "SELECT key, name, url FROM services ORDER BY position, key", | 87 | + "SELECT key, name, url, owner FROM services ORDER BY position, key", |
| 77 | (), | 88 | (), |
| 78 | ) | 89 | ) |
| 79 | .await | 90 | .await |
| @@ -84,6 +95,7 @@ pub async fn list(store: &Store) -> Result<Vec<Service>> { | |||
| 84 | key: store::text(&row, 0)?, | 95 | key: store::text(&row, 0)?, |
| 85 | name: store::text(&row, 1)?, | 96 | name: store::text(&row, 1)?, |
| 86 | url: store::text(&row, 2)?, | 97 | url: store::text(&row, 2)?, |
| 98 | + owner: store::opt_text(&row, 3)?, | ||
| 87 | }); | 99 | }); |
| 88 | } | 100 | } |
| 89 | Ok(services) | 101 | Ok(services) |
| @@ -123,9 +135,20 @@ pub async fn add(store: &Store, service: &Service) -> Result<()> { | |||
| 123 | /// Rewrites a service's name and address. The key travels in the form's | 135 | /// Rewrites a service's name and address. The key travels in the form's |
| 124 | /// hidden field and is not editable; a key not on the list is refused, so a | 136 | /// hidden field and is not editable; a key not on the list is refused, so a |
| 125 | /// form posted against a since-removed row cannot resurrect it. | 137 | /// form posted against a since-removed row cannot resurrect it. |
| 138 | +/// A row an app keeps only takes its new name here: the address is the | ||
| 139 | +/// app's own, rewritten on its every boot, so accepting one from the panel | ||
| 140 | +/// would show an edit the next boot silently undoes. | ||
| 126 | pub async fn edit(store: &Store, key: &str, name: &str, url: &str) -> Result<()> { | 141 | pub async fn edit(store: &Store, key: &str, name: &str, url: &str) -> Result<()> { |
| 127 | validate(key, name, url).map_err(StoreError::Invalid)?; | 142 | validate(key, name, url).map_err(StoreError::Invalid)?; |
| 128 | let url = url.trim_end_matches('/'); | 143 | let url = url.trim_end_matches('/'); |
| 144 | + if let Some(row) = owned_row(store, key).await? | ||
| 145 | + && row.1.is_some() | ||
| 146 | + && row.0 != url | ||
| 147 | + { | ||
| 148 | + return Err(StoreError::Invalid(format!( | ||
| 149 | + "service {key:?} keeps its own address; its app re-registers it on every boot" | ||
| 150 | + ))); | ||
| 151 | + } | ||
| 129 | let conn = store.conn.lock().await; | 152 | let conn = store.conn.lock().await; |
| 130 | let updated = conn | 153 | let updated = conn |
| 131 | .execute( | 154 | .execute( |
| @@ -143,7 +166,14 @@ pub async fn edit(store: &Store, key: &str, name: &str, url: &str) -> Result<()> | |||
| 143 | /// Takes a service off the list and closes the gap: every later row slides | 166 | /// Takes a service off the list and closes the gap: every later row slides |
| 144 | /// down one, so positions stay contiguous and the next add appends cleanly. | 167 | /// down one, so positions stay contiguous and the next add appends cleanly. |
| 145 | /// A key not on the list is a no-op — the panel only offers existing rows. | 168 | /// A key not on the list is a no-op — the panel only offers existing rows. |
| 169 | +/// A row an app keeps is not the panel's to take: it would come back on the | ||
| 170 | +/// app's next boot. | ||
| 146 | pub async fn remove(store: &Store, key: &str) -> Result<()> { | 171 | pub async fn remove(store: &Store, key: &str) -> Result<()> { |
| 172 | + if let Some((_, Some(_))) = owned_row(store, key).await? { | ||
| 173 | + return Err(StoreError::Invalid(format!( | ||
| 174 | + "service {key:?} is kept by its app; it re-registers on every boot" | ||
| 175 | + ))); | ||
| 176 | + } | ||
| 147 | let conn = store.conn.lock().await; | 177 | let conn = store.conn.lock().await; |
| 148 | let mut rows = conn | 178 | let mut rows = conn |
| 149 | .query( | 179 | .query( |
| @@ -157,12 +187,9 @@ pub async fn remove(store: &Store, key: &str) -> Result<()> { | |||
| 157 | }; | 187 | }; |
| 158 | let position = store::int(&row, 0)?; | 188 | let position = store::int(&row, 0)?; |
| 159 | drop(rows); | 189 | drop(rows); |
| 160 | - conn.execute( | 190 | + conn.execute("DELETE FROM services WHERE key = ?1", turso::params![key]) |
| 161 | - "DELETE FROM services WHERE key = ?1", | 191 | + .await |
| 162 | - turso::params![key], | 192 | + .map_err(backend)?; |
| 163 | - ) | ||
| 164 | - .await | ||
| 165 | - .map_err(backend)?; | ||
| 166 | conn.execute( | 193 | conn.execute( |
| 167 | "UPDATE services SET position = position - 1 WHERE position > ?1", | 194 | "UPDATE services SET position = position - 1 WHERE position > ?1", |
| 168 | turso::params![position], | 195 | turso::params![position], |
| @@ -226,6 +253,73 @@ pub async fn move_service(store: &Store, key: &str, up: bool) -> Result<()> { | |||
| 226 | Ok(()) | 253 | Ok(()) |
| 227 | } | 254 | } |
| 228 | 255 | ||
| 256 | +/// A row's stored `(url, owner)`, or `None` when no row carries the key. | ||
| 257 | +async fn owned_row(store: &Store, key: &str) -> Result<Option<(String, Option<String>)>> { | ||
| 258 | + let conn = store.conn.lock().await; | ||
| 259 | + let mut rows = conn | ||
| 260 | + .query( | ||
| 261 | + "SELECT url, owner FROM services WHERE key = ?1", | ||
| 262 | + turso::params![key], | ||
| 263 | + ) | ||
| 264 | + .await | ||
| 265 | + .map_err(backend)?; | ||
| 266 | + let Some(row) = rows.next().await.map_err(backend)? else { | ||
| 267 | + return Ok(None); | ||
| 268 | + }; | ||
| 269 | + Ok(Some((store::text(&row, 0)?, store::opt_text(&row, 1)?))) | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +/// An app writing its own row: im from its `issuer` on every boot, a sibling | ||
| 273 | +/// over `POST /family/register` with its client id as the `owner`. A key | ||
| 274 | +/// nobody holds is appended (or claimed, keeping the name the seed or the | ||
| 275 | +/// panel gave it); a key the caller already holds takes the new address | ||
| 276 | +/// only — the name is the admin's after the first insert. A key another app | ||
| 277 | +/// keeps is a conflict, never a takeover. | ||
| 278 | +pub async fn register( | ||
| 279 | + store: &Store, | ||
| 280 | + key: &str, | ||
| 281 | + name: &str, | ||
| 282 | + url: &str, | ||
| 283 | + owner: &str, | ||
| 284 | +) -> Result<Service> { | ||
| 285 | + validate(key, name, url).map_err(StoreError::Invalid)?; | ||
| 286 | + let url = url.trim_end_matches('/').to_string(); | ||
| 287 | + match owned_row(store, key).await? { | ||
| 288 | + Some((_, Some(held))) if held != owner => { | ||
| 289 | + return Err(StoreError::Conflict(format!( | ||
| 290 | + "service key {key:?} belongs to another app" | ||
| 291 | + ))); | ||
| 292 | + } | ||
| 293 | + Some(_) => { | ||
| 294 | + // Claiming an unowned row or refreshing our own: the address is | ||
| 295 | + // the app's to say, the name stays whatever is stored. | ||
| 296 | + let conn = store.conn.lock().await; | ||
| 297 | + conn.execute( | ||
| 298 | + "UPDATE services SET url = ?2, owner = ?3 WHERE key = ?1", | ||
| 299 | + turso::params![key, url.as_str(), owner], | ||
| 300 | + ) | ||
| 301 | + .await | ||
| 302 | + .map_err(backend)?; | ||
| 303 | + } | ||
| 304 | + None => { | ||
| 305 | + let conn = store.conn.lock().await; | ||
| 306 | + conn.execute( | ||
| 307 | + "INSERT INTO services (key, name, url, position, owner) \ | ||
| 308 | + VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), -1) + 1 FROM services), ?4)", | ||
| 309 | + turso::params![key, name.trim(), url.as_str(), owner], | ||
| 310 | + ) | ||
| 311 | + .await | ||
| 312 | + .map_err(backend)?; | ||
| 313 | + } | ||
| 314 | + } | ||
| 315 | + let row = list(store) | ||
| 316 | + .await? | ||
| 317 | + .into_iter() | ||
| 318 | + .find(|service| service.key == key) | ||
| 319 | + .ok_or_else(|| StoreError::Backend(format!("service {key:?} vanished after its write")))?; | ||
| 320 | + Ok(row) | ||
| 321 | +} | ||
| 322 | + | ||
| 229 | /// The one-time seed: a database with no services yet takes the config's | 323 | /// The one-time seed: a database with no services yet takes the config's |
| 230 | /// list as the starting rows, in the order the file names them. After that | 324 | /// list as the starting rows, in the order the file names them. After that |
| 231 | /// the panel owns the list and the same config is ignored — the `false` | 325 | /// the panel owns the list and the same config is ignored — the `false` |
| @@ -269,11 +363,17 @@ mod tests { | |||
| 269 | key: key.to_string(), | 363 | key: key.to_string(), |
| 270 | name: name.to_string(), | 364 | name: name.to_string(), |
| 271 | url: url.to_string(), | 365 | url: url.to_string(), |
| 366 | + owner: None, | ||
| 272 | } | 367 | } |
| 273 | } | 368 | } |
| 274 | 369 | ||
| 275 | async fn keys(store: &Store) -> Vec<String> { | 370 | async fn keys(store: &Store) -> Vec<String> { |
| 276 | - list(store).await.unwrap().into_iter().map(|s| s.key).collect() | 371 | + list(store) |
| 372 | + .await | ||
| 373 | + .unwrap() | ||
| 374 | + .into_iter() | ||
| 375 | + .map(|s| s.key) | ||
| 376 | + .collect() | ||
| 277 | } | 377 | } |
| 278 | 378 | ||
| 279 | #[tokio::test] | 379 | #[tokio::test] |
| @@ -299,12 +399,9 @@ mod tests { | |||
| 299 | #[tokio::test] | 399 | #[tokio::test] |
| 300 | async fn add_appends_edit_rewrites_and_a_taken_key_is_refused() { | 400 | async fn add_appends_edit_rewrites_and_a_taken_key_is_refused() { |
| 301 | let store = store().await; | 401 | let store = store().await; |
| 302 | - seed_from( | 402 | + seed_from(&store, &[service("im", "Account", "http://127.0.0.1:7650")]) |
| 303 | - &store, | 403 | + .await |
| 304 | - &[service("im", "Account", "http://127.0.0.1:7650")], | 404 | + .unwrap(); |
| 305 | - ) | ||
| 306 | - .await | ||
| 307 | - .unwrap(); | ||
| 308 | add(&store, &service("in", "Files", "http://127.0.0.1:7655")) | 405 | add(&store, &service("in", "Files", "http://127.0.0.1:7655")) |
| 309 | .await | 406 | .await |
| 310 | .unwrap(); | 407 | .unwrap(); |
| @@ -375,7 +472,9 @@ mod tests { | |||
| 375 | .unwrap(); | 472 | .unwrap(); |
| 376 | remove(&store, "im").await.unwrap(); | 473 | remove(&store, "im").await.unwrap(); |
| 377 | remove(&store, "im").await.unwrap(); // already gone: a no-op | 474 | remove(&store, "im").await.unwrap(); // already gone: a no-op |
| 378 | - add(&store, &service("wiki", "Wiki", "http://wiki")).await.unwrap(); | 475 | + add(&store, &service("wiki", "Wiki", "http://wiki")) |
| 476 | + .await | ||
| 477 | + .unwrap(); | ||
| 379 | assert_eq!( | 478 | assert_eq!( |
| 380 | keys(&store).await, | 479 | keys(&store).await, |
| 381 | vec!["in".to_string(), "iz".to_string(), "wiki".to_string()] | 480 | vec!["in".to_string(), "iz".to_string(), "wiki".to_string()] |
| @@ -385,13 +484,126 @@ mod tests { | |||
| 385 | #[tokio::test] | 484 | #[tokio::test] |
| 386 | async fn the_value_rules_refuse_garbage_before_the_database_sees_it() { | 485 | async fn the_value_rules_refuse_garbage_before_the_database_sees_it() { |
| 387 | assert!(validate("in", "Files", "http://in.example").is_ok()); | 486 | assert!(validate("in", "Files", "http://in.example").is_ok()); |
| 388 | - assert!(validate("In", "Files", "http://in.example").is_err(), "uppercase key"); | 487 | + assert!( |
| 389 | - assert!(validate("in!", "Files", "http://in.example").is_err(), "punctuated key"); | 488 | + validate("In", "Files", "http://in.example").is_err(), |
| 390 | - assert!(validate("in", " ", "http://in.example").is_err(), "blank name"); | 489 | + "uppercase key" |
| 391 | - assert!(validate("in", "Files", "ftp://in.example").is_err(), "non-http url"); | 490 | + ); |
| 491 | + assert!( | ||
| 492 | + validate("in!", "Files", "http://in.example").is_err(), | ||
| 493 | + "punctuated key" | ||
| 494 | + ); | ||
| 495 | + assert!( | ||
| 496 | + validate("in", " ", "http://in.example").is_err(), | ||
| 497 | + "blank name" | ||
| 498 | + ); | ||
| 499 | + assert!( | ||
| 500 | + validate("in", "Files", "ftp://in.example").is_err(), | ||
| 501 | + "non-http url" | ||
| 502 | + ); | ||
| 392 | assert!(validate("in", "Files", "http://").is_err(), "hostless url"); | 503 | assert!(validate("in", "Files", "http://").is_err(), "hostless url"); |
| 393 | - assert!(validate("in", "Files", "http://in.example/path x").is_err(), "space in url"); | 504 | + assert!( |
| 505 | + validate("in", "Files", "http://in.example/path x").is_err(), | ||
| 506 | + "space in url" | ||
| 507 | + ); | ||
| 394 | // A trailing slash is not garbage — it is normalized away. | 508 | // A trailing slash is not garbage — it is normalized away. |
| 395 | assert!(validate("in", "Files", "http://in.example/").is_ok()); | 509 | assert!(validate("in", "Files", "http://in.example/").is_ok()); |
| 396 | } | 510 | } |
| 511 | + | ||
| 512 | + #[tokio::test] | ||
| 513 | + async fn an_app_registers_itself_appending_then_claiming_then_refreshing() { | ||
| 514 | + let store = store().await; | ||
| 515 | + // Nothing on the list yet: the app's own row is appended. | ||
| 516 | + let row = register( | ||
| 517 | + &store, | ||
| 518 | + "im", | ||
| 519 | + "Account", | ||
| 520 | + "http://127.0.0.1:7650/", | ||
| 521 | + SELF_OWNER, | ||
| 522 | + ) | ||
| 523 | + .await | ||
| 524 | + .unwrap(); | ||
| 525 | + assert_eq!( | ||
| 526 | + row.url, "http://127.0.0.1:7650", | ||
| 527 | + "the slash is normalized off" | ||
| 528 | + ); | ||
| 529 | + assert_eq!(row.owner.as_deref(), Some(SELF_OWNER)); | ||
| 530 | + | ||
| 531 | + // A seeded row belongs to nobody; the app that names it claims it, | ||
| 532 | + // keeping the name the seed (or a later rename) gave it. | ||
| 533 | + add(&store, &service("in", "Dosyalar", "http://127.0.0.1:7655")) | ||
| 534 | + .await | ||
| 535 | + .unwrap(); | ||
| 536 | + let row = register(&store, "in", "Files", "https://in.example", "in-client") | ||
| 537 | + .await | ||
| 538 | + .unwrap(); | ||
| 539 | + assert_eq!(row.name, "Dosyalar", "the name stays the admin's"); | ||
| 540 | + assert_eq!(row.url, "https://in.example"); | ||
| 541 | + assert_eq!(row.owner.as_deref(), Some("in-client")); | ||
| 542 | + | ||
| 543 | + // The same app's next boot moves the address only. | ||
| 544 | + let row = register(&store, "in", "Whatever", "https://in.dizey.sh", "in-client") | ||
| 545 | + .await | ||
| 546 | + .unwrap(); | ||
| 547 | + assert_eq!(row.name, "Dosyalar"); | ||
| 548 | + assert_eq!(row.url, "https://in.dizey.sh"); | ||
| 549 | + // And no row was duplicated by any of it. | ||
| 550 | + assert_eq!(keys(&store).await, vec!["im".to_string(), "in".to_string()]); | ||
| 551 | + } | ||
| 552 | + | ||
| 553 | + #[tokio::test] | ||
| 554 | + async fn a_key_another_app_keeps_is_a_conflict_and_the_row_is_untouched() { | ||
| 555 | + let store = store().await; | ||
| 556 | + register(&store, "in", "Files", "https://in.example", "in-client") | ||
| 557 | + .await | ||
| 558 | + .unwrap(); | ||
| 559 | + assert!(matches!( | ||
| 560 | + register(&store, "in", "Files", "https://evil.example", "iz-client").await, | ||
| 561 | + Err(StoreError::Conflict(_)) | ||
| 562 | + )); | ||
| 563 | + assert_eq!(list(&store).await.unwrap()[0].url, "https://in.example"); | ||
| 564 | + } | ||
| 565 | + | ||
| 566 | + #[tokio::test] | ||
| 567 | + async fn the_panel_cannot_remove_an_owned_row_or_move_its_address() { | ||
| 568 | + let store = store().await; | ||
| 569 | + register(&store, "in", "Files", "https://in.example", "in-client") | ||
| 570 | + .await | ||
| 571 | + .unwrap(); | ||
| 572 | + assert!(matches!( | ||
| 573 | + remove(&store, "in").await, | ||
| 574 | + Err(StoreError::Invalid(_)) | ||
| 575 | + )); | ||
| 576 | + assert!(matches!( | ||
| 577 | + edit(&store, "in", "Dosyalar", "https://elsewhere.example").await, | ||
| 578 | + Err(StoreError::Invalid(_)) | ||
| 579 | + )); | ||
| 580 | + // The name is still the admin's, and a name-only edit lands. | ||
| 581 | + edit(&store, "in", "Dosyalar", "https://in.example") | ||
| 582 | + .await | ||
| 583 | + .unwrap(); | ||
| 584 | + let row = &list(&store).await.unwrap()[0]; | ||
| 585 | + assert_eq!(row.name, "Dosyalar"); | ||
| 586 | + assert_eq!(row.url, "https://in.example"); | ||
| 587 | + // An unowned row is still the panel's to take. | ||
| 588 | + add(&store, &service("wiki", "Wiki", "http://wiki")) | ||
| 589 | + .await | ||
| 590 | + .unwrap(); | ||
| 591 | + remove(&store, "wiki").await.unwrap(); | ||
| 592 | + assert_eq!(keys(&store).await, vec!["in".to_string()]); | ||
| 593 | + } | ||
| 594 | + | ||
| 595 | + #[tokio::test] | ||
| 596 | + async fn the_family_json_never_carries_the_owner() { | ||
| 597 | + let store = store().await; | ||
| 598 | + register(&store, "im", "Account", "http://127.0.0.1:7650", SELF_OWNER) | ||
| 599 | + .await | ||
| 600 | + .unwrap(); | ||
| 601 | + let json = serde_json::to_value(list(&store).await.unwrap()).unwrap(); | ||
| 602 | + let row = &json.as_array().unwrap()[0]; | ||
| 603 | + assert_eq!( | ||
| 604 | + row.as_object().unwrap().keys().collect::<Vec<_>>(), | ||
| 605 | + vec!["key", "name", "url"], | ||
| 606 | + "the sibling mirrors deserialize this shape: {json}" | ||
| 607 | + ); | ||
| 608 | + } | ||
| 397 | } | 609 | } |
crates/im-core/src/store.rsmodified+20 -4
| @@ -21,6 +21,10 @@ pub enum StoreError { | |||
| 21 | /// caller turns it into the page's refusal, never a database problem. | 21 | /// caller turns it into the page's refusal, never a database problem. |
| 22 | #[error("{0}")] | 22 | #[error("{0}")] |
| 23 | Invalid(String), | 23 | Invalid(String), |
| 24 | + /// The write is well-formed but the row belongs to someone else — the | ||
| 25 | + /// web layer answers 409, not 400. | ||
| 26 | + #[error("{0}")] | ||
| 27 | + Conflict(String), | ||
| 24 | } | 28 | } |
| 25 | 29 | ||
| 26 | pub type Result<T, E = StoreError> = std::result::Result<T, E>; | 30 | pub type Result<T, E = StoreError> = std::result::Result<T, E>; |
| @@ -135,7 +139,8 @@ CREATE TABLE IF NOT EXISTS services ( | |||
| 135 | key TEXT PRIMARY KEY, | 139 | key TEXT PRIMARY KEY, |
| 136 | name TEXT NOT NULL, | 140 | name TEXT NOT NULL, |
| 137 | url TEXT NOT NULL, | 141 | url TEXT NOT NULL, |
| 138 | - position INTEGER NOT NULL | 142 | + position INTEGER NOT NULL, |
| 143 | + owner TEXT | ||
| 139 | ); | 144 | ); |
| 140 | "; | 145 | "; |
| 141 | 146 | ||
| @@ -207,9 +212,12 @@ impl Store { | |||
| 207 | // born before these columns grow them here — TEXT NOT NULL with | 212 | // born before these columns grow them here — TEXT NOT NULL with |
| 208 | // a DEFAULT so every existing row reads the default. | 213 | // a DEFAULT so every existing row reads the default. |
| 209 | if !has_column(&conn, "users", "theme").await? { | 214 | if !has_column(&conn, "users", "theme").await? { |
| 210 | - conn.execute("ALTER TABLE users ADD COLUMN theme TEXT NOT NULL DEFAULT 'light'", ()) | 215 | + conn.execute( |
| 211 | - .await | 216 | + "ALTER TABLE users ADD COLUMN theme TEXT NOT NULL DEFAULT 'light'", |
| 212 | - .map_err(backend)?; | 217 | + (), |
| 218 | + ) | ||
| 219 | + .await | ||
| 220 | + .map_err(backend)?; | ||
| 213 | } | 221 | } |
| 214 | if !has_column(&conn, "users", "language").await? { | 222 | if !has_column(&conn, "users", "language").await? { |
| 215 | conn.execute( | 223 | conn.execute( |
| @@ -229,6 +237,14 @@ impl Store { | |||
| 229 | } | 237 | } |
| 230 | // What a session remembers about its browser: the listing shows | 238 | // What a session remembers about its browser: the listing shows |
| 231 | // these, so old databases grow them the same guarded way. | 239 | // these, so old databases grow them the same guarded way. |
| 240 | + // The app that keeps a service row: `im` for this app's own | ||
| 241 | + // entry, a client id for a sibling that registers itself, NULL | ||
| 242 | + // for the config seed's and the panel's own rows. | ||
| 243 | + if !has_column(&conn, "services", "owner").await? { | ||
| 244 | + conn.execute("ALTER TABLE services ADD COLUMN owner TEXT", ()) | ||
| 245 | + .await | ||
| 246 | + .map_err(backend)?; | ||
| 247 | + } | ||
| 232 | if !has_column(&conn, "sessions", "ip").await? { | 248 | if !has_column(&conn, "sessions", "ip").await? { |
| 233 | conn.execute("ALTER TABLE sessions ADD COLUMN ip TEXT", ()) | 249 | conn.execute("ALTER TABLE sessions ADD COLUMN ip TEXT", ()) |
| 234 | .await | 250 | .await |
crates/im-web/src/admin.rsmodified+46 -17
| @@ -420,17 +420,35 @@ async fn services_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat:: | |||
| 420 | let key = escape(&service.key); | 420 | let key = escape(&service.key); |
| 421 | let name = escape(&service.name); | 421 | let name = escape(&service.name); |
| 422 | let url = escape(&service.url); | 422 | let url = escape(&service.url); |
| 423 | - // The edit disclosure: the opened pop carries the name-and-address | 423 | + // A row its app keeps: the address is written on that app's every |
| 424 | - // form; the key travels hidden, like every row's write. | 424 | + // boot, so the panel neither edits it nor takes the row away — the |
| 425 | + // name and the order stay the admin's. | ||
| 426 | + let kept = service.owner.is_some(); | ||
| 427 | + // The edit disclosure: the opened pop carries the name (and, on an | ||
| 428 | + // unkept row, the address); the key travels hidden, like every | ||
| 429 | + // row's write. | ||
| 430 | + // A kept row posts the stored address back in a hidden field: the | ||
| 431 | + // form's name change is accepted, and the store refuses only a | ||
| 432 | + // *changed* address. | ||
| 433 | + let address_field = if kept { | ||
| 434 | + format!( | ||
| 435 | + r#"<input type="hidden" name="url" value="{url}">"#, | ||
| 436 | + url = url | ||
| 437 | + ) | ||
| 438 | + } else { | ||
| 439 | + format!( | ||
| 440 | + r#"<label class="auth-field"><span class="auth-label">{url_label}</span><input class="auth-input auth-input-mono" type="text" name="url" value="{url}" required></label>"#, | ||
| 441 | + url_label = t(lang, Key::AddressLabel), | ||
| 442 | + url = url, | ||
| 443 | + ) | ||
| 444 | + }; | ||
| 425 | let edit = format!( | 445 | let edit = format!( |
| 426 | - r#"<details class="admin-confirm"><summary class="admin-action">{edit_word}</summary><div class="admin-confirm-pop"><div class="admin-confirm-title">{edit_title}</div><form method="post" action="/admin/services_edit" class="admin-form"><input type="hidden" name="key" value="{key}"><label class="auth-field"><span class="auth-label">{name_label}</span><input class="auth-input auth-input-mono" type="text" name="name" value="{name}" required></label><label class="auth-field"><span class="auth-label">{url_label}</span><input class="auth-input auth-input-mono" type="text" name="url" value="{url}" required></label><button class="admin-action" type="submit">{save}</button></form></div></details>"#, | 446 | + r#"<details class="admin-confirm"><summary class="admin-action">{edit_word}</summary><div class="admin-confirm-pop"><div class="admin-confirm-title">{edit_title}</div><form method="post" action="/admin/services_edit" class="admin-form"><input type="hidden" name="key" value="{key}"><label class="auth-field"><span class="auth-label">{name_label}</span><input class="auth-input auth-input-mono" type="text" name="name" value="{name}" required></label>{address_field}<button class="admin-action" type="submit">{save}</button></form></div></details>"#, |
| 427 | edit_word = t(lang, Key::EditWord), | 447 | edit_word = t(lang, Key::EditWord), |
| 428 | edit_title = i18n::edit_service_title(lang, &name), | 448 | edit_title = i18n::edit_service_title(lang, &name), |
| 429 | key = key, | 449 | key = key, |
| 430 | name = name, | 450 | name = name, |
| 431 | - url = url, | ||
| 432 | name_label = t(lang, Key::NameCol), | 451 | name_label = t(lang, Key::NameCol), |
| 433 | - url_label = t(lang, Key::AddressLabel), | ||
| 434 | save = t(lang, Key::SaveButton), | 452 | save = t(lang, Key::SaveButton), |
| 435 | ); | 453 | ); |
| 436 | let up = format!( | 454 | let up = format!( |
| @@ -443,16 +461,23 @@ async fn services_section(cx: &Cx, lang: i18n::Lang) -> Result<String, topcoat:: | |||
| 443 | key = key, | 461 | key = key, |
| 444 | down_label = t(lang, Key::ServiceMoveDown), | 462 | down_label = t(lang, Key::ServiceMoveDown), |
| 445 | ); | 463 | ); |
| 446 | - let remove = confirm_action( | 464 | + let remove = if kept { |
| 447 | - "key", | 465 | + format!( |
| 448 | - &key, | 466 | + r#"<span class="muted">{kept_word}</span>"#, |
| 449 | - "/admin/services_remove", | 467 | + kept_word = t(lang, Key::ServiceKept), |
| 450 | - t(lang, Key::Remove), | 468 | + ) |
| 451 | - " admin-danger", | 469 | + } else { |
| 452 | - &i18n::remove_service_title(lang, &name), | 470 | + confirm_action( |
| 453 | - t(lang, Key::RemoveCost), | 471 | + "key", |
| 454 | - t(lang, Key::ConfirmRemove), | 472 | + &key, |
| 455 | - ); | 473 | + "/admin/services_remove", |
| 474 | + t(lang, Key::Remove), | ||
| 475 | + " admin-danger", | ||
| 476 | + &i18n::remove_service_title(lang, &name), | ||
| 477 | + t(lang, Key::RemoveCost), | ||
| 478 | + t(lang, Key::ConfirmRemove), | ||
| 479 | + ) | ||
| 480 | + }; | ||
| 456 | rows.push_str(&format!( | 481 | rows.push_str(&format!( |
| 457 | r#"<tr><td class="mono">{key}</td><td>{name}</td><td class="mono">{url}</td><td class="actions">{edit}{up}{down}{remove}</td></tr>"#, | 482 | r#"<tr><td class="mono">{key}</td><td>{name}</td><td class="mono">{url}</td><td class="actions">{edit}{up}{down}{remove}</td></tr>"#, |
| 458 | )); | 483 | )); |
| @@ -502,6 +527,7 @@ async fn services_add(cx: &Cx, Form(input): Form<ServiceForm>) -> Result<Respons | |||
| 502 | key: input.key, | 527 | key: input.key, |
| 503 | name: input.name, | 528 | name: input.name, |
| 504 | url: input.url, | 529 | url: input.url, |
| 530 | + owner: None, | ||
| 505 | }, | 531 | }, |
| 506 | ) | 532 | ) |
| 507 | .await; | 533 | .await; |
| @@ -514,7 +540,8 @@ async fn services_edit(cx: &Cx, Form(input): Form<ServiceForm>) -> Result<Respon | |||
| 514 | Ok(me) => me, | 540 | Ok(me) => me, |
| 515 | Err(redirect) => return Ok(redirect), | 541 | Err(redirect) => return Ok(redirect), |
| 516 | }; | 542 | }; |
| 517 | - let outcome = im_core::services::edit(&app(cx).store, &input.key, &input.name, &input.url).await; | 543 | + let outcome = |
| 544 | + im_core::services::edit(&app(cx).store, &input.key, &input.name, &input.url).await; | ||
| 518 | service_outcome(cx, &me, outcome).await | 545 | service_outcome(cx, &me, outcome).await |
| 519 | } | 546 | } |
| 520 | 547 | ||
| @@ -569,7 +596,9 @@ async fn service_outcome( | |||
| 569 | server::log_event(cx, "services_updated", Some(&me.email), None).await; | 596 | server::log_event(cx, "services_updated", Some(&me.email), None).await; |
| 570 | back(cx, "services", "&ok=services") | 597 | back(cx, "services", "&ok=services") |
| 571 | } | 598 | } |
| 572 | - Err(im_core::store::StoreError::Invalid(_)) => back(cx, "services", "&error=bad_service"), | 599 | + Err(im_core::store::StoreError::Invalid(_) | im_core::store::StoreError::Conflict(_)) => { |
| 600 | + back(cx, "services", "&error=bad_service") | ||
| 601 | + } | ||
| 573 | Err(e) => Err(e.into()), | 602 | Err(e) => Err(e.into()), |
| 574 | } | 603 | } |
| 575 | } | 604 | } |
crates/im-web/src/directory.rsmodified+249 -7
| @@ -53,7 +53,9 @@ async fn directory(cx: &Cx) -> topcoat::Result<topcoat::router::response::Respon | |||
| 53 | /// name, and base URL, in the stored order, as a bare JSON array. Registered | 53 | /// name, and base URL, in the stored order, as a bare JSON array. Registered |
| 54 | /// apps only, exactly like `/directory`: a sibling copies this into its own | 54 | /// apps only, exactly like `/directory`: a sibling copies this into its own |
| 55 | /// database and renders its switcher from that copy, so the family list has | 55 | /// database and renders its switcher from that copy, so the family list has |
| 56 | -/// one home (the admin panel here) and every other surface a cached mirror. | 56 | +/// one home (this table) and every other surface a cached mirror. The rows |
| 57 | +/// come from the panel and from the apps themselves — see | ||
| 58 | +/// `POST /family/register`. | ||
| 57 | #[route(GET "/family")] | 59 | #[route(GET "/family")] |
| 58 | async fn family(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> { | 60 | async fn family(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> { |
| 59 | if !server::valid_app(cx).await { | 61 | if !server::valid_app(cx).await { |
| @@ -68,6 +70,49 @@ async fn family(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> | |||
| 68 | Json(serde_json::to_value(services).unwrap()).into_response(cx) | 70 | Json(serde_json::to_value(services).unwrap()).into_response(cx) |
| 69 | } | 71 | } |
| 70 | 72 | ||
| 73 | +/// The body a sibling posts to keep its own row: its wordmark key, the | ||
| 74 | +/// name a fresh row is born with, and the address it answers on now. | ||
| 75 | +#[derive(serde::Deserialize)] | ||
| 76 | +struct Registration { | ||
| 77 | + key: String, | ||
| 78 | + name: String, | ||
| 79 | + url: String, | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// `POST /family/register`: an app writes its own row of the family. Same | ||
| 83 | +/// Basic pair as `/family`, and the authenticated client id is the owner — | ||
| 84 | +/// so a row an app keeps is refreshed on its every boot, never taken over | ||
| 85 | +/// by another app (409) and no longer the panel's to remove or re-point. | ||
| 86 | +#[route(POST "/family/register")] | ||
| 87 | +async fn family_register( | ||
| 88 | + cx: &Cx, | ||
| 89 | + Json(input): Json<Registration>, | ||
| 90 | +) -> topcoat::Result<topcoat::router::response::Response> { | ||
| 91 | + let Some(client_id) = server::app_client(cx).await else { | ||
| 92 | + return ( | ||
| 93 | + StatusCode::UNAUTHORIZED, | ||
| 94 | + Json(serde_json::json!({ "error": "invalid_client" })), | ||
| 95 | + ) | ||
| 96 | + .into_response(cx); | ||
| 97 | + }; | ||
| 98 | + let store = server::app(cx).store.clone(); | ||
| 99 | + match im_core::services::register(&store, &input.key, &input.name, &input.url, &client_id).await | ||
| 100 | + { | ||
| 101 | + Ok(service) => Json(serde_json::to_value(service).unwrap()).into_response(cx), | ||
| 102 | + Err(im_core::store::StoreError::Conflict(_)) => ( | ||
| 103 | + StatusCode::CONFLICT, | ||
| 104 | + Json(serde_json::json!({ "error": "owned" })), | ||
| 105 | + ) | ||
| 106 | + .into_response(cx), | ||
| 107 | + Err(im_core::store::StoreError::Invalid(reason)) => ( | ||
| 108 | + StatusCode::BAD_REQUEST, | ||
| 109 | + Json(serde_json::json!({ "error": "invalid", "reason": reason })), | ||
| 110 | + ) | ||
| 111 | + .into_response(cx), | ||
| 112 | + Err(e) => Err(e.into()), | ||
| 113 | + } | ||
| 114 | +} | ||
| 115 | + | ||
| 71 | #[cfg(test)] | 116 | #[cfg(test)] |
| 72 | mod tests { | 117 | mod tests { |
| 73 | use std::path::Path; | 118 | use std::path::Path; |
| @@ -245,6 +290,7 @@ mod tests { | |||
| 245 | key: service.key.clone(), | 290 | key: service.key.clone(), |
| 246 | name: service.name.clone(), | 291 | name: service.name.clone(), |
| 247 | url: service.url.clone(), | 292 | url: service.url.clone(), |
| 293 | + owner: None, | ||
| 248 | }) | 294 | }) |
| 249 | .collect() | 295 | .collect() |
| 250 | } | 296 | } |
| @@ -312,6 +358,29 @@ mod tests { | |||
| 312 | (parts.status, String::from_utf8(bytes).unwrap()) | 358 | (parts.status, String::from_utf8(bytes).unwrap()) |
| 313 | } | 359 | } |
| 314 | 360 | ||
| 361 | + /// `POST /family/register` with a JSON body and (maybe) an app's pair. | ||
| 362 | + async fn post_register( | ||
| 363 | + router: &Router, | ||
| 364 | + authorization: Option<String>, | ||
| 365 | + body: serde_json::Value, | ||
| 366 | + ) -> (StatusCode, serde_json::Value) { | ||
| 367 | + let mut builder = http::Request::builder() | ||
| 368 | + .method(http::Method::POST) | ||
| 369 | + .uri("/family/register") | ||
| 370 | + .header(header::CONTENT_TYPE, "application/json"); | ||
| 371 | + if let Some(value) = authorization { | ||
| 372 | + builder = builder.header(header::AUTHORIZATION, value); | ||
| 373 | + } | ||
| 374 | + let response = router | ||
| 375 | + .handle(builder.body(Body::from(body.to_string())).unwrap()) | ||
| 376 | + .await; | ||
| 377 | + let (parts, body) = response.into_parts(); | ||
| 378 | + let bytes = to_bytes(body, usize::MAX).await.unwrap().to_vec(); | ||
| 379 | + let text = String::from_utf8(bytes).unwrap(); | ||
| 380 | + let json = serde_json::from_str(&text).unwrap_or(serde_json::Value::String(text)); | ||
| 381 | + (parts.status, json) | ||
| 382 | + } | ||
| 383 | + | ||
| 315 | /// A page GET as a signed-in browser: the whole document back. | 384 | /// A page GET as a signed-in browser: the whole document back. |
| 316 | async fn get_page(router: &Router, uri: &str, cookie: &str) -> String { | 385 | async fn get_page(router: &Router, uri: &str, cookie: &str) -> String { |
| 317 | let response = router | 386 | let response = router |
| @@ -528,7 +597,10 @@ mod tests { | |||
| 528 | ) | 597 | ) |
| 529 | .await; | 598 | .await; |
| 530 | assert_eq!(status, StatusCode::SEE_OTHER); | 599 | assert_eq!(status, StatusCode::SEE_OTHER); |
| 531 | - assert_eq!(location.as_deref(), Some("/admin?section=services&ok=services")); | 600 | + assert_eq!( |
| 601 | + location.as_deref(), | ||
| 602 | + Some("/admin?section=services&ok=services") | ||
| 603 | + ); | ||
| 532 | let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | 604 | let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; |
| 533 | let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); | 605 | let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); |
| 534 | let family = family.as_array().unwrap(); | 606 | let family = family.as_array().unwrap(); |
| @@ -567,10 +639,21 @@ mod tests { | |||
| 567 | Some(&cookie), | 639 | Some(&cookie), |
| 568 | ) | 640 | ) |
| 569 | .await; | 641 | .await; |
| 570 | - assert_eq!(location.as_deref(), Some("/admin?section=services&ok=services")); | 642 | + assert_eq!( |
| 571 | - let (_status, location, _) = | 643 | + location.as_deref(), |
| 572 | - post_form(&router, "/admin/services_move", "key=wiki&dir=up", Some(&cookie)).await; | 644 | + Some("/admin?section=services&ok=services") |
| 573 | - assert_eq!(location.as_deref(), Some("/admin?section=services&ok=services")); | 645 | + ); |
| 646 | + let (_status, location, _) = post_form( | ||
| 647 | + &router, | ||
| 648 | + "/admin/services_move", | ||
| 649 | + "key=wiki&dir=up", | ||
| 650 | + Some(&cookie), | ||
| 651 | + ) | ||
| 652 | + .await; | ||
| 653 | + assert_eq!( | ||
| 654 | + location.as_deref(), | ||
| 655 | + Some("/admin?section=services&ok=services") | ||
| 656 | + ); | ||
| 574 | let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | 657 | let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; |
| 575 | let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); | 658 | let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); |
| 576 | let family = family.as_array().unwrap(); | 659 | let family = family.as_array().unwrap(); |
| @@ -599,7 +682,10 @@ mod tests { | |||
| 599 | // And once the row is gone, the same origin is refused to the door. | 682 | // And once the row is gone, the same origin is refused to the door. |
| 600 | let (_status, location, _) = | 683 | let (_status, location, _) = |
| 601 | post_form(&router, "/admin/services_remove", "key=wiki", Some(&cookie)).await; | 684 | post_form(&router, "/admin/services_remove", "key=wiki", Some(&cookie)).await; |
| 602 | - assert_eq!(location.as_deref(), Some("/admin?section=services&ok=services")); | 685 | + assert_eq!( |
| 686 | + location.as_deref(), | ||
| 687 | + Some("/admin?section=services&ok=services") | ||
| 688 | + ); | ||
| 603 | let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | 689 | let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; |
| 604 | let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); | 690 | let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); |
| 605 | let keys = family | 691 | let keys = family |
| @@ -661,6 +747,7 @@ mod tests { | |||
| 661 | key: "in".into(), | 747 | key: "in".into(), |
| 662 | name: "Files".into(), | 748 | name: "Files".into(), |
| 663 | url: "http://127.0.0.1:7655".into(), | 749 | url: "http://127.0.0.1:7655".into(), |
| 750 | + owner: None, | ||
| 664 | }]; | 751 | }]; |
| 665 | assert!(!im_core::services::seed_from(&store, &reseed).await.unwrap()); | 752 | assert!(!im_core::services::seed_from(&store, &reseed).await.unwrap()); |
| 666 | let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | 753 | let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; |
| @@ -674,4 +761,159 @@ mod tests { | |||
| 674 | "{body}" | 761 | "{body}" |
| 675 | ); | 762 | ); |
| 676 | } | 763 | } |
| 764 | + | ||
| 765 | + #[tokio::test] | ||
| 766 | + async fn an_app_registers_its_own_row_and_only_its_own() { | ||
| 767 | + let Setup { | ||
| 768 | + router, | ||
| 769 | + client_id, | ||
| 770 | + secret, | ||
| 771 | + store, | ||
| 772 | + } = setup().await; | ||
| 773 | + | ||
| 774 | + // No pair, no write. | ||
| 775 | + let (status, body) = post_register( | ||
| 776 | + &router, | ||
| 777 | + None, | ||
| 778 | + serde_json::json!({"key": "wiki", "name": "Wiki", "url": "http://wiki.example"}), | ||
| 779 | + ) | ||
| 780 | + .await; | ||
| 781 | + assert_eq!(status, StatusCode::UNAUTHORIZED); | ||
| 782 | + assert_eq!(body["error"], "invalid_client"); | ||
| 783 | + | ||
| 784 | + // A fresh key is appended, and /family carries it right away. | ||
| 785 | + let (status, body) = post_register( | ||
| 786 | + &router, | ||
| 787 | + Some(basic(&client_id, &secret)), | ||
| 788 | + serde_json::json!({"key": "wiki", "name": "Wiki", "url": "http://wiki.example/"}), | ||
| 789 | + ) | ||
| 790 | + .await; | ||
| 791 | + assert_eq!(status, StatusCode::OK, "{body}"); | ||
| 792 | + assert_eq!(body["url"], "http://wiki.example"); | ||
| 793 | + assert!( | ||
| 794 | + body.get("owner").is_none(), | ||
| 795 | + "the owner never leaves: {body}" | ||
| 796 | + ); | ||
| 797 | + let (_, listed) = get_family(&router, Some(basic(&client_id, &secret))).await; | ||
| 798 | + let listed = serde_json::from_str::<serde_json::Value>(&listed).unwrap(); | ||
| 799 | + let keys = listed | ||
| 800 | + .as_array() | ||
| 801 | + .unwrap() | ||
| 802 | + .iter() | ||
| 803 | + .map(|s| s["key"].as_str().unwrap()) | ||
| 804 | + .collect::<Vec<_>>(); | ||
| 805 | + assert_eq!(keys, vec!["in", "im", "iz", "wiki"]); | ||
| 806 | + | ||
| 807 | + // A second app cannot take the key over. | ||
| 808 | + let (other_id, other_secret) = | ||
| 809 | + create_client(&store, "other", vec!["http://other/callback".into()]) | ||
| 810 | + .await | ||
| 811 | + .unwrap(); | ||
| 812 | + let (status, body) = post_register( | ||
| 813 | + &router, | ||
| 814 | + Some(basic(&other_id.to_string(), other_secret.expose())), | ||
| 815 | + serde_json::json!({"key": "wiki", "name": "Mine", "url": "http://evil.example"}), | ||
| 816 | + ) | ||
| 817 | + .await; | ||
| 818 | + assert_eq!(status, StatusCode::CONFLICT); | ||
| 819 | + assert_eq!(body["error"], "owned"); | ||
| 820 | + | ||
| 821 | + // The keeper's next boot moves the address; the name is the panel's. | ||
| 822 | + im_core::services::edit(&store, "wiki", "Vikipedi", "http://wiki.example") | ||
| 823 | + .await | ||
| 824 | + .unwrap(); | ||
| 825 | + let (status, body) = post_register( | ||
| 826 | + &router, | ||
| 827 | + Some(basic(&client_id, &secret)), | ||
| 828 | + serde_json::json!({"key": "wiki", "name": "Wiki", "url": "http://wiki.dizey.sh"}), | ||
| 829 | + ) | ||
| 830 | + .await; | ||
| 831 | + assert_eq!(status, StatusCode::OK); | ||
| 832 | + assert_eq!(body["name"], "Vikipedi"); | ||
| 833 | + assert_eq!(body["url"], "http://wiki.dizey.sh"); | ||
| 834 | + | ||
| 835 | + // A value against the rules is a 400 with the store's own reason. | ||
| 836 | + let (status, body) = post_register( | ||
| 837 | + &router, | ||
| 838 | + Some(basic(&client_id, &secret)), | ||
| 839 | + serde_json::json!({"key": "wiki", "name": "Wiki", "url": "ftp://wiki.example"}), | ||
| 840 | + ) | ||
| 841 | + .await; | ||
| 842 | + assert_eq!(status, StatusCode::BAD_REQUEST); | ||
| 843 | + assert_eq!(body["error"], "invalid"); | ||
| 844 | + assert!(body["reason"].as_str().unwrap().contains("http"), "{body}"); | ||
| 845 | + } | ||
| 846 | + | ||
| 847 | + #[tokio::test] | ||
| 848 | + async fn the_panel_cannot_remove_a_row_its_app_keeps() { | ||
| 849 | + let Setup { | ||
| 850 | + router, | ||
| 851 | + client_id, | ||
| 852 | + secret, | ||
| 853 | + store, | ||
| 854 | + } = setup().await; | ||
| 855 | + let ada = im_core::accounts::user_by_email(&store, "ada@example.com") | ||
| 856 | + .await | ||
| 857 | + .unwrap() | ||
| 858 | + .unwrap(); | ||
| 859 | + let session = im_core::sessions::create_session(&store, &ada.id, &Default::default()) | ||
| 860 | + .await | ||
| 861 | + .unwrap(); | ||
| 862 | + let cookie = format!("{SESSION_COOKIE}={}", session.expose()); | ||
| 863 | + | ||
| 864 | + // The app claims the seeded `in` row. | ||
| 865 | + let (status, _) = post_register( | ||
| 866 | + &router, | ||
| 867 | + Some(basic(&client_id, &secret)), | ||
| 868 | + serde_json::json!({"key": "in", "name": "Files", "url": "https://in.dizey.sh"}), | ||
| 869 | + ) | ||
| 870 | + .await; | ||
| 871 | + assert_eq!(status, StatusCode::OK); | ||
| 872 | + | ||
| 873 | + // The panel's remove is refused and the row stays. | ||
| 874 | + let (_status, location, _) = | ||
| 875 | + post_form(&router, "/admin/services_remove", "key=in", Some(&cookie)).await; | ||
| 876 | + assert_eq!( | ||
| 877 | + location.as_deref(), | ||
| 878 | + Some("/admin?section=services&error=bad_service") | ||
| 879 | + ); | ||
| 880 | + // So is a re-point; a rename still lands. | ||
| 881 | + let (_status, location, _) = post_form( | ||
| 882 | + &router, | ||
| 883 | + "/admin/services_edit", | ||
| 884 | + "key=in&name=Dosyalar&url=http%3A%2F%2Felsewhere.example", | ||
| 885 | + Some(&cookie), | ||
| 886 | + ) | ||
| 887 | + .await; | ||
| 888 | + assert_eq!( | ||
| 889 | + location.as_deref(), | ||
| 890 | + Some("/admin?section=services&error=bad_service") | ||
| 891 | + ); | ||
| 892 | + let (_status, location, _) = post_form( | ||
| 893 | + &router, | ||
| 894 | + "/admin/services_edit", | ||
| 895 | + "key=in&name=Dosyalar&url=https%3A%2F%2Fin.dizey.sh", | ||
| 896 | + Some(&cookie), | ||
| 897 | + ) | ||
| 898 | + .await; | ||
| 899 | + assert_eq!( | ||
| 900 | + location.as_deref(), | ||
| 901 | + Some("/admin?section=services&ok=services") | ||
| 902 | + ); | ||
| 903 | + let (_, body) = get_family(&router, Some(basic(&client_id, &secret))).await; | ||
| 904 | + let family = serde_json::from_str::<serde_json::Value>(&body).unwrap(); | ||
| 905 | + assert_eq!(family[0]["key"], "in"); | ||
| 906 | + assert_eq!(family[0]["name"], "Dosyalar"); | ||
| 907 | + assert_eq!(family[0]["url"], "https://in.dizey.sh"); | ||
| 908 | + | ||
| 909 | + // And the panel offers no remove form for it — the marker instead. | ||
| 910 | + let panel = get_page(&router, "/admin?section=services", &cookie).await; | ||
| 911 | + assert!(panel.contains("kept by the app"), "the marker is missing"); | ||
| 912 | + assert!( | ||
| 913 | + !panel.contains(r#"value="in"><button class="admin-action admin-danger"#), | ||
| 914 | + "an owned row must carry no remove form" | ||
| 915 | + ); | ||
| 916 | + // The unowned rows still do. | ||
| 917 | + assert!(panel.contains(r#"action="/admin/services_remove""#)); | ||
| 918 | + } | ||
| 677 | } | 919 | } |
crates/im-web/src/i18n.rsmodified+3 -0
| @@ -130,6 +130,7 @@ pub enum Key { | |||
| 130 | ServicesTitle, | 130 | ServicesTitle, |
| 131 | ServiceKeyLabel, | 131 | ServiceKeyLabel, |
| 132 | ServiceAdd, | 132 | ServiceAdd, |
| 133 | + ServiceKept, | ||
| 133 | ServiceMoveUp, | 134 | ServiceMoveUp, |
| 134 | ServiceMoveDown, | 135 | ServiceMoveDown, |
| 135 | SignOutEverywhere, | 136 | SignOutEverywhere, |
| @@ -470,6 +471,8 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 470 | (ServiceKeyLabel, Tr) => "Anahtar", | 471 | (ServiceKeyLabel, Tr) => "Anahtar", |
| 471 | (ServiceAdd, En) => "Add service", | 472 | (ServiceAdd, En) => "Add service", |
| 472 | (ServiceAdd, Tr) => "Hizmet ekle", | 473 | (ServiceAdd, Tr) => "Hizmet ekle", |
| 474 | + (ServiceKept, En) => "kept by the app", | ||
| 475 | + (ServiceKept, Tr) => "uygulaması koruyor", | ||
| 473 | (ServiceMoveUp, En) => "Move up", | 476 | (ServiceMoveUp, En) => "Move up", |
| 474 | (ServiceMoveUp, Tr) => "Yukarı taşı", | 477 | (ServiceMoveUp, Tr) => "Yukarı taşı", |
| 475 | (ServiceMoveDown, En) => "Move down", | 478 | (ServiceMoveDown, En) => "Move down", |
crates/im-web/src/main.rsmodified+24 -1
| @@ -12,8 +12,8 @@ use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route}; | |||
| 12 | 12 | ||
| 13 | mod admin; | 13 | mod admin; |
| 14 | mod auth; | 14 | mod auth; |
| 15 | -mod directory; | ||
| 16 | mod config; | 15 | mod config; |
| 16 | +mod directory; | ||
| 17 | mod dropdown; | 17 | mod dropdown; |
| 18 | mod i18n; | 18 | mod i18n; |
| 19 | mod layout; | 19 | mod layout; |
| @@ -158,6 +158,7 @@ async fn seed_services(store: &Store, config: &Config) { | |||
| 158 | key: service.key.clone(), | 158 | key: service.key.clone(), |
| 159 | name: service.name.clone(), | 159 | name: service.name.clone(), |
| 160 | url: service.url.clone(), | 160 | url: service.url.clone(), |
| 161 | + owner: None, | ||
| 161 | }) | 162 | }) |
| 162 | .collect(); | 163 | .collect(); |
| 163 | match im_core::services::seed_from(store, &seed).await { | 164 | match im_core::services::seed_from(store, &seed).await { |
| @@ -170,6 +171,27 @@ async fn seed_services(store: &Store, config: &Config) { | |||
| 170 | } | 171 | } |
| 171 | } | 172 | } |
| 172 | 173 | ||
| 174 | +/// im's own row of the family, written on every boot from `issuer`: the | ||
| 175 | +/// address is the running app's, not a config line someone edits once and | ||
| 176 | +/// forgets. A seeded `im` row is claimed here (its name stays the admin's); | ||
| 177 | +/// afterwards the panel can rename and reorder it, but not re-point or | ||
| 178 | +/// remove it. Never a reason to refuse boot — the family is a convenience, | ||
| 179 | +/// the sign-in is not. | ||
| 180 | +async fn register_self(store: &Store, config: &Config) { | ||
| 181 | + match im_core::services::register( | ||
| 182 | + store, | ||
| 183 | + im_core::services::SELF_OWNER, | ||
| 184 | + "Account", | ||
| 185 | + &config.issuer, | ||
| 186 | + im_core::services::SELF_OWNER, | ||
| 187 | + ) | ||
| 188 | + .await | ||
| 189 | + { | ||
| 190 | + Ok(service) => println!("im registered itself in the family at {}", service.url), | ||
| 191 | + Err(e) => eprintln!("im: registering itself in the family failed: {e}"), | ||
| 192 | + } | ||
| 193 | +} | ||
| 194 | + | ||
| 173 | /// `im-web invite <email> [--admin]`: creates the invite, mails it when the | 195 | /// `im-web invite <email> [--admin]`: creates the invite, mails it when the |
| 174 | /// panel has configured a sender, prints the link otherwise (dev mode). | 196 | /// panel has configured a sender, prints the link otherwise (dev mode). |
| 175 | /// | 197 | /// |
| @@ -243,6 +265,7 @@ async fn serve(config: Config) { | |||
| 243 | } | 265 | } |
| 244 | let store = open_store(&config).await; | 266 | let store = open_store(&config).await; |
| 245 | seed_services(&store, &config).await; | 267 | seed_services(&store, &config).await; |
| 268 | + register_self(&store, &config).await; | ||
| 246 | let (live, _) = tokio::sync::broadcast::channel(64); | 269 | let (live, _) = tokio::sync::broadcast::channel(64); |
| 247 | // Told when the process is stopping, so the live streams end instead of | 270 | // Told when the process is stopping, so the live streams end instead of |
| 248 | // being waited out — see `live::Shutdown`. | 271 | // being waited out — see `live::Shutdown`. |
crates/im-web/src/server.rsmodified+18 -18
| @@ -175,27 +175,27 @@ pub fn opened_pending(cx: &Cx) -> Option<Pending> { | |||
| 175 | /// registry. Anything unparseable, unknown, or wrong is simply false — the | 175 | /// registry. Anything unparseable, unknown, or wrong is simply false — the |
| 176 | /// caller answers its one refusal and never says which. | 176 | /// caller answers its one refusal and never says which. |
| 177 | pub async fn valid_app(cx: &Cx) -> bool { | 177 | pub async fn valid_app(cx: &Cx) -> bool { |
| 178 | + app_client(cx).await.is_some() | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/// The same check, answering *which* app it is: the routes that write on a | ||
| 182 | +/// caller's behalf (`/family/register`) need the client id the pair | ||
| 183 | +/// authenticated, and the ones that only read do not. | ||
| 184 | +pub async fn app_client(cx: &Cx) -> Option<String> { | ||
| 178 | use base64::Engine as _; | 185 | use base64::Engine as _; |
| 179 | use topcoat::router::{header, request::headers as request_headers}; | 186 | use topcoat::router::{header, request::headers as request_headers}; |
| 180 | - let Some(encoded) = request_headers(cx) | 187 | + let encoded = request_headers(cx) |
| 181 | .get(header::AUTHORIZATION) | 188 | .get(header::AUTHORIZATION) |
| 182 | .and_then(|value| value.to_str().ok()) | 189 | .and_then(|value| value.to_str().ok()) |
| 183 | - .and_then(|value| value.strip_prefix("Basic ")) | 190 | + .and_then(|value| value.strip_prefix("Basic "))?; |
| 184 | - else { | 191 | + let decoded = base64::engine::general_purpose::STANDARD |
| 185 | - return false; | 192 | + .decode(encoded) |
| 186 | - }; | 193 | + .ok()?; |
| 187 | - let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(encoded) else { | 194 | + let pair = std::str::from_utf8(&decoded).ok()?; |
| 188 | - return false; | 195 | + let (client_id, secret) = pair.split_once(':')?; |
| 189 | - }; | ||
| 190 | - let Ok(pair) = std::str::from_utf8(&decoded) else { | ||
| 191 | - return false; | ||
| 192 | - }; | ||
| 193 | - let Some((client_id, secret)) = pair.split_once(':') else { | ||
| 194 | - return false; | ||
| 195 | - }; | ||
| 196 | let store = app(cx).store.clone(); | 196 | let store = app(cx).store.clone(); |
| 197 | - let Ok(Some(client)) = im_core::oidc::client_by_id(&store, client_id).await else { | 197 | + let client = im_core::oidc::client_by_id(&store, client_id) |
| 198 | - return false; | 198 | + .await |
| 199 | - }; | 199 | + .ok()??; |
| 200 | - im_core::oidc::verify_client_secret(&client, secret) | 200 | + im_core::oidc::verify_client_secret(&client, secret).then(|| client_id.to_string()) |
| 201 | } | 201 | } |