forge
Explore
Log in

Don't you dare go Hollow

im_old

Clone
★ 0

0 watching0 forksRustGPL-3.0755.6 KiB84318dcTahinli2 months ago77 commits

services.rs738 lines, 26.4 KiBHistoryRawDownload
1//! The family: the services every topbar shows as wordmarks and the
2//! landing's services home. The list lives in the database, seeded once from
3//! the config's `[[services]]` on first boot and served to the sibling apps
4//! over `GET /family`, which each mirrors into its own database.
5//!
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.
11
12use serde::Serialize;
13
14use crate::store::{self, Result, Store, StoreError, backend};
15
16/// One service of the family: the wordmark `key` ("in", "im", "iz" — or a
17/// later sibling; the key rules are mechanical, not a fixed trio), the
18/// human `name`, and the absolute base `url` without a trailing slash.
19/// `position` is the stored order and never leaves this module — readers
20/// get the list already ordered.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
22pub struct Service {
23 pub key: String,
24 pub name: 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 /// public fields below, and the ownership stays im's business.
30 #[serde(skip)]
31 pub owner: Option<String>,
32 /// The relying-party credential this row answers for — the client id
33 /// `POST /family/register` authenticated, stamped on every register,
34 /// insert and refresh alike. im's own row stays `None`: the IdP is not
35 /// its own client. This is the panel's join key between the wordmark
36 /// and its Rotate/Revoke controls; a row the seed or the panel made
37 /// carries `None` until its app registers.
38 #[serde(skip)]
39 pub client_id: Option<String>,
40 /// The storage cap the panel holds this service to, in bytes — im's
41 /// field alone, never the keeping app's. Served to the family as
42 /// `limit_bytes` (JSON `null` when unstated, the sibling's own default
43 /// standing in its place); a register's refresh never touches it, the
44 /// way it never touches the name.
45 #[serde(rename = "limit_bytes")]
46 pub storage_limit_bytes: Option<u64>,
47}
48
49/// The owner im writes on its own row, registered from `issuer` on every
50/// boot — not a client id, because im is nobody's client.
51pub const SELF_OWNER: &str = "im";
52
53/// The form-level rules every stored row obeys: a key of lowercase ASCII
54/// letters, digits, and dashes; a non-empty name; an absolute http(s) URL.
55/// Returns the reason a value is refused — the panel shows it as its one
56/// generic refusal, the exact words stay a store matter.
57pub fn validate(key: &str, name: &str, url: &str) -> std::result::Result<(), String> {
58 if key.is_empty()
59 || !key
60 .chars()
61 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
62 {
63 return Err(format!(
64 "key {key:?} must be lowercase letters, digits, or dashes"
65 ));
66 }
67 if name.trim().is_empty() {
68 return Err("name must not be empty".to_string());
69 }
70 let trimmed = url.trim_end_matches('/');
71 let Some(rest) = trimmed
72 .strip_prefix("http://")
73 .or_else(|| trimmed.strip_prefix("https://"))
74 else {
75 return Err(format!("url {url:?} must be an http(s) URL"));
76 };
77 let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
78 if authority.is_empty() {
79 return Err(format!("url {url:?} must name a host"));
80 }
81 if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) {
82 return Err(format!(
83 "url {url:?} must not carry spaces or control characters"
84 ));
85 }
86 Ok(())
87}
88
89/// The one doorway every write passes: [`validate`], with the URL in its
90/// stored form — no trailing slash.
91fn checked(service: &Service) -> Result<String> {
92 validate(&service.key, &service.name, &service.url).map_err(StoreError::Invalid)?;
93 Ok(service.url.trim_end_matches('/').to_string())
94}
95
96/// Every service, in the stored order — the one order the trio, the landing
97/// cards, and `/family` all render in.
98pub async fn list(store: &Store) -> Result<Vec<Service>> {
99 let conn = store.conn.lock().await;
100 let mut rows = conn
101 .query(
102 "SELECT key, name, url, owner, client_id, storage_limit_bytes \
103 FROM services ORDER BY position, key",
104 (),
105 )
106 .await
107 .map_err(backend)?;
108 let mut services = Vec::new();
109 while let Some(row) = rows.next().await.map_err(backend)? {
110 services.push(Service {
111 key: store::text(&row, 0)?,
112 name: store::text(&row, 1)?,
113 url: store::text(&row, 2)?,
114 owner: store::opt_text(&row, 3)?,
115 client_id: store::opt_text(&row, 4)?,
116 storage_limit_bytes: store::opt_int(&row, 5)?.map(|bytes| bytes.max(0) as u64),
117 });
118 }
119 Ok(services)
120}
121
122/// Appends a service at the end of the family. A key already on the list is
123/// refused — the add form is the only writer, and a silent overwrite would
124/// surprise it.
125pub async fn add(store: &Store, service: &Service) -> Result<()> {
126 let url = checked(service)?;
127 let conn = store.conn.lock().await;
128 let mut rows = conn
129 .query(
130 "SELECT 1 FROM services WHERE key = ?1",
131 turso::params![service.key.as_str()],
132 )
133 .await
134 .map_err(backend)?;
135 let taken = rows.next().await.map_err(backend)?.is_some();
136 drop(rows);
137 if taken {
138 return Err(StoreError::Invalid(format!(
139 "service key {:?} is already on the list",
140 service.key
141 )));
142 }
143 conn.execute(
144 "INSERT INTO services (key, name, url, position, storage_limit_bytes) \
145 VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), -1) + 1 FROM services), ?4)",
146 turso::params![
147 service.key.as_str(),
148 service.name.trim(),
149 url.as_str(),
150 service.storage_limit_bytes.map(|bytes| bytes as i64)
151 ],
152 )
153 .await
154 .map_err(backend)?;
155 Ok(())
156}
157
158/// Rewrites a service's name, address, and storage limit. The key travels
159/// in the form's hidden field and is not editable; a key not on the list is
160/// refused, so a form posted against a since-removed row cannot resurrect
161/// it. A row an app keeps only takes its new name here: the address is the
162/// app's own, rewritten on its every boot, so accepting one from the panel
163/// would show an edit the next boot silently undoes. The limit is im's on
164/// every row — kept or not, an empty field clears it to no limit stated.
165pub async fn edit(
166 store: &Store,
167 key: &str,
168 name: &str,
169 url: &str,
170 storage_limit_bytes: Option<u64>,
171) -> Result<()> {
172 validate(key, name, url).map_err(StoreError::Invalid)?;
173 let url = url.trim_end_matches('/');
174 if let Some(row) = owned_row(store, key).await?
175 && row.1.is_some()
176 && row.0 != url
177 {
178 return Err(StoreError::Invalid(format!(
179 "service {key:?} keeps its own address; its app re-registers it on every boot"
180 )));
181 }
182 let conn = store.conn.lock().await;
183 let updated = conn
184 .execute(
185 "UPDATE services SET name = ?2, url = ?3, storage_limit_bytes = ?4 WHERE key = ?1",
186 turso::params![
187 key,
188 name.trim(),
189 url,
190 storage_limit_bytes.map(|bytes| bytes as i64)
191 ],
192 )
193 .await
194 .map_err(backend)?;
195 if updated == 0 {
196 return Err(StoreError::Invalid(format!("no service keyed {key:?}")));
197 }
198 Ok(())
199}
200
201/// Takes a service off the list and closes the gap: every later row slides
202/// down one, so positions stay contiguous and the next add appends cleanly.
203/// A key not on the list is a no-op — the panel only offers existing rows.
204/// A row an app keeps is not the panel's to take: it would come back on the
205/// app's next boot.
206pub async fn remove(store: &Store, key: &str) -> Result<()> {
207 if let Some((_, Some(_))) = owned_row(store, key).await? {
208 return Err(StoreError::Invalid(format!(
209 "service {key:?} is kept by its app; it re-registers on every boot"
210 )));
211 }
212 let conn = store.conn.lock().await;
213 let mut rows = conn
214 .query(
215 "SELECT position FROM services WHERE key = ?1",
216 turso::params![key],
217 )
218 .await
219 .map_err(backend)?;
220 let Some(row) = rows.next().await.map_err(backend)? else {
221 return Ok(());
222 };
223 let position = store::int(&row, 0)?;
224 drop(rows);
225 conn.execute("DELETE FROM services WHERE key = ?1", turso::params![key])
226 .await
227 .map_err(backend)?;
228 conn.execute(
229 "UPDATE services SET position = position - 1 WHERE position > ?1",
230 turso::params![position],
231 )
232 .await
233 .map_err(backend)?;
234 Ok(())
235}
236
237/// Swaps a service one slot toward the front (`up`) or the back. An edge
238/// row has no neighbor in that direction and the list is left alone.
239pub async fn move_service(store: &Store, key: &str, up: bool) -> Result<()> {
240 let conn = store.conn.lock().await;
241 let mut rows = conn
242 .query(
243 "SELECT position FROM services WHERE key = ?1",
244 turso::params![key],
245 )
246 .await
247 .map_err(backend)?;
248 let Some(row) = rows.next().await.map_err(backend)? else {
249 return Ok(());
250 };
251 let position = store::int(&row, 0)?;
252 drop(rows);
253 let mut neighbor = if up {
254 conn.query(
255 "SELECT key, position FROM services WHERE position < ?1 \
256 ORDER BY position DESC LIMIT 1",
257 turso::params![position],
258 )
259 .await
260 .map_err(backend)?
261 } else {
262 conn.query(
263 "SELECT key, position FROM services WHERE position > ?1 \
264 ORDER BY position ASC LIMIT 1",
265 turso::params![position],
266 )
267 .await
268 .map_err(backend)?
269 };
270 let Some(row) = neighbor.next().await.map_err(backend)? else {
271 return Ok(());
272 };
273 let other_key = store::text(&row, 0)?;
274 let other_position = store::int(&row, 1)?;
275 drop(neighbor);
276 conn.execute(
277 "UPDATE services SET position = ?1 WHERE key = ?2",
278 turso::params![other_position, key],
279 )
280 .await
281 .map_err(backend)?;
282 conn.execute(
283 "UPDATE services SET position = ?1 WHERE key = ?2",
284 turso::params![position, other_key],
285 )
286 .await
287 .map_err(backend)?;
288 Ok(())
289}
290
291/// A row's stored `(url, owner)`, or `None` when no row carries the key.
292async fn owned_row(store: &Store, key: &str) -> Result<Option<(String, Option<String>)>> {
293 let conn = store.conn.lock().await;
294 let mut rows = conn
295 .query(
296 "SELECT url, owner FROM services WHERE key = ?1",
297 turso::params![key],
298 )
299 .await
300 .map_err(backend)?;
301 let Some(row) = rows.next().await.map_err(backend)? else {
302 return Ok(None);
303 };
304 Ok(Some((store::text(&row, 0)?, store::opt_text(&row, 1)?)))
305}
306
307/// An app writing its own row: im from its `issuer` on every boot, a sibling
308/// over `POST /family/register` with its client id as the `owner`. A key
309/// nobody holds is appended (or claimed, keeping the name the seed or the
310/// panel gave it); a key the caller already holds takes the new address
311/// only — the name is the admin's after the first insert. A key another app
312/// keeps is a conflict, never a takeover.
313pub async fn register(
314 store: &Store,
315 key: &str,
316 name: &str,
317 url: &str,
318 owner: &str,
319 client_id: Option<&str>,
320) -> Result<Service> {
321 validate(key, name, url).map_err(StoreError::Invalid)?;
322 let url = url.trim_end_matches('/').to_string();
323 match owned_row(store, key).await? {
324 Some((_, Some(held))) if held != owner => {
325 return Err(StoreError::Conflict(format!(
326 "service key {key:?} belongs to another app"
327 )));
328 }
329 Some(_) => {
330 // Claiming an unowned row or refreshing our own: the address is
331 // the app's to say, the name stays whatever is stored, and the
332 // credential stamp follows the caller on every register.
333 let conn = store.conn.lock().await;
334 conn.execute(
335 "UPDATE services SET url = ?2, owner = ?3, client_id = ?4 WHERE key = ?1",
336 turso::params![key, url.as_str(), owner, client_id],
337 )
338 .await
339 .map_err(backend)?;
340 }
341 None => {
342 let conn = store.conn.lock().await;
343 conn.execute(
344 "INSERT INTO services (key, name, url, position, owner, client_id) \
345 VALUES (?1, ?2, ?3, (SELECT COALESCE(MAX(position), -1) + 1 FROM services), ?4, ?5)",
346 turso::params![key, name.trim(), url.as_str(), owner, client_id],
347 )
348 .await
349 .map_err(backend)?;
350 }
351 }
352 let row = list(store)
353 .await?
354 .into_iter()
355 .find(|service| service.key == key)
356 .ok_or_else(|| StoreError::Backend(format!("service {key:?} vanished after its write")))?;
357 Ok(row)
358}
359
360/// The one-time seed: a database with no services yet takes the config's
361/// list as the starting rows, in the order the file names them. After that
362/// the panel owns the list and the same config is ignored — the `false`
363/// return tells the boot it did nothing.
364pub async fn seed_from(store: &Store, seed: &[Service]) -> Result<bool> {
365 if !list(store).await?.is_empty() {
366 return Ok(false);
367 }
368 let conn = store.conn.lock().await;
369 for (position, service) in seed.iter().enumerate() {
370 let url = checked(service)?;
371 conn.execute(
372 "INSERT OR IGNORE INTO services (key, name, url, position) \
373 VALUES (?1, ?2, ?3, ?4)",
374 turso::params![
375 service.key.as_str(),
376 service.name.trim(),
377 url.as_str(),
378 position as i64
379 ],
380 )
381 .await
382 .map_err(backend)?;
383 }
384 Ok(true)
385}
386
387#[cfg(test)]
388mod tests {
389 use std::path::Path;
390
391 use super::*;
392 use crate::store::StoreError;
393
394 async fn store() -> Store {
395 Store::open(Path::new(":memory:")).await.unwrap()
396 }
397
398 fn service(key: &str, name: &str, url: &str) -> Service {
399 Service {
400 key: key.to_string(),
401 name: name.to_string(),
402 url: url.to_string(),
403 owner: None,
404 client_id: None,
405 storage_limit_bytes: None,
406 }
407 }
408
409 async fn keys(store: &Store) -> Vec<String> {
410 list(store)
411 .await
412 .unwrap()
413 .into_iter()
414 .map(|s| s.key)
415 .collect()
416 }
417
418 #[tokio::test]
419 async fn the_seed_fills_an_empty_table_once_and_then_hands_over() {
420 let store = store().await;
421 let seed = vec![
422 service("in", "Files", "http://127.0.0.1:7655/"),
423 service("im", "Account", "http://127.0.0.1:7650"),
424 ];
425 assert!(seed_from(&store, &seed).await.unwrap());
426 // A trailing slash in the file is not in the table: the stored form
427 // is slash-free, everywhere.
428 assert_eq!(list(&store).await.unwrap()[0].url, "http://127.0.0.1:7655");
429 // The panel renamed the first entry; a re-boot with the same config
430 // must not bring the old name back.
431 edit(&store, "in", "Renamed", "http://127.0.0.1:7655", None)
432 .await
433 .unwrap();
434 assert!(!seed_from(&store, &seed).await.unwrap());
435 assert_eq!(list(&store).await.unwrap()[0].name, "Renamed");
436 }
437
438 #[tokio::test]
439 async fn add_appends_edit_rewrites_and_a_taken_key_is_refused() {
440 let store = store().await;
441 seed_from(&store, &[service("im", "Account", "http://127.0.0.1:7650")])
442 .await
443 .unwrap();
444 add(&store, &service("in", "Files", "http://127.0.0.1:7655"))
445 .await
446 .unwrap();
447 add(&store, &service("in", "Again", "http://elsewhere/"))
448 .await
449 .err()
450 .unwrap_or_else(|| panic!("a taken key must be refused"));
451 // The refused add changed nothing.
452 assert_eq!(keys(&store).await, vec!["im".to_string(), "in".to_string()]);
453 edit(&store, "in", "Dosyalar", "https://in.example", None)
454 .await
455 .unwrap();
456 let services = list(&store).await.unwrap();
457 assert_eq!(services[1].name, "Dosyalar");
458 assert_eq!(services[1].url, "https://in.example");
459 // A form posted against a since-removed key cannot resurrect it.
460 remove(&store, "in").await.unwrap();
461 assert!(matches!(
462 edit(&store, "in", "Zombie", "https://in.example", None).await,
463 Err(StoreError::Invalid(_))
464 ));
465 assert_eq!(keys(&store).await, vec!["im".to_string()]);
466 }
467
468 #[tokio::test]
469 async fn moving_swaps_with_the_neighbor_and_edges_stay_put() {
470 let store = store().await;
471 seed_from(
472 &store,
473 &[
474 service("in", "Files", "http://127.0.0.1:7655"),
475 service("im", "Account", "http://127.0.0.1:7650"),
476 service("iz", "Board", "http://127.0.0.1:7654"),
477 ],
478 )
479 .await
480 .unwrap();
481 move_service(&store, "iz", true).await.unwrap();
482 assert_eq!(
483 keys(&store).await,
484 vec!["in".to_string(), "iz".to_string(), "im".to_string()]
485 );
486 // The front edge has nothing above it; the list does not move.
487 move_service(&store, "in", true).await.unwrap();
488 assert_eq!(
489 keys(&store).await,
490 vec!["in".to_string(), "iz".to_string(), "im".to_string()]
491 );
492 move_service(&store, "in", false).await.unwrap();
493 assert_eq!(
494 keys(&store).await,
495 vec!["iz".to_string(), "in".to_string(), "im".to_string()]
496 );
497 }
498
499 #[tokio::test]
500 async fn removing_closes_the_gap_so_the_next_add_appends_last() {
501 let store = store().await;
502 seed_from(
503 &store,
504 &[
505 service("in", "Files", "http://127.0.0.1:7655"),
506 service("im", "Account", "http://127.0.0.1:7650"),
507 service("iz", "Board", "http://127.0.0.1:7654"),
508 ],
509 )
510 .await
511 .unwrap();
512 remove(&store, "im").await.unwrap();
513 remove(&store, "im").await.unwrap(); // already gone: a no-op
514 add(&store, &service("wiki", "Wiki", "http://wiki"))
515 .await
516 .unwrap();
517 assert_eq!(
518 keys(&store).await,
519 vec!["in".to_string(), "iz".to_string(), "wiki".to_string()]
520 );
521 }
522
523 #[tokio::test]
524 async fn the_value_rules_refuse_garbage_before_the_database_sees_it() {
525 assert!(validate("in", "Files", "http://in.example").is_ok());
526 assert!(
527 validate("In", "Files", "http://in.example").is_err(),
528 "uppercase key"
529 );
530 assert!(
531 validate("in!", "Files", "http://in.example").is_err(),
532 "punctuated key"
533 );
534 assert!(
535 validate("in", " ", "http://in.example").is_err(),
536 "blank name"
537 );
538 assert!(
539 validate("in", "Files", "ftp://in.example").is_err(),
540 "non-http url"
541 );
542 assert!(validate("in", "Files", "http://").is_err(), "hostless url");
543 assert!(
544 validate("in", "Files", "http://in.example/path x").is_err(),
545 "space in url"
546 );
547 // A trailing slash is not garbage — it is normalized away.
548 assert!(validate("in", "Files", "http://in.example/").is_ok());
549 }
550
551 #[tokio::test]
552 async fn an_app_registers_itself_appending_then_claiming_then_refreshing() {
553 let store = store().await;
554 // Nothing on the list yet: the app's own row is appended.
555 let row = register(
556 &store,
557 "im",
558 "Account",
559 "http://127.0.0.1:7650/",
560 SELF_OWNER,
561 None,
562 )
563 .await
564 .unwrap();
565 assert_eq!(
566 row.url, "http://127.0.0.1:7650",
567 "the slash is normalized off"
568 );
569 assert_eq!(row.owner.as_deref(), Some(SELF_OWNER));
570 assert_eq!(row.client_id, None, "im is not its own client");
571
572 // A seeded row belongs to nobody; the app that names it claims it,
573 // keeping the name the seed (or a later rename) gave it.
574 add(&store, &service("in", "Dosyalar", "http://127.0.0.1:7655"))
575 .await
576 .unwrap();
577 let row = register(&store, "in", "Files", "https://in.example", "in-client", Some("in-client"))
578 .await
579 .unwrap();
580 assert_eq!(row.name, "Dosyalar", "the name stays the admin's");
581 assert_eq!(row.url, "https://in.example");
582 assert_eq!(row.owner.as_deref(), Some("in-client"));
583 assert_eq!(
584 row.client_id.as_deref(),
585 Some("in-client"),
586 "the claim stamps the credential"
587 );
588
589 // The same app's next boot moves the address only.
590 let row = register(&store, "in", "Whatever", "https://in.dizey.sh", "in-client", Some("in-client"))
591 .await
592 .unwrap();
593 assert_eq!(row.name, "Dosyalar");
594 assert_eq!(row.url, "https://in.dizey.sh");
595 assert_eq!(
596 row.client_id.as_deref(),
597 Some("in-client"),
598 "the refresh keeps the stamp current"
599 );
600 // And no row was duplicated by any of it.
601 assert_eq!(keys(&store).await, vec!["im".to_string(), "in".to_string()]);
602 }
603
604 #[tokio::test]
605 async fn a_key_another_app_keeps_is_a_conflict_and_the_row_is_untouched() {
606 let store = store().await;
607 register(&store, "in", "Files", "https://in.example", "in-client", Some("in-client"))
608 .await
609 .unwrap();
610 assert!(matches!(
611 register(&store, "in", "Files", "https://evil.example", "iz-client", None).await,
612 Err(StoreError::Conflict(_))
613 ));
614 assert_eq!(list(&store).await.unwrap()[0].url, "https://in.example");
615 }
616
617 #[tokio::test]
618 async fn the_panel_cannot_remove_an_owned_row_or_move_its_address() {
619 let store = store().await;
620 register(&store, "in", "Files", "https://in.example", "in-client", Some("in-client"))
621 .await
622 .unwrap();
623 assert!(matches!(
624 remove(&store, "in").await,
625 Err(StoreError::Invalid(_))
626 ));
627 assert!(matches!(
628 edit(&store, "in", "Dosyalar", "https://elsewhere.example", None).await,
629 Err(StoreError::Invalid(_))
630 ));
631 // The name is still the admin's, and a name-only edit lands.
632 edit(&store, "in", "Dosyalar", "https://in.example", None)
633 .await
634 .unwrap();
635 let row = &list(&store).await.unwrap()[0];
636 assert_eq!(row.name, "Dosyalar");
637 assert_eq!(row.url, "https://in.example");
638 // An unowned row is still the panel's to take.
639 add(&store, &service("wiki", "Wiki", "http://wiki"))
640 .await
641 .unwrap();
642 remove(&store, "wiki").await.unwrap();
643 assert_eq!(keys(&store).await, vec!["in".to_string()]);
644 }
645
646 #[tokio::test]
647 async fn the_family_json_carries_the_limit_and_never_the_owner() {
648 let store = store().await;
649 register(&store, "im", "Account", "http://127.0.0.1:7650", SELF_OWNER, None)
650 .await
651 .unwrap();
652 let json = serde_json::to_value(list(&store).await.unwrap()).unwrap();
653 let row = &json.as_array().unwrap()[0];
654 let mut keys: Vec<String> = row.as_object().unwrap().keys().cloned().collect();
655 keys.sort();
656 assert_eq!(
657 keys,
658 vec!["key", "limit_bytes", "name", "url"],
659 "the sibling mirrors deserialize this shape: {json}"
660 );
661 assert!(
662 row["limit_bytes"].is_null(),
663 "no stated limit reads null, not absence"
664 );
665 // A stated limit rides as plain bytes; the owner never travels.
666 edit(
667 &store,
668 "im",
669 "Account",
670 "http://127.0.0.1:7650",
671 Some(512 * 1024 * 1024),
672 )
673 .await
674 .unwrap();
675 let json = serde_json::to_value(list(&store).await.unwrap()).unwrap();
676 assert_eq!(
677 json[0]["limit_bytes"],
678 serde_json::json!(512 * 1024 * 1024)
679 );
680 assert!(json[0].get("owner").is_none());
681 assert!(json[0].get("client_id").is_none());
682 }
683
684 #[tokio::test]
685 async fn the_storage_limit_round_trips_and_survives_a_register() {
686 let store = store().await;
687 add(
688 &store,
689 &Service {
690 storage_limit_bytes: Some(512 * 1024 * 1024),
691 ..service("in", "Files", "http://127.0.0.1:7655")
692 },
693 )
694 .await
695 .unwrap();
696 assert_eq!(
697 list(&store).await.unwrap()[0].storage_limit_bytes,
698 Some(512 * 1024 * 1024),
699 "add carries the stated limit in"
700 );
701 // The edit rewrites the limit; the row holds plain bytes.
702 edit(
703 &store,
704 "in",
705 "Files",
706 "http://127.0.0.1:7655",
707 Some(2 * 1024 * 1024 * 1024),
708 )
709 .await
710 .unwrap();
711 assert_eq!(
712 list(&store).await.unwrap()[0].storage_limit_bytes,
713 Some(2 * 1024 * 1024 * 1024)
714 );
715 // A kept row: the app re-registers, the limit stays im's — the
716 // refresh rewrites the address and credential, never the cap.
717 register(
718 &store,
719 "in",
720 "Files",
721 "http://127.0.0.1:7655",
722 "in-client",
723 Some("in-client"),
724 )
725 .await
726 .unwrap();
727 assert_eq!(
728 list(&store).await.unwrap()[0].storage_limit_bytes,
729 Some(2 * 1024 * 1024 * 1024),
730 "the app's register never touches the limit"
731 );
732 // The field empties to cleared: NULL is no limit stated.
733 edit(&store, "in", "Files", "http://127.0.0.1:7655", None)
734 .await
735 .unwrap();
736 assert_eq!(list(&store).await.unwrap()[0].storage_limit_bytes, None);
737 }
738}