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 {iz, Board, public address} to im's POST /family/register with the client pair — the address resolved per beat the way a sign-out resolves it, the stored public address first, then base_url, then the bound one — so im lists this app at its real address without an admin typing it; an empty 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

87d91bc4537781df3c5cc9b48674f0cabb1167beAhmet Kaan GümüşParent: 03a5482
Claude-Session: https://claude.ai/code/session_01JDMA1TAen2UjGRvUVu96KE
crates/iz-client/src/lib.rsmodified+134 -5
@@ -244,6 +244,49 @@ impl IzClient {
244 }244 }
245 reply.json().await.ok()245 reply.json().await.ok()
246 }246 }
247+
248+ /// Files this app in im's family list, so the switcher learns where it
249+ /// lives without an admin typing the address: the app's key, name and
250+ /// public origin posted as the app (`Authorization: Basic` with the
251+ /// client pair, the same credentials the family fetch takes). `Ok` on
252+ /// any 2xx; anything else is an `Err` naming the status and whatever
253+ /// `error`/`reason` im gave with it — a refused pair, a key another app
254+ /// owns, or the 404 an im too old to register answers. All of those are
255+ /// a line in the log and never a reason to stop mirroring: the caller
256+ /// goes on to the fetch either way.
257+ pub async fn register_family(
258+ &self,
259+ key: &str,
260+ name: &str,
261+ url: &str,
262+ ) -> std::result::Result<(), String> {
263+ let reply = self
264+ .http
265+ .post(format!("{}/family/register", self.config.issuer))
266+ .basic_auth(&self.config.client_id, Some(&self.config.client_secret))
267+ .json(&serde_json::json!({ "key": key, "name": name, "url": url }))
268+ .send()
269+ .await
270+ .map_err(|problem| problem.to_string())?;
271+ let status = reply.status();
272+ if status.is_success() {
273+ return Ok(());
274+ }
275+ // The body is im's own account of the refusal — `owned`, `invalid`
276+ // with a reason. A body that is not JSON, or one that names neither,
277+ // leaves the status to speak alone.
278+ let body = reply.text().await.unwrap_or_default();
279+ let said = serde_json::from_str::<serde_json::Value>(&body).unwrap_or_default();
280+ let error = said.get("error").and_then(|v| v.as_str()).unwrap_or("");
281+ let reason = said.get("reason").and_then(|v| v.as_str()).unwrap_or("");
282+ let detail = match (error, reason) {
283+ ("", "") => String::new(),
284+ (error, "") => format!(": {error}"),
285+ ("", reason) => format!(": {reason}"),
286+ (error, reason) => format!(": {error} ({reason})"),
287+ };
288+ Err(format!("im answered {status}{detail}"))
289+ }
247 }290 }
248 291
249 /// Path of im's RFC 7662 introspection endpoint, relative to the issuer.292 /// Path of im's RFC 7662 introspection endpoint, relative to the issuer.
@@ -1114,6 +1157,13 @@ mod tests {
1114 token: Arc<OnceLock<String>>,1157 token: Arc<OnceLock<String>>,
1115 jwks: Arc<OnceLock<String>>,1158 jwks: Arc<OnceLock<String>>,
1116 introspect: Arc<OnceLock<String>>,1159 introspect: Arc<OnceLock<String>>,
1160+ /// Status and body for `POST /family/register`, so a test can be
1161+ /// an im that accepts, one that says the key is owned, or one too
1162+ /// old to know the route at all.
1163+ register: Arc<OnceLock<(u16, String)>>,
1164+ /// The whole first registration request, head and body, for the
1165+ /// test that reads back what was sent.
1166+ register_seen: Arc<OnceLock<String>>,
1117 }1167 }
1118 1168
1119 struct FakeIm {1169 struct FakeIm {
@@ -1158,16 +1208,25 @@ mod tests {
1158 let head = String::from_utf8_lossy(&req[..body_start]).to_string();1208 let head = String::from_utf8_lossy(&req[..body_start]).to_string();
1159 let first = head.lines().next().unwrap_or("").to_string();1209 let first = head.lines().next().unwrap_or("").to_string();
1160 let len = content_length(&head);1210 let len = content_length(&head);
1211+ let whole =
1212+ String::from_utf8_lossy(&req[..body_start + len]).to_string();
1161 req.drain(..body_start + len);1213 req.drain(..body_start + len);
1162- let payload = if first.starts_with("POST /token ") {1214+ let (status, payload) = if first.starts_with("POST /token ") {
1163- canned.token.get().cloned().unwrap_or_default()1215+ (200, canned.token.get().cloned().unwrap_or_default())
1164 } else if first.starts_with("GET /jwks.json ") {1216 } else if first.starts_with("GET /jwks.json ") {
1165- canned.jwks.get().cloned().unwrap_or_default()1217+ (200, canned.jwks.get().cloned().unwrap_or_default())
1218+ } else if first.starts_with("POST /family/register ") {
1219+ let _ = canned.register_seen.set(whole);
1220+ canned
1221+ .register
1222+ .get()
1223+ .cloned()
1224+ .unwrap_or((200, String::new()))
1166 } else {1225 } else {
1167- canned.introspect.get().cloned().unwrap_or_default()1226+ (200, canned.introspect.get().cloned().unwrap_or_default())
1168 };1227 };
1169 let response = format!(1228 let response = format!(
1170- "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: keep-alive\r\n\r\n",1229+ "HTTP/1.1 {status} answer\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: keep-alive\r\n\r\n",
1171 payload.len()1230 payload.len()
1172 );1231 );
1173 if socket.write_all(response.as_bytes()).await.is_err() {1232 if socket.write_all(response.as_bytes()).await.is_err() {
@@ -1473,4 +1532,74 @@ mod tests {
1473 res.set_cookies1532 res.set_cookies
1474 );1533 );
1475 }1534 }
1535+
1536+ /// The happy path, and the request im gets: the client pair as Basic
1537+ /// auth and the three fields under the registration route.
1538+ #[tokio::test]
1539+ async fn register_family_files_the_app_and_carries_the_client_pair() {
1540+ let canned = CannedIm::default();
1541+ let _ = canned.register.set((
1542+ 200,
1543+ serde_json::json!({"key": "iz", "name": "Board", "url": "https://iz.dizey.sh"})
1544+ .to_string(),
1545+ ));
1546+ let fake = FakeIm::spawn(canned.clone()).await;
1547+ let client = IzClient::new(test_config(fake.url()));
1548+ let filed = client
1549+ .register_family("iz", "Board", "https://iz.dizey.sh")
1550+ .await;
1551+ assert!(filed.is_ok(), "a 200 must read as filed: {filed:?}");
1552+ let seen = canned.register_seen.get().cloned().unwrap_or_default();
1553+ assert!(
1554+ seen.contains(&format!(
1555+ "Basic {}",
1556+ base64::engine::general_purpose::STANDARD.encode("client-1:s3cr3t")
1557+ )),
1558+ "the registration must carry the client pair: {seen}"
1559+ );
1560+ assert!(
1561+ seen.contains(r#""key":"iz""#)
1562+ && seen.contains(r#""name":"Board""#)
1563+ && seen.contains(r#""url":"https://iz.dizey.sh""#),
1564+ "the registration must carry key, name and url: {seen}"
1565+ );
1566+ }
1567+
1568+ /// Another app holds the key: the error names the status and im's word
1569+ /// for it, so the log line says which of the two it was.
1570+ #[tokio::test]
1571+ async fn register_family_reports_a_key_another_app_owns() {
1572+ let canned = CannedIm::default();
1573+ let _ = canned
1574+ .register
1575+ .set((409, serde_json::json!({"error": "owned"}).to_string()));
1576+ let fake = FakeIm::spawn(canned).await;
1577+ let client = IzClient::new(test_config(fake.url()));
1578+ let problem = client
1579+ .register_family("iz", "Board", "https://iz.dizey.sh")
1580+ .await
1581+ .expect_err("a 409 must not read as filed");
1582+ assert!(
1583+ problem.contains("409") && problem.contains("owned"),
1584+ "the refusal must name the status and im's word: {problem}"
1585+ );
1586+ }
1587+
1588+ /// An im too old to register answers 404. That is an `Err` like any
1589+ /// other — the caller logs it and goes on to the fetch.
1590+ #[tokio::test]
1591+ async fn register_family_reports_an_im_that_does_not_register_yet() {
1592+ let canned = CannedIm::default();
1593+ let _ = canned.register.set((404, "not found".into()));
1594+ let fake = FakeIm::spawn(canned).await;
1595+ let client = IzClient::new(test_config(fake.url()));
1596+ let problem = client
1597+ .register_family("iz", "Board", "https://iz.dizey.sh")
1598+ .await
1599+ .expect_err("a 404 must not read as filed");
1600+ assert!(
1601+ problem.contains("404"),
1602+ "the refusal names the status: {problem}"
1603+ );
1604+ }
1476 }1605 }
crates/iz-core/src/config.rsmodified+8 -4
@@ -55,8 +55,10 @@ storage = "storage"
55 listen = "127.0.0.1:7654"55 listen = "127.0.0.1:7654"
56 # This app's public address, when it differs from `listen` — a proxy in56 # This app's public address, when it differs from `listen` — a proxy in
57 # front, for instance. It is where a sign-out sends the browser back to,57 # front, for instance. It is where a sign-out sends the browser back to,
58-# so a deployment the family reaches by name sets it. Empty: derived58+# and the address İz files itself under in im's family list, as the key
59-# from `listen`.59+# "iz", so the family's switcher finds it without an admin typing it. A
60+# deployment the family reaches by name sets it. Empty: derived from
61+# `listen`.
60 base_url = ""62 base_url = ""
61 # How long a live-update connection is held before the browser is asked to63 # How long a live-update connection is held before the browser is asked to
62 # reconnect, in seconds. The reconnect is what re-checks the session, so a64 # reconnect, in seconds. The reconnect is what re-checks the session, so a
@@ -124,8 +126,10 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[
124 concat!(126 concat!(
125 "# This app's public address, when it differs from `listen` — a proxy\n",127 "# This app's public address, when it differs from `listen` — a proxy\n",
126 "# in front, for instance. It is where a sign-out sends the browser\n",128 "# in front, for instance. It is where a sign-out sends the browser\n",
127- "# back to, so a deployment the family reaches by name sets it.\n",129+ "# back to, and the address İz files itself under in im's family\n",
128- "# Empty: derived from `listen`.\n",130+ "# list, as the key \"iz\", so the family's switcher finds it without\n",
131+ "# an admin typing it. A deployment the family reaches by name sets\n",
132+ "# it. Empty: derived from `listen`.\n",
129 "base_url = \"\"\n"133 "base_url = \"\"\n"
130 ),134 ),
131 ),135 ),
crates/iz-web/src/main.rsmodified+33 -1
@@ -149,6 +149,7 @@ async fn main() {
149 tokio::spawn(directory_sync(149 tokio::spawn(directory_sync(
150 store.clone(),150 store.clone(),
151 iz_client::IzClient::new(oidc.clone()),151 iz_client::IzClient::new(oidc.clone()),
152+ config.public_url(),
152 ));153 ));
153 // Told when the process is stopping, so the live streams end instead of154 // Told when the process is stopping, so the live streams end instead of
154 // being waited out. See `iz_web::live::Shutdown`.155 // being waited out. See `iz_web::live::Shutdown`.
@@ -321,7 +322,15 @@ const DIRECTORY_SECONDS: u64 = 300;
321 /// hears one entry at a time and announces only what changed. An im that322 /// hears one entry at a time and announces only what changed. An im that
322 /// does not answer — down, restarting, mid-deploy — costs one log line323 /// does not answer — down, restarting, mid-deploy — costs one log line
323 /// and nothing else: the rows stay, and the next beat asks again.324 /// and nothing else: the rows stay, and the next beat asks again.
324-async fn directory_sync(store: Arc<dyn iz_core::store::Store>, client: iz_client::IzClient) {325+async fn directory_sync(
326+ store: Arc<dyn iz_core::store::Store>,
327+ client: iz_client::IzClient,
328+ configured_url: String,
329+) {
330+ // An address that never arrives would otherwise say so every beat,
331+ // five minutes apart, forever. It is one deployment fact, so it is
332+ // said once and the mirror goes on without it.
333+ let mut said_no_address = false;
325 loop {334 loop {
326 match client.directory().await {335 match client.directory().await {
327 Some(members) => {336 Some(members) => {
@@ -336,6 +345,29 @@ async fn directory_sync(store: Arc<dyn iz_core::store::Store>, client: iz_client
336 }345 }
337 None => eprintln!("directory sync: im did not answer; keeping the rows there are"),346 None => eprintln!("directory sync: im did not answer; keeping the rows there are"),
338 }347 }
348+ // Before asking for the family, this app files itself in it, so a
349+ // deployment appears in everyone's switcher without an admin
350+ // typing its address. Resolved per beat in the order a sign-out
351+ // resolves it — the stored public address an admin set wins over
352+ // the configured one — because both can change while the process
353+ // runs. Registration is announcement, not permission: a refusal,
354+ // an im too old to know the route, a dropped connection all cost
355+ // one line and the fetch below still runs.
356+ let origin = match store.get_setting(iz_web::server::PUBLIC_URL_KEY).await {
357+ Ok(Some(stored)) if !stored.trim().is_empty() => stored.trim().to_string(),
358+ _ => configured_url.trim().to_string(),
359+ };
360+ let origin = origin.trim_end_matches('/').to_string();
361+ if origin.is_empty() {
362+ if !said_no_address {
363+ said_no_address = true;
364+ eprintln!(
365+ "family: no public address to register; set base_url or the Server rail's public address"
366+ );
367+ }
368+ } else if let Err(problem) = client.register_family("iz", "Board", &origin).await {
369+ eprintln!("family register: {problem}");
370+ }
339 // The family rides the same beat: one JSON array in one setting371 // The family rides the same beat: one JSON array in one setting
340 // row, the same shape im's `/family` served this pass. `family`372 // row, the same shape im's `/family` served this pass. `family`
341 // refuses a body it cannot read whole rather than storing half a373 // refuses a body it cannot read whole rather than storing half a