From a84b041e95507362023c631713a98d8798e6f370 Mon Sep 17 00:00:00 2001 From: Aaron Ogle Date: Wed, 11 Nov 2026 12:42:18 -0600 Subject: [PATCH] fix: report project-identity bind conflicts accurately instead of always advising adopt/fork MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The push-time identity bind dropped the server's 409 body on the floor and collapsed the follow-up binding read into Option: 'None' conflated 'server reports unbound' with 'read failed', and the message always advised 'repo identity adopt'/'fork' — advice that cannot work when the remote is actually unbound (the storage-side ref-scoping bug fixed in atomic-storage#113). - atomic-remote: parse the 409 body into BindServerError {code, message} (both optional, non-JSON tolerated, nested error{} accepted) and map the follow-up read to an explicit ConflictRemote::{Bound, Unbound, Unknown} instead of Option. - libatomic: format_bind_conflict renders per-outcome advice — genuine divergence keeps adopt/fork, a re-minted document of the same project advises adopt only (fork would conflict the same way), an unbound report names the storage bug and says upgrade-and-retry, and an unknown binding states it could not be read without remediation. The server's code/message are quoted verbatim whenever present. Fixes atomicdotdev/atomic#329 --- atomic-remote/src/http/identity.rs | 89 ++++++- .../tests/project_identity_transport.rs | 92 ++++++- libatomic/src/identity_transport.rs | 228 ++++++++++++++++-- 3 files changed, 378 insertions(+), 31 deletions(-) diff --git a/atomic-remote/src/http/identity.rs b/atomic-remote/src/http/identity.rs index 55390c9d..c5b7ce1a 100644 --- a/atomic-remote/src/http/identity.rs +++ b/atomic-remote/src/http/identity.rs @@ -19,7 +19,7 @@ use reqwest::header::CONTENT_TYPE; use reqwest::StatusCode; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::Value; use super::HttpRemote; @@ -36,14 +36,81 @@ pub enum IdentityFetch { Unsupported, } +/// The server's structured error body on a `409` bind rejection. Both fields +/// are optional and the body itself may be empty or non-JSON, in which case +/// the caller simply gets no reason to quote. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct BindServerError { + /// The server's machine-readable reason (e.g. `IDENTITY_CONFLICT`). + #[serde(default)] + pub code: Option, + /// The server's human-readable reason, quoted verbatim to the operator. + #[serde(default)] + pub message: Option, +} + +impl BindServerError { + /// Parse a `409` response body; `None` when it is not a usable JSON + /// object. The flat `{"code", "message"}` spelling is expected, and the + /// nested `{"error": {…}}` spelling is accepted so either server shape + /// surfaces its reason. + fn from_body(body: &str) -> Option { + let parsed: Value = serde_json::from_str(body).ok()?; + let (code, message) = match parsed.get("error") { + Some(nested) => ( + nested.get("code").and_then(|v| v.as_str()), + nested.get("message").and_then(|v| v.as_str()), + ), + None => ( + parsed.get("code").and_then(|v| v.as_str()), + parsed.get("message").and_then(|v| v.as_str()), + ), + }; + Some(Self { + code: code.map(str::to_owned), + message: message.map(str::to_owned), + }) + } +} + +/// What the follow-up read of the remote binding resolved to after a `409`, +/// so callers can tell a genuine divergence from a server that disagrees with +/// its own rejection. +#[derive(Debug, Clone, PartialEq)] +pub enum ConflictRemote { + /// The follow-up GET resolved to a bound identity document. + Bound(Value), + /// The follow-up GET succeeded but the server reports the project unbound + /// (server disagrees with its own 409). + Unbound, + /// The follow-up GET failed or the document was unusable. + Unknown, +} + +impl ConflictRemote { + fn from_fetch(fetched: RemoteResult) -> Self { + match fetched { + Ok(IdentityFetch::Bound(identity)) => Self::Bound(identity), + Ok(IdentityFetch::Unbound) => Self::Unbound, + // A pre-transport ping or any transport trouble leaves the + // binding unreadable. + Ok(IdentityFetch::Unsupported) | Err(_) => Self::Unknown, + } + } +} + /// The result of offering the local identity to a remote. #[derive(Debug, Clone)] pub enum BindOutcome { /// Bound now, or already identically bound. Bound, - /// A *different* identity is already bound; carries the remote's document - /// when it could be read. - Conflict { remote: Option }, + /// A *different* identity is already bound; carries what the follow-up + /// read of the remote binding resolved to and the server's error body + /// when it sent one. + Conflict { + remote: ConflictRemote, + server: Option, + }, /// The remote predates the identity transport; nothing to do. Unsupported, } @@ -114,13 +181,13 @@ impl HttpRemote { match response.status() { StatusCode::OK | StatusCode::CREATED => Ok(BindOutcome::Bound), StatusCode::CONFLICT => { - // Read the binding the server already holds so the caller can - // name the divergence; failure to read it is not fatal here. - let remote = match self.fetch_project_identity().await { - Ok(IdentityFetch::Bound(identity)) => Some(identity), - _ => None, - }; - Ok(BindOutcome::Conflict { remote }) + // Read the rejection body (the server's reason) and the + // binding the server already holds so the caller can name the + // divergence; neither read is fatal here. + let body = response.text().await.unwrap_or_default(); + let server = BindServerError::from_body(&body); + let remote = ConflictRemote::from_fetch(self.fetch_project_identity().await); + Ok(BindOutcome::Conflict { remote, server }) } StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED diff --git a/atomic-remote/tests/project_identity_transport.rs b/atomic-remote/tests/project_identity_transport.rs index b3844156..43f17b4e 100644 --- a/atomic-remote/tests/project_identity_transport.rs +++ b/atomic-remote/tests/project_identity_transport.rs @@ -3,11 +3,13 @@ //! Covers the four behaviors the daemon and CLI depend on: reading a bound //! identity, distinguishing unbound from unsupported servers, binding on the //! first push, and mapping the server's 409 to a typed conflict that carries -//! the remote's document. +//! the server's error body and what the follow-up read of the binding +//! resolved to. use std::io::{Read, Write}; use std::net::TcpListener; +use atomic_remote::http::identity::ConflictRemote; use atomic_remote::{HttpRemote, HttpRemoteConfig}; use serde_json::json; @@ -144,8 +146,92 @@ async fn a_conflict_reports_the_remote_binding() { .await .expect("bind") { - atomic_remote::http::identity::BindOutcome::Conflict { remote } => { - assert_eq!(remote, Some(remote_document)); + atomic_remote::http::identity::BindOutcome::Conflict { remote, server } => { + assert_eq!(remote, ConflictRemote::Bound(remote_document)); + assert_eq!( + server, + Some(atomic_remote::http::identity::BindServerError { + code: Some("IDENTITY_CONFLICT".into()), + message: None, + }), + "the nested error body's code is surfaced" + ); + } + other => panic!("expected Conflict, got {other:?}"), + } +} + +#[tokio::test] +async fn a_conflict_body_surfaces_the_server_code_and_message() { + let document = identity_document(&"A".repeat(52)); + let (url, _) = serve(vec![ + ( + 409, + json!({"code": "IDENTITY_CONFLICT", "message": "project already bound"}).to_string(), + ), + ( + 200, + json!({"bound": true, "hash": "cd".repeat(32), "identity": document}).to_string(), + ), + ]); + match remote(&url) + .bind_project_identity(&document) + .await + .expect("bind") + { + atomic_remote::http::identity::BindOutcome::Conflict { remote, server } => { + assert!(matches!(remote, ConflictRemote::Bound(_))); + assert_eq!( + server, + Some(atomic_remote::http::identity::BindServerError { + code: Some("IDENTITY_CONFLICT".into()), + message: Some("project already bound".into()), + }), + ); + } + other => panic!("expected Conflict, got {other:?}"), + } +} + +#[tokio::test] +async fn a_conflict_followed_by_an_unbound_read_maps_to_unbound() { + // The server contradicts its own 409: the follow-up read says the project + // is unbound (the atomic-storage#113 ref-scoping bug). + let document = identity_document(&"A".repeat(52)); + let (url, _) = serve(vec![ + (409, json!({"code": "IDENTITY_CONFLICT"}).to_string()), + (200, json!({"bound": false}).to_string()), + ]); + match remote(&url) + .bind_project_identity(&document) + .await + .expect("bind") + { + atomic_remote::http::identity::BindOutcome::Conflict { remote, server } => { + assert_eq!(remote, ConflictRemote::Unbound); + assert_eq!( + server.map(|s| s.code), + Some(Some("IDENTITY_CONFLICT".into())), + ); + } + other => panic!("expected Conflict, got {other:?}"), + } +} + +#[tokio::test] +async fn a_conflict_whose_follow_up_read_fails_maps_to_unknown() { + let document = identity_document(&"A".repeat(52)); + let (url, _) = serve(vec![ + (409, json!({"code": "IDENTITY_CONFLICT"}).to_string()), + (500, "storage error".to_string()), + ]); + match remote(&url) + .bind_project_identity(&document) + .await + .expect("bind") + { + atomic_remote::http::identity::BindOutcome::Conflict { remote, .. } => { + assert_eq!(remote, ConflictRemote::Unknown); } other => panic!("expected Conflict, got {other:?}"), } diff --git a/libatomic/src/identity_transport.rs b/libatomic/src/identity_transport.rs index 3c6b7809..cceeabe4 100644 --- a/libatomic/src/identity_transport.rs +++ b/libatomic/src/identity_transport.rs @@ -21,7 +21,7 @@ use std::fmt; use atomic_core::kg::project_id::ProjectIdentityRecord; -use atomic_remote::http::identity::{BindOutcome, IdentityFetch}; +use atomic_remote::http::identity::{BindOutcome, BindServerError, ConflictRemote, IdentityFetch}; use atomic_remote::HttpRemote; use atomic_repository::{Repository, RepositoryError}; @@ -179,6 +179,78 @@ pub enum PushBind { Unsupported, } +/// Render the operator-facing refusal for a `409` bind outcome. Pure so the +/// advice can be unit-tested without any transport. +/// +/// The advice depends on what the follow-up read of the remote binding found: +/// a genuinely different project keeps the adopt/fork choice, a re-minted +/// document of the same project only leaves `adopt` (fork would mint a third +/// lineage that conflicts the same way), and a server that contradicts its own +/// `409` by reporting the project unbound points at the storage bug instead. +/// The server's own words are quoted whenever it sent any. +fn format_bind_conflict( + local_id: &str, + remote: &ConflictRemote, + server: Option<&BindServerError>, +) -> String { + let note = server_note(server); + match remote { + ConflictRemote::Bound(document) => { + let remote_id = document + .get("atomic:projectId") + .and_then(|v| v.as_str()) + .map(str::to_owned); + match remote_id { + Some(remote_id) if remote_id != local_id => format!( + "remote project identity is {remote_id}; local is {local_id}. \ + These are different projects — run 'atomic repo identity adopt' \ + to take the remote lineage, or 'atomic repo identity fork' to \ + start a new project, then push accordingly.{note}" + ), + Some(remote_id) => format!( + "the remote is bound to a different document of the same project \ + ({remote_id}) — the bound document was likely re-minted. \ + Run 'atomic repo identity adopt' to take the remote lineage, \ + then push; 'fork' would mint a third lineage that conflicts \ + the same way.{note}" + ), + None => format!( + "the remote is bound to a project-identity document without a \ + readable atomic:projectId, so the divergence cannot be named. \ + Run 'atomic repo identity adopt' to take the remote lineage \ + regardless, then push.{note}" + ), + } + } + ConflictRemote::Unbound => format!( + "the server refused the project-identity bind with a conflict but then \ + reports the project unbound — this contradicts itself and indicates a \ + server-side project-identity ref scoping bug (fixed in \ + atomic-storage#113). Local project identity is {local_id}. Upgrade the \ + storage server and retry the push.{note}" + ), + ConflictRemote::Unknown => format!( + "the push was refused because the remote is already bound to a different \ + project identity, and the remote binding could not be read to name the \ + divergence. Local project identity is {local_id}.{note}" + ), + } +} + +/// The server's own words from the `409` body, quoted verbatim; empty when the +/// server sent no readable reason. +fn server_note(server: Option<&BindServerError>) -> String { + let Some(server) = server else { + return String::new(); + }; + match (&server.code, &server.message) { + (Some(code), Some(message)) => format!(" (server code {code}: {message})"), + (Some(code), None) => format!(" (server code {code})"), + (None, Some(message)) => format!(" (server message: {message})"), + (None, None) => String::new(), + } +} + /// Bind the local identity to the remote before a push, refusing a push that /// would land on a project bound to a *different* identity. Pass the local /// record when the repository has one; `None` (no local identity) is a no-op. @@ -205,22 +277,9 @@ pub async fn bind_before_push( })? { BindOutcome::Bound => Ok(PushBind::Bound(local_id)), BindOutcome::Unsupported => Ok(PushBind::Unsupported), - BindOutcome::Conflict { remote: remote_doc } => { - let remote_id = remote_doc - .as_ref() - .and_then(|doc| doc.get("atomic:projectId")) - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - Err(RepositoryError::InvalidOperation { - message: format!( - "remote project identity is {remote_id}; local is {local_id}. \ - These are different projects — run 'atomic repo identity adopt' \ - to take the remote lineage, or 'atomic repo identity fork' to \ - start a new project, then push accordingly." - ), - }) - } + BindOutcome::Conflict { remote, server } => Err(RepositoryError::InvalidOperation { + message: format_bind_conflict(&local_id, &remote, server.as_ref()), + }), } } @@ -250,3 +309,138 @@ pub async fn adopt_from_remote( repo.rebuild_kg(false)?; Ok(project_id) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn local_id() -> String { + "A".repeat(52) + } + + fn bound_document(project_id: &str) -> ConflictRemote { + ConflictRemote::Bound(json!({ + "@context": {"atomic": "https://atomic.dev/ns/workflow#"}, + "@type": "atomic:ProjectIdentity", + "atomic:projectId": project_id, + })) + } + + fn server_error(code: &str, message: &str) -> BindServerError { + BindServerError { + code: Some(code.to_owned()), + message: Some(message.to_owned()), + } + } + + #[test] + fn a_genuinely_different_project_keeps_the_adopt_fork_advice() { + let remote_id = "B".repeat(52); + let message = format_bind_conflict( + &local_id(), + &bound_document(&remote_id), + Some(&server_error("IDENTITY_CONFLICT", "project already bound")), + ); + assert!( + message.contains(&remote_id) && message.contains(&local_id()), + "both ids must be named: {message}" + ); + assert!( + message.contains("adopt") && message.contains("fork"), + "genuine divergence keeps both remediations: {message}" + ); + assert!( + message.contains("project already bound"), + "the server's own words are quoted: {message}" + ); + } + + #[test] + fn a_re_minted_document_of_the_same_project_advises_adopt_only() { + let message = format_bind_conflict( + &local_id(), + &bound_document(&local_id()), + Some(&server_error("IDENTITY_CONFLICT", "project already bound")), + ); + assert!( + message.contains("same project"), + "the same-project case is named: {message}" + ); + assert!( + message.contains("adopt"), + "adopt is the remediation: {message}" + ); + assert!( + !message.contains("'atomic repo identity fork'"), + "fork would conflict the same way and must not be advised: {message}" + ); + } + + #[test] + fn a_bound_document_without_a_readable_project_id_says_so() { + let message = format_bind_conflict( + &local_id(), + &ConflictRemote::Bound(json!({"@type": "atomic:ProjectIdentity"})), + None, + ); + assert!( + message.contains("without a readable atomic:projectId"), + "the unreadable document is explained: {message}" + ); + assert!( + !message.contains(""), + "no bare placeholder: {message}" + ); + } + + #[test] + fn an_unbound_report_points_at_the_server_bug_not_remediation() { + let message = format_bind_conflict( + &local_id(), + &ConflictRemote::Unbound, + Some(&server_error( + "IDENTITY_CONFLICT", + "ref scoped to sibling project", + )), + ); + assert!( + !message.contains("adopt") && !message.contains("fork"), + "adopt/fork cannot help against an unbound remote: {message}" + ); + assert!( + message.contains("atomic-storage#113"), + "the server-side bug is named: {message}" + ); + assert!( + message.contains("Upgrade the storage server and retry"), + "the remediation is upgrade-and-retry: {message}" + ); + assert!( + message.contains("IDENTITY_CONFLICT") + && message.contains("ref scoped to sibling project"), + "the server's code and message are quoted verbatim: {message}" + ); + } + + #[test] + fn an_unknown_binding_states_it_could_not_be_read_without_remediation() { + let message = format_bind_conflict( + &local_id(), + &ConflictRemote::Unknown, + Some(&server_error("IDENTITY_CONFLICT", "project already bound")), + ); + assert!( + message.contains("could not be read"), + "the unreadable binding is stated: {message}" + ); + assert!( + !message.contains("adopt") && !message.contains("fork"), + "no remediation when the divergence is unknown: {message}" + ); + assert!( + message.contains("project already bound"), + "the server's own words are quoted: {message}" + ); + } +}