forge
Explore
Log in

Don't you dare go Hollow

the app files itself in im's family: before every family beat the client posts {in, Files, public origin} to im's POST /family/register with the client pair, so im lists this app at its real address without an admin typing it; an empty public address logs once at boot and skips only the registration, and a refusal or an im that does not register yet costs one log line while the mirror fetch still runs

Browse files at this commit

922246b667ec41828c955f8b7ab304c7bb43f1c3Ahmet Kaan GümüşParent: a1b335c
Claude-Session: https://claude.ai/code/session_01JDMA1TAen2UjGRvUVu96KE
config/in.tomlmodified+4 -2
@@ -21,8 +21,10 @@ base_url = ""
21 # and the boot completes this file with the value it resolved.21 # and the boot completes this file with the value it resolved.
22 22
23 # The suite the switcher's wordmarks link to is im's to keep — im's admin23 # The suite the switcher's wordmarks link to is im's to keep — im's admin
24-# panel owns the list, and In fetches it from im and keeps a mirror. This24+# panel owns the list, and In fetches it from im and keeps a mirror. On
25-# file no longer names the suite; a `[[services]]` block left behind by an25+# every beat In also announces itself to im under the key "in" at the
26+# address `base_url` gives, so the suite lists it without anyone typing it.
27+# This file no longer names the suite; a `[[services]]` block left behind by an
26 # older file is reported as ignored and then passed over.28 # older file is reported as ignored and then passed over.
27 # Where drive files, thumbnails and staged upload chunks live as files, created on boot.29 # Where drive files, thumbnails and staged upload chunks live as files, created on boot.
28 storage = "/home/tahinli/Documents/Code/Rust/in/storage"30 storage = "/home/tahinli/Documents/Code/Rust/in/storage"
crates/in-client/src/lib.rsmodified+143 -34
@@ -243,6 +243,49 @@ impl InClient {
243 }243 }
244 reply.json().await.ok()244 reply.json().await.ok()
245 }245 }
246+
247+ /// Tells im this app is one of the family: the key the switcher inks,
248+ /// the label its title wears, and the address it lives at, posted as
249+ /// this app (Basic client credentials) to `{issuer}/family/register`.
250+ /// Sent on every family beat, not only at boot, so a moved address
251+ /// corrects itself and a fresh im learns the app without an admin
252+ /// typing anything.
253+ ///
254+ /// `Ok` on any 2xx — im filed the entry or it already reads that way.
255+ /// `Err` names the status and whatever im said about it (`error` /
256+ /// `reason`), including the 404 or 405 an im too old to register with
257+ /// answers; the caller logs and carries on, because a refused
258+ /// registration must never stop the mirror that follows.
259+ pub async fn register_family(&self, key: &str, name: &str, url: &str) -> Result<(), String> {
260+ let reply = self
261+ .http
262+ .post(format!("{}/family/register", self.config.issuer))
263+ .basic_auth(&self.config.client_id, Some(&self.config.client_secret))
264+ .json(&ServiceJson {
265+ key: key.to_string(),
266+ name: name.to_string(),
267+ url: url.to_string(),
268+ })
269+ .send()
270+ .await
271+ .map_err(|problem| format!("im did not answer: {problem}"))?;
272+ let status = reply.status();
273+ if status.is_success() {
274+ return Ok(());
275+ }
276+ let said = reply.json::<serde_json::Value>().await.ok();
277+ let detail = said.as_ref().and_then(|said| {
278+ let error = said.get("error")?.as_str()?;
279+ Some(match said.get("reason").and_then(|r| r.as_str()) {
280+ Some(reason) => format!("{error}: {reason}"),
281+ None => error.to_string(),
282+ })
283+ });
284+ Err(match detail {
285+ Some(detail) => format!("im refused with {status}: {detail}"),
286+ None => format!("im refused with {status}"),
287+ })
288+ }
246 }289 }
247 290
248 /// im's family list — the suite the signed-in chrome's switcher renders —291 /// im's family list — the suite the signed-in chrome's switcher renders —
@@ -626,7 +669,9 @@ async fn in_logout(cx: &Cx) -> Result<Response, topcoat::Error> {
626 let state = client(cx);669 let state = client(cx);
627 clear_cookie(cx, &state.config.cookie_name);670 clear_cookie(cx, &state.config.cookie_name);
628 let back = match try_app_context::<LogoutBack>(cx) {671 let back = match try_app_context::<LogoutBack>(cx) {
629- Some(ask) => (ask.0)(cx).await.unwrap_or_else(|| state.config.logout_back.clone()),672+ Some(ask) => (ask.0)(cx)
673+ .await
674+ .unwrap_or_else(|| state.config.logout_back.clone()),
630 None => state.config.logout_back.clone(),675 None => state.config.logout_back.clone(),
631 };676 };
632 see(677 see(
@@ -700,7 +745,9 @@ async fn exchange_code(state: &InClient, code: &str, flight: &InFlight) -> Resul
700 let (_user, exp) = match introspect(state, &app_session).await {745 let (_user, exp) = match introspect(state, &app_session).await {
701 Introspected::Active(user, exp) => (user, exp),746 Introspected::Active(user, exp) => (user, exp),
702 Introspected::Revoked | Introspected::Unanswered => {747 Introspected::Revoked | Introspected::Unanswered => {
703- return Err(Error::Refused("fresh app session does not introspect".into()));748+ return Err(Error::Refused(
749+ "fresh app session does not introspect".into(),
750+ ));
704 }751 }
705 };752 };
706 Ok(Session { app_session, exp })753 Ok(Session { app_session, exp })
@@ -836,9 +883,9 @@ mod tests {
836 use super::*;883 use super::*;
837 use rsa::signature::{SignatureEncoding, Signer};884 use rsa::signature::{SignatureEncoding, Signer};
838 use rsa::traits::PublicKeyParts;885 use rsa::traits::PublicKeyParts;
886+ use std::sync::{Arc, OnceLock};
839 use topcoat::cookie::RouterBuilderCookieExt;887 use topcoat::cookie::RouterBuilderCookieExt;
840 use topcoat::router::{Body, Router, to_bytes};888 use topcoat::router::{Body, Router, to_bytes};
841- use std::sync::{Arc, OnceLock};
842 889
843 fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) {890 fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) {
844 // 2048-bit generation is slow for a unit test; 1024 is the smallest891 // 2048-bit generation is slow for a unit test; 1024 is the smallest
@@ -975,7 +1022,10 @@ mod tests {
975 fn next_allows_plain_local_paths() {1022 fn next_allows_plain_local_paths() {
976 assert_eq!(safe_next("/"), "/");1023 assert_eq!(safe_next("/"), "/");
977 assert_eq!(safe_next("/drive/folder/a"), "/drive/folder/a");1024 assert_eq!(safe_next("/drive/folder/a"), "/drive/folder/a");
978- assert_eq!(safe_next("/?auth_error=exchange_failed"), "/?auth_error=exchange_failed");1025+ assert_eq!(
1026+ safe_next("/?auth_error=exchange_failed"),
1027+ "/?auth_error=exchange_failed"
1028+ );
979 }1029 }
980 1030
981 #[test]1031 #[test]
@@ -1007,7 +1057,10 @@ mod tests {
1007 // `HeaderValue` refuses the injected bytes; the redirect must land1057 // `HeaderValue` refuses the injected bytes; the redirect must land
1008 // on `/` rather than panic its handler.1058 // on `/` rather than panic its handler.
1009 assert!(HeaderValue::from_str("/\r\nX-evil:1").is_err());1059 assert!(HeaderValue::from_str("/\r\nX-evil:1").is_err());
1010- assert_eq!(location_value("/\r\nX-evil:1"), HeaderValue::from_static("/"));1060+ assert_eq!(
1061+ location_value("/\r\nX-evil:1"),
1062+ HeaderValue::from_static("/")
1063+ );
1011 assert_eq!(1064 assert_eq!(
1012 location_value("/drive"),1065 location_value("/drive"),
1013 HeaderValue::from_str("/drive").unwrap()1066 HeaderValue::from_str("/drive").unwrap()
@@ -1131,6 +1184,10 @@ mod tests {
1131 token: Arc<OnceLock<String>>,1184 token: Arc<OnceLock<String>>,
1132 jwks: Arc<OnceLock<String>>,1185 jwks: Arc<OnceLock<String>>,
1133 introspect: Arc<OnceLock<String>>,1186 introspect: Arc<OnceLock<String>>,
1187+ /// `POST /family/register`, with the status im answers it under —
1188+ /// the one canned reply whose status the test chooses, because a
1189+ /// refusal is what the caller is meant to name.
1190+ register: Arc<OnceLock<(u16, String)>>,
1134 }1191 }
1135 1192
1136 struct FakeIm {1193 struct FakeIm {
@@ -1162,8 +1219,7 @@ mod tests {
1162 }1219 }
1163 req.extend_from_slice(&buf[..n]);1220 req.extend_from_slice(&buf[..n]);
1164 if let Some(end) = headers_end(&req) {1221 if let Some(end) = headers_end(&req) {
1165- let head =1222+ let head = String::from_utf8_lossy(&req[..end]).to_string();
1166- String::from_utf8_lossy(&req[..end]).to_string();
1167 let len = content_length(&head);1223 let len = content_length(&head);
1168 if req.len() >= end + len {1224 if req.len() >= end + len {
1169 break end;1225 break end;
@@ -1173,20 +1229,25 @@ mod tests {
1173 return;1229 return;
1174 }1230 }
1175 };1231 };
1176- let head =1232+ let head = String::from_utf8_lossy(&req[..body_start]).to_string();
1177- String::from_utf8_lossy(&req[..body_start]).to_string();
1178 let first = head.lines().next().unwrap_or("").to_string();1233 let first = head.lines().next().unwrap_or("").to_string();
1179 let len = content_length(&head);1234 let len = content_length(&head);
1180 req.drain(..body_start + len);1235 req.drain(..body_start + len);
1181- let payload = if first.starts_with("POST /token ") {1236+ let (status, payload) = if first.starts_with("POST /token ") {
1182- canned.token.get().cloned().unwrap_or_default()1237+ (200, canned.token.get().cloned().unwrap_or_default())
1183 } else if first.starts_with("GET /jwks.json ") {1238 } else if first.starts_with("GET /jwks.json ") {
1184- canned.jwks.get().cloned().unwrap_or_default()1239+ (200, canned.jwks.get().cloned().unwrap_or_default())
1240+ } else if first.starts_with("POST /family/register ") {
1241+ canned
1242+ .register
1243+ .get()
1244+ .cloned()
1245+ .unwrap_or((200, String::new()))
1185 } else {1246 } else {
1186- canned.introspect.get().cloned().unwrap_or_default()1247+ (200, canned.introspect.get().cloned().unwrap_or_default())
1187 };1248 };
1188 let response = format!(1249 let response = format!(
1189- "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: keep-alive\r\n\r\n",1250+ "HTTP/1.1 {status} x\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: keep-alive\r\n\r\n",
1190 payload.len()1251 payload.len()
1191 );1252 );
1192 if socket.write_all(response.as_bytes()).await.is_err() {1253 if socket.write_all(response.as_bytes()).await.is_err() {
@@ -1281,23 +1342,23 @@ mod tests {
1281 let _ = canned1342 let _ = canned
1282 .jwks1343 .jwks
1283 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());1344 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());
1284- let _ = canned1345+ let _ = canned.token.set(
1285- .token1346+ serde_json::json!({
1286- .set(serde_json::json!({
1287 "id_token": id_token,1347 "id_token": id_token,
1288 "app_session": "tok-1",1348 "app_session": "tok-1",
1289 })1349 })
1290- .to_string());1350+ .to_string(),
1291- let _ = canned1351+ );
1292- .introspect1352+ let _ = canned.introspect.set(
1293- .set(serde_json::json!({1353+ serde_json::json!({
1294 "active": true,1354 "active": true,
1295 "sub": "user-1",1355 "sub": "user-1",
1296 "email": "ann@example.com",1356 "email": "ann@example.com",
1297 "name": "Ann",1357 "name": "Ann",
1298 "exp": now + 3600,1358 "exp": now + 3600,
1299 })1359 })
1300- .to_string());1360+ .to_string(),
1361+ );
1301 1362
1302 let router = test_router(test_config(fake.url()));1363 let router = test_router(test_config(fake.url()));
1303 let callback = TestResponse::of(1364 let callback = TestResponse::of(
@@ -1344,23 +1405,23 @@ mod tests {
1344 let _ = canned1405 let _ = canned
1345 .jwks1406 .jwks
1346 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());1407 .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());
1347- let _ = canned1408+ let _ = canned.token.set(
1348- .token1409+ serde_json::json!({
1349- .set(serde_json::json!({
1350 "id_token": id_token,1410 "id_token": id_token,
1351 "app_session": "tok-1",1411 "app_session": "tok-1",
1352 })1412 })
1353- .to_string());1413+ .to_string(),
1354- let _ = canned1414+ );
1355- .introspect1415+ let _ = canned.introspect.set(
1356- .set(serde_json::json!({1416+ serde_json::json!({
1357 "active": true,1417 "active": true,
1358 "sub": "user-1",1418 "sub": "user-1",
1359 "email": "ann@example.com",1419 "email": "ann@example.com",
1360 "name": "Ann",1420 "name": "Ann",
1361 "exp": now + 3600,1421 "exp": now + 3600,
1362 })1422 })
1363- .to_string());1423+ .to_string(),
1424+ );
1364 1425
1365 let router = test_router(test_config(fake.url()));1426 let router = test_router(test_config(fake.url()));
1366 let callback = TestResponse::of(1427 let callback = TestResponse::of(
@@ -1467,16 +1528,16 @@ mod tests {
1467 async fn current_user_serves_the_introspected_user() {1528 async fn current_user_serves_the_introspected_user() {
1468 let now = OffsetDateTime::now_utc().unix_timestamp();1529 let now = OffsetDateTime::now_utc().unix_timestamp();
1469 let canned = CannedIm::default();1530 let canned = CannedIm::default();
1470- let _ = canned1531+ let _ = canned.introspect.set(
1471- .introspect1532+ serde_json::json!({
1472- .set(serde_json::json!({
1473 "active": true,1533 "active": true,
1474 "sub": "user-1",1534 "sub": "user-1",
1475 "email": "ann@example.com",1535 "email": "ann@example.com",
1476 "name": "Ann",1536 "name": "Ann",
1477 "exp": now + 3600,1537 "exp": now + 3600,
1478 })1538 })
1479- .to_string());1539+ .to_string(),
1540+ );
1480 let fake = FakeIm::spawn(canned).await;1541 let fake = FakeIm::spawn(canned).await;
1481 let router = test_router(test_config(fake.url()));1542 let router = test_router(test_config(fake.url()));
1482 let res = TestResponse::of(1543 let res = TestResponse::of(
@@ -1492,4 +1553,52 @@ mod tests {
1492 res.set_cookies1553 res.set_cookies
1493 );1554 );
1494 }1555 }
1556+
1557+ #[tokio::test]
1558+ async fn register_family_files_the_entry() {
1559+ let canned = CannedIm::default();
1560+ let _ = canned.register.set((
1561+ 200,
1562+ serde_json::json!({"key": "in", "name": "Files", "url": "http://app.test"}).to_string(),
1563+ ));
1564+ let fake = FakeIm::spawn(canned).await;
1565+ let client = InClient::new(test_config(fake.url()));
1566+ assert_eq!(
1567+ client
1568+ .register_family("in", "Files", "http://app.test")
1569+ .await,
1570+ Ok(())
1571+ );
1572+ }
1573+
1574+ #[tokio::test]
1575+ async fn register_family_names_a_key_another_app_owns() {
1576+ let canned = CannedIm::default();
1577+ let _ = canned
1578+ .register
1579+ .set((409, serde_json::json!({"error": "owned"}).to_string()));
1580+ let fake = FakeIm::spawn(canned).await;
1581+ let client = InClient::new(test_config(fake.url()));
1582+ let problem = client
1583+ .register_family("in", "Files", "http://app.test")
1584+ .await
1585+ .unwrap_err();
1586+ assert!(problem.contains("owned"), "{problem}");
1587+ assert!(problem.contains("409"), "{problem}");
1588+ }
1589+
1590+ /// An im too old to know the route answers 404 — an `Err` the caller
1591+ /// logs, never a panic and never a success.
1592+ #[tokio::test]
1593+ async fn register_family_survives_an_im_without_the_route() {
1594+ let canned = CannedIm::default();
1595+ let _ = canned.register.set((404, String::new()));
1596+ let fake = FakeIm::spawn(canned).await;
1597+ let client = InClient::new(test_config(fake.url()));
1598+ let problem = client
1599+ .register_family("in", "Files", "http://app.test")
1600+ .await
1601+ .unwrap_err();
1602+ assert!(problem.contains("404"), "{problem}");
1603+ }
1495 }1604 }
crates/in-web/src/main.rsmodified+22 -2
@@ -1,8 +1,8 @@
1 use std::sync::Arc;1 use std::sync::Arc;
2 2
3 use in_core::Config;3 use in_core::Config;
4-use in_core::store::{Store, TursoStore};
5 use in_core::store::r2::R2Blobs;4 use in_core::store::r2::R2Blobs;
5+use in_core::store::{Store, TursoStore};
6 use topcoat::Result;6 use topcoat::Result;
7 use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};7 use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
8 use topcoat::context::Cx;8 use topcoat::context::Cx;
@@ -219,9 +219,14 @@ async fn main() {
219 // a fresh deploy shows the trio at boot; an im that does not answer —219 // a fresh deploy shows the trio at boot; an im that does not answer —
220 // down, restarting, mid-deploy — costs one log line and nothing else:220 // down, restarting, mid-deploy — costs one log line and nothing else:
221 // the last list filed keeps the switcher alive until the next beat.221 // the last list filed keeps the switcher alive until the next beat.
222+ // The address the app registers itself under: the same origin the
223+ // logout walk and the share links carry, without the trailing slash im
224+ // keeps its entries free of.
225+ let public_origin = config.public_origin().trim_end_matches('/').to_string();
222 tokio::spawn(family_sync(226 tokio::spawn(family_sync(
223 store.clone(),227 store.clone(),
224 in_client::InClient::new(oidc.clone()),228 in_client::InClient::new(oidc.clone()),
229+ public_origin,
225 ));230 ));
226 231
227 // Told when the process is stopping, so the live streams end instead of232 // Told when the process is stopping, so the live streams end instead of
@@ -337,8 +342,23 @@ const FAMILY_SECONDS: u64 = 300;
337 /// `family` setting — the one row the switcher reads, so a beat that342 /// `family` setting — the one row the switcher reads, so a beat that
338 /// answers simply replaces what is filed. Runs the whole life of the343 /// answers simply replaces what is filed. Runs the whole life of the
339 /// process; nothing here is worth keeping alive past shutdown.344 /// process; nothing here is worth keeping alive past shutdown.
340-async fn family_sync(store: Arc<dyn in_core::store::Store>, client: in_client::InClient) {345+async fn family_sync(
346+ store: Arc<dyn in_core::store::Store>,
347+ client: in_client::InClient,
348+ origin: String,
349+) {
350+ if origin.is_empty() {
351+ eprintln!("family: no public address to register; set base_url");
352+ }
341 loop {353 loop {
354+ // Announced before every fetch, so an im that was down, restarted
355+ // or freshly seeded learns this app on the next beat. A refusal is
356+ // one log line: the mirror below runs either way.
357+ if !origin.is_empty()
358+ && let Err(problem) = client.register_family("in", "Files", &origin).await
359+ {
360+ eprintln!("family register: {problem}");
361+ }
342 match client.family().await {362 match client.family().await {
343 Some(family) => match serde_json::to_string(&family) {363 Some(family) => match serde_json::to_string(&family) {
344 Ok(json) => {364 Ok(json) => {