//! The phone's [`ServerFetch`]: one signed request, with the clock correction //! and the terminal notes already applied. //! //! The port of `apps/cotton/src/replica/serverTransport.ts`. Everything above //! this file — the sync cycle, the join flow, the snapshot download, the live //! channel — asks for a path and gets an answer; the credential, the address //! and the four refusals that stop the loop are all here and none of them is //! visible up there. //! //! ## The ladder, in the order it runs //! //! 1. **No address** ⇒ `no_server`. There is no default and there never was: a //! phone learns a server by joining one. //! 2. **A clock hold on this origin** ⇒ refused locally, `device_clock`, //! nothing recorded (re-arming a hold from inside the hold would make it //! permanent). //! 3. **A standing TERMINAL refusal** ⇒ refused without sending, unless this //! is a pairing route (pairing is how a refused device gets back in, so it //! goes out) — or the note is not about the machine answering now. A note //! belongs to the MACHINE that said it ([`Refuser`]), and the name can move: //! the gate asks the origin `GET /health` who answers it, at most once a //! minute, and a DIFFERENT machine gets ONE fresh attempt. So does a note an //! older build wrote, which recorded no machine at all. The same machine //! gets the same verdict without being asked again. //! 4. Sign, send, and on a 2xx clear this origin's hold and any clock note — //! and, when the request went out as a fresh attempt past a terminal note, //! that note too: the machine answering the name now admits this device. //! 5. **`426`** ⇒ `upgrade_required`, by STATUS — whatever code the body //! carried. It is surfaced, never silently retried. //! 6. **`403 device_clock`, first time in a chain** ⇒ adopt the server's clock //! from `serverTime` (or the `Date` header) and retry once. A second, or a //! first with no readable clock, holds this origin for a minute. //! 7. **Every `403`, and an OWNER-route `401 device_bad_signature`**, goes //! through the recorder. An unclassified code records nothing. //! //! ## Every note is about one database //! //! A request that names a database other than Mine (`database=`) is //! gated on, and files its refusal under, THAT database's note ([`NoteKey`]). //! A place's refusal stops that place and leaves Mine syncing; Mine's //! terminal note stops every request. Only an answer about Mine may ask this //! device to erase itself. //! //! ## What never happens here //! //! **No `Authorization` header, ever.** The GoTrue bearer went with pairing PR //! 6; the device signature is the whole credential. `no_bearer_tests.rs` reads //! this module's own source for the word. use std::sync::Arc; use std::time::Duration; use cotton_core::device::server_id::SERVER_ID_HEADER; use crate::seams::Clock; use super::address::is_pairing_route; use super::refusal::{ DeviceRefusal, NoteKey, RefusalKind, RefusalMemory, Refuser, CLOCK_HOLD_MS, }; use super::signer::{RequestSigner, SignRequest}; use super::wire::Origin; use super::{ Answer, ClientAnswer, ClientRequest, Exchange, RefusalAware, ServerFetch, ServerRefusal, REQUEST_CEILING_MS, }; /// The most an ORDINARY answer may be before it is not an answer to one of /// these routes. /// /// Thirty-two megabytes: the biggest thing that comes back through /// [`ServerFetch`] is a pull page of a thousand ops, and the push body's own /// ceiling on the server is the same number. A whole file never comes through /// here: it is streamed to disk, the rule build 106 cost 464 MB and a white /// screen to learn. pub const ANSWER_CEILING_BYTES: usize = 32 * 1024 * 1024; /// How much of a refusal body is read before it is parsed. /// /// Four hundred characters, which is the phone's own number and is kept /// deliberately: a refusal envelope is `{error, code}` and a hundred bytes, /// and a body longer than this is a captive portal or a proxy's HTML. Reading /// it whole to look for a `code` would be reading somebody else's page into /// memory to be disappointed by it. pub const REFUSAL_BODY_MAX: usize = 400; /// Where the gate asks an origin which machine answers it: the one route that /// needs no signature and touches nothing. pub const ANSWERER_PROBE_PATH: &str = "/health"; /// How long that question may take. Ten seconds: an answer to it is optional — /// a name that does not answer quickly is a name the owner request would not /// have reached either — and the gate is in front of a caller that is waiting. pub const ANSWERER_PROBE_CEILING_MS: u64 = 10_000; /// How a request got past the gate. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Passage { /// Nothing stood in its way — no terminal note, or a pairing route. Open, /// A terminal note stands, and this is the ONE fresh attempt past it: the /// name is answered by a different machine than the one that said it, or /// the note is an older build's and recorded no machine. Its answer clears /// the note (a 2xx) or replaces it (a refusal). Fresh, } /// Whether the gate may let a request out as a fresh attempt at all. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Retry { /// An ordinary request: the loop's, a pull, a push. Allowed, /// The live socket's upgrade headers. The socket's answer never comes back /// through [`SignedHttp::attempt_once`], so nothing could clear or replace /// the note on the strength of it — the sync loop's own attempt does that. Never, } /// Where the address comes from. /// /// A seam rather than a field, because "which server this device talks to" has /// ONE owner (`client/connection.json`) and this module must not become a /// second. A test drives an in-memory one. pub trait ServerAddress: Send + Sync + std::fmt::Debug { /// The origin this device talks to, or `None` for a device that has not /// joined one. fn base_url(&self) -> Option; /// MINE's id — the person's own database — when this address knows it. /// /// A request naming this id is about Mine, like one naming none. `None` /// (an address that knows no database) files every request that names /// one under that database alone. fn mine_id(&self) -> Option { None } /// The database this device's requests act on — the workspace id it joined /// — or `None` for a device that has joined none. /// /// Asked beside [`Self::base_url`] on every signed request, because the /// server opens the one file a request NAMES /// (`cotton_core::device::database`) and the same seam that knows which /// server knows which database there. fn database(&self) -> Option; } /// The signed transport. /// The way a request reached the Mac — what "Last synced" on a device's own /// page says beside the time. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Way { /// The address the household is reached at, which is not the relay. Address, /// Through the relay. Relay, } impl Way { /// The way, as a person reads it. pub fn words(self) -> &'static str { match self { Way::Address => "directly", Way::Relay => "over the relay", } } /// The way a request to the household's own origin went: the relay when /// that origin is a relay name, else the address itself. pub fn to_origin(base_url: Option<&str>) -> Way { let host = base_url .and_then(|origin| origin.split("://").nth(1)) .and_then(|rest| rest.split(['/', ':']).next()); match host { Some(host) if cotton_core::device::pairing::is_relay_host(host) => Way::Relay, _ => Way::Address, } } } pub struct SignedHttp { signer: RequestSigner, removals: Option>, address: Arc, refusals: Arc, exchange: Arc, clock: Arc, ceiling: Duration, /// What this device says it IS — `"/"`, the value of /// [`cotton_core::device::signature::DEVICE_APP_HEADER`]. `None` on a build that does not know its own /// version, and then no header is sent at all rather than an empty one. /// /// It is set ONCE, at construction, because it is a fact about the binary /// that is running: a build cannot change version without the process /// ending. device_app: Option, /// The refusal behind the last failure, for `RefusalAware`. last: std::sync::Mutex>, /// The way the last request the Mac ANSWERED went ([`Self::last_way`]). last_way: std::sync::Mutex>, /// **WHICH APP THIS DEVICE IS** — `cotton_core::flavor::current()` when /// the transport is made. `Some` puts every origin through /// [`Self::confirm_app`] before the first request this device signs to /// it; `None` (a process that declared nothing — a unit test) has no rule. app: Option, /// The origins [`Self::confirm_app`] has found to be this app's, so each /// is asked once per process. A refusal is never remembered here: it is /// asked again next time, and refused again. confirmed: std::sync::Mutex>, /// **THE ONE MAC THIS TRANSPORT TALKS TO** — its `x-cotton-server` tag, /// for a database joined at another person's Mac /// (`crate::connection::joined`). `Some` puts every origin through /// [`Self::confirm_pin`] before the first request signed to it, and every /// answer through the same comparison before anything in it is read or /// recorded. `None` — the household's own transport — has no pin: which of /// its Macs answers is runtime. pinned: Option, /// The origins [`Self::confirm_pin`] found answered by the pinned Mac. /// An answer from any other Mac takes the origin out again. pin_confirmed: std::sync::Mutex>, /// RECORDS BEFORE BYTES ([`super::records_first`]): raised by every sync /// read this transport sends, read by every media fetch over it. records: Arc, } /// The code a request carries when the Mac answering is not the one this /// transport is pinned to. Status `0`: nothing was signed to it, or nothing /// in its answer was taken, and nothing is recorded as a refusal. pub const OTHER_SERVER: &str = "other_server"; /// The code a request refused by [`SignedHttp::confirm_app`] carries. pub const OTHER_APP: &str = "other_app"; /// A signed request for another sender: where it goes and what it carries. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HandedOver { /// The origin and the signed path — scheme, host, path and query. pub url: String, pub headers: Vec<(String, String)>, /// The server's idea of now when it was signed (this device's clock plus /// the origin's correction) — the start of its life. pub signed_at_ms: i64, } impl std::fmt::Debug for SignedHttp { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SignedHttp") .field("address", &self.address.base_url()) .finish_non_exhaustive() } } impl SignedHttp { /// One independent command-line client, using the same signer, socket /// exchange, clock/refusal handling and records gate as the app transport. /// A caller with an existing transport must share that transport instead. pub fn standalone( device: Arc, address: Arc, ) -> Self { let clock = Arc::new(crate::seams::SystemClock); Self::new( RequestSigner::new(device, clock.clone(), Arc::new(crate::seams::SystemRandom)), address, Arc::new(RefusalMemory::default()), Arc::new(super::SocketExchange), clock, ) } pub fn new( signer: RequestSigner, address: Arc, refusals: Arc, exchange: Arc, clock: Arc, ) -> SignedHttp { SignedHttp { signer, removals: None, address, refusals, exchange, clock, ceiling: Duration::from_millis(REQUEST_CEILING_MS), device_app: None, last: std::sync::Mutex::new(None), last_way: std::sync::Mutex::new(None), app: cotton_core::flavor::current(), confirmed: std::sync::Mutex::new(std::collections::HashSet::new()), pinned: None, pin_confirmed: std::sync::Mutex::new(std::collections::HashSet::new()), records: Arc::default(), } } /// The records-first gate every request of this transport meets at. /// THE SAME TRANSPORT, ADDRESSED TO ANOTHER PERSON'S MAC: this device's /// signer, the one socket layer and the ONE records-first gate, with that /// Mac's address, its own refusal memory and its pin. A joined database's /// line is never a second transport — its reads and the household's /// share one gate, so a read on either cancels every media fetch on both /// (architect, 13 Oct 2026: one transport on the phone for every byte). #[must_use] pub fn to_another_mac( &self, address: Arc, refusals: Arc, server_device_id: &str, ) -> SignedHttp { let mut line = SignedHttp::new( self.signer.clone(), address, refusals, Arc::clone(&self.exchange), Arc::clone(&self.clock), ) .pinned_to(server_device_id); line.ceiling = self.ceiling; line.device_app.clone_from(&self.device_app); line.app = self.app; line.records = Arc::clone(&self.records); line.removals.clone_from(&self.removals); line } pub fn records_gate(&self) -> &Arc { &self.records } /// Talk to ONE Mac only: the one whose device id is `server_device_id`. /// /// The comparison is of `x-cotton-server` tags /// (`cotton_core::device::server_id`), which every answer carries and /// `GET /health` carries unsigned. It is what tells one Mac behind a name /// from another; it is not a proof of the Mac's key. #[must_use] pub fn pinned_to(mut self, server_device_id: &str) -> SignedHttp { self.pinned = Some(cotton_core::device::server_id::server_id_of(server_device_id)); self } /// The origin this transport's own address names, if it names one. pub fn origin(&self) -> Option { self.address.base_url() } /// **IS THE MAC AT THIS ORIGIN THE PINNED ONE?** Asked before the first /// request this device signs there — unsigned, of `GET /health` — so a /// name that another Mac answers is sent nothing: no queued write, no /// signature. An origin that does not answer is offline, not another Mac. fn confirm_pin(&self, origin: &Origin) -> Result<(), ServerRefusal> { let Some(pinned) = &self.pinned else { return Ok(()); }; if self .pin_confirmed .lock() .unwrap_or_else(|e| e.into_inner()) .contains(&origin.text) { return Ok(()); } let authority = origin.authority(); let wire = super::http1::Http1Request { method: "GET", path: ANSWERER_PROBE_PATH, authority: &authority, headers: Vec::new(), body: None, }; let ceiling = self .ceiling .min(Duration::from_millis(ANSWERER_PROBE_CEILING_MS)); let answer = self .exchange .send(origin, &wire, ceiling) .map_err(ServerRefusal::offline)?; self.pinned_answer(origin, pinned, answer.header(SERVER_ID_HEADER).as_deref())?; self.pin_confirmed .lock() .unwrap_or_else(|e| e.into_inner()) .insert(origin.text.clone()); Ok(()) } /// One answer's tag against the pin. A Mac that names another machine, or /// names none, is not the pinned one. fn pinned_answer( &self, origin: &Origin, pinned: &str, tag: Option<&str>, ) -> Result<(), ServerRefusal> { if tag.map(str::trim) == Some(pinned) { return Ok(()); } self.pin_confirmed .lock() .unwrap_or_else(|e| e.into_inner()) .remove(&origin.text); Err(ServerRefusal::offline(format!( "{} is not answered by the Mac this database was joined at — nothing was sent to it", origin.text )) .with_code(OTHER_SERVER)) } /// Be the app `app`, whatever this process declared — for a test that /// drives the rule in a process that declares nothing. #[must_use] pub fn as_app(mut self, app: Option) -> SignedHttp { self.app = app; self } /// Say what this device is on every request it signs — the platform and the /// running app's version, as `"/"`. /// /// A builder rather than a sixth constructor argument: the facts are the /// embedder's (only the app knows its own version) and every test that /// builds a transport to exercise the ladder has nothing to say here. A /// blank or version-less value is dropped rather than sent, so a caller /// that does not know cannot claim to. #[must_use] pub fn describing(mut self, platform: &str, app_version: Option<&str>) -> SignedHttp { let version = app_version.map(str::trim).filter(|value| !value.is_empty()); self.device_app = match (platform.trim(), version) { ("", _) | (_, None) => None, (platform, Some(version)) => Some(format!("{platform}/{version}")), }; self } pub fn refusals(&self) -> &Arc { &self.refusals } pub fn device_id(&self) -> String { self.signer.device_id() } /// The socket URL to dial and the two headers its upgrade carries. /// /// The same signature as a `GET /v1/live`: an empty nonce, an empty body, /// and the origin the socket is dialling. The CREDENTIAL is in headers, /// never a query string — a credential in a URL lands in the reverse /// proxy's access log. The DATABASE is in the query, like every other /// signed request's, which is why the URL comes back: the one dialled has /// to be the one signed. pub fn upgrade_headers( &self, url: &str, ) -> Result<(String, Vec<(String, String)>), ServerRefusal> { let origin = self.origin_for(None)?; self.confirm_app(&origin)?; self.confirm_pin(&origin)?; let url = self.naming_database(url); let path = cotton_core::device::signature::signed_path(&url).map_err(|_| { ServerRefusal::offline(format!("{url} is not an address")).with_code("no_server") })?; // The socket is Mine's: Mine's note decides whether this device may // open one at all. self.gate(&origin, &path, &NoteKey::Mine, Retry::Never)?; let headers = self .signer .headers( &SignRequest { origin: &origin.text, method: "GET", path: &path, body: None, }, self.refusals.clock_offset_ms(&origin.text), ) .into_iter() .map(|(name, value)| (name.to_string(), value)) .collect(); Ok((url, headers)) } /// `path` naming the database this device acts on — THE one place a /// signed request gains its `database` (`cotton_core::device::database`). /// /// A path that already names one keeps it (the join names the database it /// was approved for before it has remembered one), a pairing route or the /// database listing names none, and a device that has joined no database /// sends the path as it is — and the server says `database_required` /// rather than this side inventing one. fn naming_database(&self, path: &str) -> String { match self.address.database() { Some(database) => cotton_core::device::database::naming_database(path, &database), None => path.to_string(), } } /// One signed request against a NAMED origin rather than the remembered /// one. /// /// The JOINING half's only entry point, and it has no other caller by /// design: a device that has joined nothing has no remembered address, and /// the origin comes off the QR payload or the typed name. Everything else /// about the ladder is the same — the same signature over the same seven /// fields, the same one moved follow, the same clock correction — which is /// why this is a parameter here rather than a second transport. pub fn call_at( &self, origin: &str, request: ClientRequest, ) -> Result { let deadline_ms = self.deadline_ms(&request); let answer = self.attempt(&request, Some(origin), false)?; read_whole(answer, self.clock.as_ref(), deadline_ms) } /// One request, answered as a STREAM — the head read, the body still on /// the socket. /// /// The snapshot's entry point. Everything the ladder does happens here; /// [`Self::call`] is this plus reading the body whole. /// The way the last request the Mac answered went — an answer or its own /// refusal, never a way that reached nobody. `None` before any has. pub fn last_way(&self) -> Option { *self.last_way.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } /// `answered`, noting the way it came when the Mac was reached at all. fn went( &self, way: Way, answered: Result, ServerRefusal>, ) -> Result, ServerRefusal> { if !matches!(&answered, Err(refusal) if refusal.status == 0) { *self.last_way.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(way); } answered } pub fn open(&self, request: &ClientRequest) -> Result, ServerRefusal> { let answered = self.attempt(request, None, false); self.went(Way::to_origin(self.address.base_url().as_deref()), answered) } /// Which origin this call goes to. fn origin_for(&self, over: Option<&str>) -> Result { let text = match over { Some(text) => text.to_string(), None => self .address .base_url() .ok_or_else(|| ServerRefusal::offline(NO_SERVER).with_code("no_server"))?, }; Origin::parse(&text).map_err(|reason| ServerRefusal::offline(reason).with_code("no_server")) } /// Is `origin` some other Mac than the household this device joined? /// /// `None` (no address in a note) and a device that has joined nothing /// are not foreign: with nothing to compare against, the note is read as /// it was written. Compared as parsed origins, so a trailing slash or a /// default port does not make a home server look like a stranger. fn is_foreign(&self, origin: Option<&str>) -> bool { let (Some(origin), Some(home)) = (origin, self.address.base_url()) else { return false; }; match (Origin::parse(origin), Origin::parse(&home)) { (Ok(there), Ok(here)) => there.text != here.text, _ => origin != home, } } /// Which database's note a request is gated on and filed under. /// /// No database named, or Mine's own id, is Mine; any other id is a place. fn key_for(&self, request: &ClientRequest) -> NoteKey { match request.database() { None => NoteKey::Mine, Some(id) if self.address.mine_id().as_deref() == Some(id) => NoteKey::Mine, Some(id) => NoteKey::Place(id.to_string()), } } /// The two things that refuse a request before it is signed. fn gate( &self, origin: &Origin, path: &str, key: &NoteKey, retry: Retry, ) -> Result { let now_ms = self.clock.now().timestamp_millis(); if let Some(until) = self.refusals.clock_hold_until(&origin.text) { if now_ms < until { // Thrown, never recorded: recording here would re-arm the hold // from inside the hold and it would never lift. return Err(ServerRefusal::new(CLOCK_HELD, 403).with_code("device_clock")); } } if is_pairing_route(path) { // The way back in. A refused device still pairs — that is the // whole point of the exemption. return Ok(Passage::Open); } let Some(note) = self.refusals.standing_terminal_for(key) else { return Ok(Passage::Open); }; // A NOTE UNDER MINE THAT ANOTHER PERSON'S MAC WROTE IS NOT MINE'S. // Before 4 Oct 2026 a `403 device_revoked` from the Mac of a shared // database — answered to a database-less request there, the listing — // was filed under Mine, and from then on the phone refused every owner // route to EVERY server, its own household included, until it was // paired again. `record` no longer files one; a phone that already // holds such a note drops it here, so the fix heals a poisoned phone // on its next request rather than on a re-pair. if self.refusals.standing_for(&NoteKey::Mine).as_ref() == Some(¬e) && self.is_foreign(note.server_url.as_deref()) { self.refusals.note_for(NoteKey::Mine, None); return match self.refusals.standing_terminal_for(key) { None => Ok(Passage::Open), Some(own) => Err(ServerRefusal::new(terminal_sentence(&own.code), 403).with_code(own.code)), }; } // A fresh attempt is only ever against the request's OWN note. A // place stopped by Mine's note waits for Mine's own requests to earn // theirs: a place's answer says nothing about Mine. let own = self.refusals.standing_for(key).as_ref() == Some(¬e); if own && retry == Retry::Allowed && self.worth_one_more_ask(origin, ¬e, now_ms) { return Ok(Passage::Fresh); } Err(ServerRefusal::new(terminal_sentence(¬e.code), 403).with_code(note.code)) } /// Is the verdict in `note` about a machine OTHER than the one this name /// reaches now — so the owner request goes out once more? /// /// * An older build's note recorded no machine: stale, and it gets its one /// retry without the question ([`RefusalMemory::spend_stale_retry`] /// makes sure it is only one). /// * Otherwise the origin is ASKED which machine answers it — unsigned, /// about nothing but itself — and only a machine that names itself and /// is not the one that refused is a reason to ask again. The same /// machine, a name that answers with no tag, or a name that does not /// answer at all are the same verdict as before, and the origin is not /// asked again for [`super::refusal::ANSWERER_QUIET_MS`]. fn worth_one_more_ask(&self, origin: &Origin, note: &DeviceRefusal, now_ms: i64) -> bool { // **A REVOCATION IS NEVER RE-ASKED OF ANOTHER MACHINE.** A copy of the // file only moves forward, so a Mac that says `device_revoked` saw a // real revocation; a Mac that would admit the device is the one more // likely to be stale. Re-asking would let a revoked device — and an // erase the owner ticked — be cleared by whichever Mac has not heard // yet. The way back for a revoked device is pairing, which the gate // already lets out. Only a verdict a stale copy can give wrongly // (`device_not_approved`, 28 Sep 2026) earns the fresh attempt. if note.kind == RefusalKind::Revoked { return false; } if note.refuser == Refuser::Unrecorded { return true; } if self.refusals.answerer_is_quiet(&origin.text, now_ms) { return false; } let answering = self.who_answers(origin); if note.refuser.is_other_than(answering.as_deref()) { return true; } self.refusals.note_same_answerer(&origin.text, now_ms); false } /// `GET /health` of `origin`, UNSIGNED and past the gate, read whole. /// /// What a join asks BEFORE it presents this device's key: which app the /// server is (`cotton_core::flavor`). Unsigned because the answer is about /// the server, never about this device — and so a device carrying a /// standing refusal note can still ask it, as it can still pair. A non-2xx /// is handed back as an answer, not a refusal: the caller decides what an /// older or stranger server's `/health` means. pub fn health_of(&self, origin: &str) -> Result { let origin = self.origin_for(Some(origin))?; self.health_at(&origin) } /// [`Self::health_of`] for a parsed origin. fn health_at(&self, origin: &Origin) -> Result { let authority = origin.authority(); let wire = super::http1::Http1Request { method: "GET", path: ANSWERER_PROBE_PATH, authority: &authority, headers: Vec::new(), body: None, }; let request = ClientRequest::get(ANSWERER_PROBE_PATH); let deadline_ms = self.deadline_ms(&request); let answer = self .exchange .send(origin, &wire, self.ceiling_for(&request)) .map_err(ServerRefusal::offline)?; read_whole(answer, self.clock.as_ref(), deadline_ms) } /// **IS THIS ORIGIN THIS APP'S?** Asked before the first request this /// device signs to it, whatever route that request is — so a Cotton Dev /// device whose remembered address is the real household's (a restored /// backup, a copied folder, a hand-edited file) signs NOTHING there, and /// the reverse. The join asks the same question on its own, earlier, to /// give its own refusal; this is the transport's, under every caller. /// /// Two halves, as the join's: a relay name that is the other app's is /// refused without a request; otherwise the origin's unsigned /// `GET /health` is read for its `flavor`, and a server that says nothing /// is the frozen real one (`cotton_core::flavor::Flavor::refusal_for_server`). /// Status `0` and [`OTHER_APP`]: nothing was signed or sent for this /// device, and nothing is recorded as a refusal of it. fn confirm_app(&self, origin: &Origin) -> Result<(), ServerRefusal> { let Some(app) = self.app else { return Ok(()); }; if self .confirmed .lock() .unwrap_or_else(|e| e.into_inner()) .contains(&origin.text) { return Ok(()); } let refused = |sentence: String| ServerRefusal::offline(sentence).with_code(OTHER_APP); if let Some(sentence) = crate::join::origin_refusal(&origin.text, Some(app)) { return Err(refused(sentence)); } let health = self.health_at(origin)?; let said = crate::join::server_flavor_of(&health)?; if let Some(sentence) = app.refusal_for_server(said.as_deref()) { return Err(refused(sentence)); } self.confirmed .lock() .unwrap_or_else(|e| e.into_inner()) .insert(origin.text.clone()); Ok(()) } /// Which machine answers `origin` right now, by its own tag — `None` when /// it did not answer or did not say. /// /// `GET /health`, UNSIGNED: this asks the name about itself, never about /// this device, so it is not the refused question asked again. fn who_answers(&self, origin: &Origin) -> Option { let authority = origin.authority(); let wire = super::http1::Http1Request { method: "GET", path: ANSWERER_PROBE_PATH, authority: &authority, headers: Vec::new(), body: None, }; let ceiling = self .ceiling .min(Duration::from_millis(ANSWERER_PROBE_CEILING_MS)); let answer = self.exchange.send(origin, &wire, ceiling).ok()?; if !(200..300).contains(&answer.status()) { return None; } Refuser::of_header(answer.header(SERVER_ID_HEADER).as_deref()) .tag() .map(str::to_string) } /// When this call must be over, on this transport's clock: the ceiling, /// plus what the request's body buys, counted from NOW — the start of the /// call, before the dial — so the body's read is inside the ceiling /// rather than a fresh one after the head. fn deadline_ms(&self, request: &ClientRequest) -> i64 { let whole = self.ceiling_for(request) + super::body_allowance(request.body.as_ref().map_or(0, Vec::len)); self.clock.now().timestamp_millis() + whole.as_millis() as i64 } /// The ceiling THIS request asked for, or this transport's. /// /// Never longer than the transport's: a caller may give up sooner than the /// backstop and never later, because the backstop is what stops a socket /// that never settles from holding a loop for ever. No route is exempt: /// the snapshot, whose server works for minutes before it has a byte, /// polls for its copy in ordinary short requests instead. fn ceiling_for(&self, request: &ClientRequest) -> Duration { match request.ceiling_ms { Some(ms) => self.ceiling.min(Duration::from_millis(ms)), None => self.ceiling, } } fn attempt( &self, request: &ClientRequest, over: Option<&str>, clock_corrected: bool, ) -> Result, ServerRefusal> { // EVERY REQUEST THIS DEVICE SIGNS PASSES HERE — `call`, `call_at` and // `open` — so the guard is asked once, before the gate, whether or not // the gate would refuse without dialling: the caller cannot know which, // and a hold that is safe only when the server is unreachable is not // safe. `wire::dial` asks again below; a seam a test fakes above the // dial (`media::drain`'s ports) asks on its own. cotton_store::held::must_not_wait("a signed request to the server"); let outcome = self .attempt_once(request, over, clock_corrected) .map(|answer| Box::new(ReadOutsideAHold(answer)) as Box); if let Err(refusal) = &outcome { *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Some(refusal.clone()); } else { *self.last.lock().unwrap_or_else(|e| e.into_inner()) = None; } outcome } fn attempt_once( &self, request: &ClientRequest, over: Option<&str>, clock_corrected: bool, ) -> Result, ServerRefusal> { let origin = self.origin_for(over)?; self.confirm_app(&origin)?; self.confirm_pin(&origin)?; let key = self.key_for(request); let passage = self.gate(&origin, &request.path, &key, Retry::Allowed)?; self.send_signed(request, &origin, passage, &key, clock_corrected) } /// The path as signed — naming the database — and every header the /// request carries: the signature, and the unsigned ones beside it. /// /// ONE composition for a request this transport sends and one it hands /// over ([`Self::hand_over`]), so the two can never disagree about what a /// signed request is. fn signed_headers( &self, request: &ClientRequest, origin: &Origin, ) -> (String, Vec<(String, String)>) { let path = self.naming_database(&request.path); let mut headers: Vec<(String, String)> = self .signer .headers( &SignRequest { origin: &origin.text, method: request.method, path: &path, body: request.body.as_deref(), }, self.refusals.clock_offset_ms(&origin.text), ) .into_iter() .map(|(name, value)| (name.to_string(), value)) .collect(); if let Some(content_type) = request.content_type { headers.push(("Content-Type".to_string(), content_type.to_string())); } // WHAT THIS DEVICE IS, on every request it makes. Unsigned, for the // reason `DEVICE_APP_HEADER` states: the signature says whose row this // is, and this says what that row should now read. The server writes it // only when it CHANGED, so the cost of sending it every time is the // twenty bytes on the wire. if let Some(device_app) = &self.device_app { headers.push(( cotton_core::device::signature::DEVICE_APP_HEADER.to_string(), device_app.clone(), )); } // Only where the caller said it will inflate what comes back. The // signature covers the method, the path and the body — never this — so // asking costs the request nothing but its own eleven bytes. if let Some(encoding) = request.accept_encoding { headers.push(("Accept-Encoding".to_string(), encoding.to_string())); } // A resumed body: the rest of a copy the signed query names by id. if let Some(start) = request.range { headers.push(("Range".to_string(), format!("bytes={start}-"))); } (path, headers) } /// **A REQUEST SIGNED HERE AND SENT BY SOMEBODY ELSE** — the URL and every /// header, for the phone's background download (`bootstrap::carry`), which /// iOS sends from its own process while this one is suspended. /// /// Everything before the send is the ladder's: the address, the app and /// pin checks, the gate (a standing refusal refuses here, nothing is /// signed) and the clock correction. What is NOT here is anything after /// it — the answer comes back as a file the bootstrap folds in, and a /// refusal in it sends the next attempt through [`Self::open`], where the /// ladder reads it. A signature is good for /// `MAX_DEVICE_CLOCK_SKEW_SECONDS`, so a caller asks again rather than /// keeping one. pub fn hand_over(&self, request: &ClientRequest) -> Result { let origin = self.origin_for(None)?; self.confirm_app(&origin)?; self.confirm_pin(&origin)?; let key = self.key_for(request); self.gate(&origin, &request.path, &key, Retry::Never)?; let (path, headers) = self.signed_headers(request, &origin); Ok(HandedOver { url: format!("{}{path}", origin.text), headers, signed_at_ms: self.clock.now().timestamp_millis() + self.refusals.clock_offset_ms(&origin.text), }) } /// One signed request past the gate. The clock correction re-enters HERE, /// not at the gate: the retry is the same request, and asking the name who /// answers it a second time would be a second fresh attempt. fn send_signed( &self, request: &ClientRequest, origin: &Origin, passage: Passage, key: &NoteKey, clock_corrected: bool, ) -> Result, ServerRefusal> { let started_ms = self.clock.now().timestamp_millis(); let (path, headers) = self.signed_headers(request, origin); let authority = origin.authority(); let wire = super::http1::Http1Request { method: request.method, path: &path, authority: &authority, headers, body: request.body.as_deref(), }; let mut answer = self .exchange .send(origin, &wire, self.ceiling_for(request)) .map_err(ServerRefusal::offline)?; // THE PIN, on the answer itself: the name can pass to another Mac // between the check and this request. Before the status is read, so a // verdict from a Mac that is not the pinned one is never recorded. if let Some(pinned) = &self.pinned { self.pinned_answer(origin, pinned, answer.header(SERVER_ID_HEADER).as_deref())?; } let status = answer.status(); if passage == Passage::Fresh { // A server ANSWERED the fresh attempt, so an older build's note has // had its one retry — whatever the status. Nothing answering // (offline, above) is not an attempt, and leaves it for the next. self.refusals.spend_stale_retry_for(key); } if (200..300).contains(&status) { self.refusals.note_success(&origin.text); if passage == Passage::Fresh { // The machine answering the name now admits this device: the // verdict was another machine's, and it goes. self.refusals.note_for(key.clone(), None); } return Ok(answer); } // The body is read SHORT and then parsed — the phone's own rule, kept: // a refusal envelope is a hundred bytes, and a body longer than this // is somebody else's HTML. let body = read_short(answer.as_mut(), REFUSAL_BODY_MAX); let envelope = Envelope::of(&body); let code = if status == 426 { // By STATUS, whatever the body said. A server whose file is AHEAD // of this build answers 426 and the person needs the same sentence // whichever code it chose to spell it with. Some(super::UPGRADE_REQUIRED.to_string()) } else { envelope.code.clone() }; let mut refusal = ServerRefusal::new( format!( "server {status}: {}", envelope .error .clone() .filter(|text| !text.is_empty()) .unwrap_or_else(|| body.clone()) ), status, ); if let Some(code) = &code { refusal = refusal.with_code(code.clone()); } if status == 409 && code.as_deref() == Some("connection_exists") { refusal.existing_connection_id = envelope .id .as_deref() .map(str::trim) .filter(|id| !id.is_empty()) .map(str::to_string); } refusal = refusal.answered_by(answer.header(SERVER_ID_HEADER).as_deref()); refusal.removed_by = envelope.removed_by.clone(); if let Some(seconds) = answer .header("retry-after") .and_then(|value| value.trim().parse::().ok()) { refusal = refusal.retry_after(seconds); } if status == 403 && code.as_deref() == Some("device_clock") && !clock_corrected { if let Some(server_ms) = server_clock_of(answer.as_ref(), &envelope) { self.refusals.note_server_clock( &origin.text, server_ms, self.clock.now().timestamp_millis(), ); // Adopted and retried at once, recording NOTHING: a phone // whose clock was two minutes out is not a device anybody // refused, it is a device that has now been told the time. // // Inside the SAME ceiling: the retry gets what the first try // left, never a fresh one. let spent = u64::try_from( self.clock.now().timestamp_millis().saturating_sub(started_ms), ) .unwrap_or(0); let left = u64::try_from(self.ceiling_for(request).as_millis()) .unwrap_or(u64::MAX) .saturating_sub(spent); if left == 0 { return Err(refusal); } let mut again = request.clone(); again.ceiling_ms = Some(left); return self.send_signed(&again, origin, passage, key, true); } } let unrecognised_signature = status == 401 && code.as_deref() == Some("device_bad_signature") && !is_pairing_route(&request.path); if status == 403 || unrecognised_signature { let refuser = Refuser::of_header(answer.header(SERVER_ID_HEADER).as_deref()); let answered_for = answer.header(crate::connection::list::DATABASE_HEADER); self.record( origin, code.as_deref(), &envelope, refuser, key, answered_for.as_deref(), ); } Err(refusal) } fn record( &self, origin: &Origin, code: Option<&str>, envelope: &Envelope, refuser: Refuser, key: &NoteKey, answered_for: Option<&str>, ) { let Some(code) = code else { // An unclassified refusal records NOTHING. A 403 whose code this // build has never heard of is not a decision about this device. return; }; let Some(kind) = RefusalKind::of_code(code) else { return; }; // ANOTHER PERSON'S MAC DECIDES NOTHING ABOUT MINE. A request to the // Mac of a shared database that names no database (the listing there) // is keyed Mine, but a terminal answer from that Mac is about this // device THERE — being removed from somebody's garden club must not // stop the phone talking to its own household. Such an answer is // filed under nothing: the origins pass reads the 403 itself and // marks the databases removed. if *key == NoteKey::Mine && kind.is_terminal() && self.is_foreign(Some(&origin.text)) { return; } let at = self.clock.now_iso(); if kind == RefusalKind::Clock { let until = self.clock.now().timestamp_millis() + CLOCK_HOLD_MS; self.refusals.note_clock_hold(&origin.text, until); // A clock note must never paint over a terminal one: the clock is // a condition, the other four are decisions. if self.refusals.standing_terminal_for(key).is_some() { return; } } // AN ERASE IS MINE'S ALONE. A place that revokes this device stops // that place; it never wipes the phone. And an answer that names its // database must name Mine for its erase to count (a server older than // the header names none, and is read by the request's own key). let about_mine = *key == NoteKey::Mine && answered_for.is_none_or(|id| self.address.mine_id().as_deref() == Some(id)); self.refusals.note_for(key.clone(), Some(DeviceRefusal { kind, code: code.to_string(), server_url: Some(origin.text.clone()), server_name: envelope.server_name.clone(), at, // ONLY a revocation can carry it. An `erase` on any other body is // a field this build has no opinion about, and reading one would // let a server wipe a phone with a 403 it invented — the erase is // the answer to a revoke the owner ticked a box on, and // `device_revoked` is the only code that says so. erase: kind == RefusalKind::Revoked && envelope.erase && about_mine, // The epoch the refusing Mac serves, kept for the erase guard // (slice 12): a phone wipes only for an epoch it handed over to. serving_epoch: envelope.serving_epoch, // WHICH MACHINE said it, so the verdict is held against that // machine and not against a name another Mac may answer tomorrow. refuser, device: Some(self.signer.device_id()), })); } } impl SignedHttp { /// Persist owner removal requests beside the connection, outside replicas. #[must_use] pub fn with_device_removals(mut self, path: std::path::PathBuf) -> Self { self.removals = Some(Arc::new(super::device_removals::Removals::at(path))); self } fn retry_device_removals(&self) -> Result<(), ServerRefusal> { let Some(removals) = &self.removals else { return Ok(()) }; let Ok(_flight) = removals.flight.try_lock() else { return Ok(()) }; let origin = self.address.base_url().unwrap_or_default(); for row in removals.for_origin(&origin)? { match self.call_direct(row.request()) { Ok(_) => removals.complete(&row)?, Err(error) => { // Transient failures stay pending. A permanent refusal is // reported once without stranding all subsequent sync. if !super::device_removals::transient(&error) { removals.complete(&row)?; return Err(error); } break; } } } Ok(()) } fn call_direct(&self, request: ClientRequest) -> Result { let deadline_ms = self.deadline_ms(&request); // A SYNC READ HOLDS THE GATE from the dial to its last byte: every // media fetch over this transport yields to it. let read = super::records_first::is_sync_read(&request.path).then(|| self.records.reading()); let answer = self.open(&request)?; if let Some(read) = &read { read.over(answer.closer()); } let answered = read_whole(answer, self.clock.as_ref(), deadline_ms); drop(read); answered.map_err(|mut refusal| { // A sync read that STILL missed its ceiling says what media was // on the wire at the time, so the next stall reads from the log. if super::records_first::is_sync_read(&request.path) { if let Some(media) = self.records.media_in_flight() { refusal.message = format!("{} (while {media} was on the wire)", refusal.message); } } refusal }) } } impl ServerFetch for SignedHttp { fn call(&self, request: ClientRequest) -> Result { self.retry_device_removals()?; self.call_direct(request) } fn remove_device(&self, device: &str, erase: bool, database: Option<&str>) -> Result { let removals = self.removals.as_ref().ok_or_else(|| ServerRefusal::new("This device could not save the removal request", 0).with_code("removal_unconfigured"))?; let _flight = removals.flight.lock().unwrap_or_else(|e|e.into_inner()); let row = removals.queue(super::device_removals::Removal { origin: self.address.base_url().unwrap_or_default(), database: database.map(str::to_string).or_else(|| self.address.database()).unwrap_or_default(), device: device.into(), erase, })?; match self.call_direct(row.request()) { Ok(answer) => { removals.complete(&row)?; Ok(answer) } Err(error) if super::device_removals::transient(&error) => Ok(super::device_removals::waiting()), Err(error) => { removals.complete(&row)?; Err(error) } } } fn records_first(&self) -> Option> { Some(Arc::clone(&self.records)) } fn answered_way(&self) -> Option<&'static str> { SignedHttp::last_way(self).map(Way::words) } } /// The body, to the ceiling and no further. /// /// [`ANSWER_CEILING_BYTES`] rather than no limit: this is the path a pull page /// and a refusal come back on, and the one answer that is a whole database goes /// nowhere near it. fn read_whole( mut answer: Box, clock: &dyn Clock, deadline_ms: i64, ) -> Result { let status = answer.status(); let mut body = Vec::new(); let mut buffer = [0u8; 16 * 1024]; // A DEADLINE OVER THE WHOLE CALL, not only over each read — and not a // fresh one once the head is in: `deadline_ms` was set before the dial. // // A per-read timeout lets a server dribbling one byte every fifty-nine // seconds reset it for ever, and this loop never ends — the shape of the // 2026-09-07 hang the ceiling exists to stop, moved one layer in. And // EACH READ waits only for what is LEFT: a check before a read that may // then block for a whole ceiling is a deadline that overruns by one read, // which is up to the ceiling again. A stall timeout is deliberately the // OTHER kind (sixty seconds without a byte, restarted on every byte) // because a whole database on a slow train is a legitimately long read; a // JSON answer on this path is not. let too_long = || { ServerRefusal::new( "the server's answer took longer than this route waits", status, ) }; loop { let left_ms = deadline_ms - clock.now().timestamp_millis(); if left_ms <= 0 { return Err(too_long()); } answer .set_read_timeout(Duration::from_millis(left_ms as u64)) .map_err(|error| { ServerRefusal::new( format!("the server's answer could not be timed ({error})"), status, ) })?; match answer.read(&mut buffer) { Ok(0) => break, Ok(read) => { if body.len() + read > ANSWER_CEILING_BYTES { return Err(ServerRefusal::new( "the server's answer is longer than this route can hold", status, )); } body.extend_from_slice(&buffer[..read]); } // The read waited out what was left: that is the deadline, and // says so rather than "resource temporarily unavailable". Err(_) if deadline_ms <= clock.now().timestamp_millis() => return Err(too_long()), Err(error) => { return Err(ServerRefusal::new( format!("the server's answer did not finish ({error})"), status, )) } } } Ok(ClientAnswer { status, body }) } impl RefusalAware for SignedHttp { fn last_refusal(&self) -> Option { self.last.lock().unwrap_or_else(|e| e.into_inner()).clone() } } /// The sentence a person has to have no server. pub const NO_SERVER: &str = "no server is remembered — join one first"; /// What a held origin answers, locally, without sending anything. pub const CLOCK_HELD: &str = "clock held — try again in a minute"; /// The sentence behind a terminal refusal, for the log and for a caller that /// has no screen. The SCREEN's sentences are the app's (design P16); these are /// what a refusal carries when nothing is painting. fn terminal_sentence(code: &str) -> String { crate::connection::terminal_device_sentence(code) .unwrap_or_else(|| "this device was refused by the server".to_string()) } /// What a refusal body said, when it was a refusal body at all. #[derive(Debug, Default)] struct Envelope { error: Option, code: Option, id: Option, server_name: Option, server_time: Option, /// `true` only on a `device_revoked` the owner asked to be an ERASE. A /// boolean is read as a boolean: a server that sent `"true"` said nothing, /// and the safe reading of nothing is "ask the person". erase: bool, /// The serving epoch a `device_revoked` names (slice 12), when it named one. serving_epoch: Option, /// Who removed this device, when a `device_revoked` named them. removed_by: Option, } impl Envelope { fn of(body: &str) -> Envelope { if !body.trim_start().starts_with('{') { return Envelope::default(); } let Ok(serde_json::Value::Object(parsed)) = serde_json::from_str(body) else { return Envelope::default(); }; let text = |key: &str| { parsed .get(key) .and_then(serde_json::Value::as_str) .map(str::to_string) }; Envelope { error: text("error"), code: text("code"), id: text("id"), server_name: text("serverName"), server_time: parsed.get("serverTime").cloned(), erase: parsed .get("erase") .and_then(serde_json::Value::as_bool) .unwrap_or(false), serving_epoch: parsed.get("servingEpoch").and_then(serde_json::Value::as_i64), removed_by: text("removedBy").map(|name| name.trim().to_string()).filter(|name| !name.is_empty()), } } } /// The server's own idea of now, in milliseconds — from the body first, the /// `Date` header second. fn server_clock_of(answer: &dyn Answer, envelope: &Envelope) -> Option { if let Some(claimed) = &envelope.server_time { // A NUMBER is seconds, always: the server sends `serverTime` as unix // seconds and a millisecond reading would put the phone forty-eight // thousand years out. if let Some(seconds) = claimed.as_i64() { return Some(seconds * 1_000); } if let Some(text) = claimed.as_str() { if !text.is_empty() && text.len() <= 12 && text.bytes().all(|byte| byte.is_ascii_digit()) { return text.parse::().ok().map(|seconds| seconds * 1_000); } if let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(text) { return Some(parsed.timestamp_millis()); } } } let header = answer.header("date")?; chrono::DateTime::parse_from_rfc2822(&header) .ok() .map(|parsed| parsed.timestamp_millis()) } /// At most `max` BYTES of the body, as text. fn read_short(answer: &mut dyn Answer, max: usize) -> String { let mut buffer = vec![0u8; max]; let mut filled = 0usize; while filled < max { match answer.read(&mut buffer[filled..]) { Ok(0) => break, Ok(read) => filled += read, Err(_) => break, } } String::from_utf8_lossy(&buffer[..filled]).to_string() } /// An answer whose body is still on the wire, asking the guard at EVERY read. /// /// `open` hands the caller a socket with the head read and the body not, and /// the caller reads it when it likes — possibly after taking the file. The /// check at the top of [`SignedHttp::attempt`] cannot see that, so each read /// of the body asks again: a body read inside a hold waits on the network /// exactly as a dial would. struct ReadOutsideAHold(Box); impl std::io::Read for ReadOutsideAHold { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { cotton_store::held::must_not_wait("the body of a signed answer"); self.0.read(buf) } } impl Answer for ReadOutsideAHold { fn status(&self) -> u16 { self.0.status() } fn header(&self, name: &str) -> Option { self.0.header(name) } fn content_length(&self) -> Option { self.0.content_length() } fn set_read_timeout(&mut self, timeout: std::time::Duration) -> std::io::Result<()> { self.0.set_read_timeout(timeout) } fn closer(&self) -> Option { self.0.closer() } } #[cfg(test)] #[path = "signed_http_tests.rs"] mod tests;