From e897fd7d65192aec32f3b80458dd4a2e673e6c78 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Wed, 2 Dec 2026 23:29:12 +0000 Subject: [PATCH 1/9] fix(breg): admit additive Action response members Signed-off-by: Jeremi Joslin --- crates/registry-breg-client/src/actions.rs | 40 +--- .../action_recovery_registry_revision.rs | 221 +++++++++++++++++- 2 files changed, 218 insertions(+), 43 deletions(-) diff --git a/crates/registry-breg-client/src/actions.rs b/crates/registry-breg-client/src/actions.rs index 4b3d91b690..9c7606df34 100644 --- a/crates/registry-breg-client/src/actions.rs +++ b/crates/registry-breg-client/src/actions.rs @@ -589,6 +589,7 @@ impl BaseRegistryClient { let restored = BRegActionInvocationRequest::new(action, original_inputs.clone(), conditions.as_ref()) .map_err(|_| action_recovery_refusal())?; + // Recovery requires the exact canonical body, including closed condition objects. if restored.body.as_slice() != saved.body.as_bytes() { return Err(action_recovery_refusal()); } @@ -832,28 +833,11 @@ fn decode_availability( ) -> Result { let value = crate::strict_json::from_slice(bytes).map_err(|_| BRegActionError::InvalidResponse)?; - let outer = value - .as_object() - .filter(|object| object.len() == 1) - .ok_or(BRegActionError::InvalidResponse)?; + let outer = value.as_object().ok_or(BRegActionError::InvalidResponse)?; let availability = outer .get("availability") .and_then(Value::as_object) .ok_or(BRegActionError::InvalidResponse)?; - if availability.keys().any(|key| { - !matches!( - key.as_str(), - "available" - | "observedRevision" - | "reason" - | "recovery" - | "missingInputs" - | "guardReason" - | "guardLabel" - ) - }) { - return Err(BRegActionError::InvalidResponse); - } let available = match availability.get("available") { Some(Value::Bool(value)) => Some(*value), Some(Value::Null) => None, @@ -944,10 +928,7 @@ fn decode_conditions( ) -> Result { let value = crate::strict_json::from_slice(bytes).map_err(|_| BRegActionError::InvalidResponse)?; - let object = value - .as_object() - .filter(|object| object.len() == 1) - .ok_or(BRegActionError::InvalidResponse)?; + let object = value.as_object().ok_or(BRegActionError::InvalidResponse)?; let conditions = object .get("preconditions") .and_then(Value::as_object) @@ -962,10 +943,7 @@ fn decode_conditions( let preconditions = conditions .iter() .map(|(name, value)| { - let condition = value - .as_object() - .filter(|condition| condition.len() == 1) - .ok_or(BRegActionError::InvalidResponse)?; + let condition = value.as_object().ok_or(BRegActionError::InvalidResponse)?; let if_match = condition .get("ifMatch") .and_then(Value::as_str) @@ -992,10 +970,7 @@ fn decode_receipt( ) -> Result { let value = crate::strict_json::from_slice(bytes).map_err(|_| BRegActionError::InvalidResponse)?; - let object = value - .as_object() - .filter(|object| object.len() == 3) - .ok_or(BRegActionError::InvalidResponse)?; + let object = value.as_object().ok_or(BRegActionError::InvalidResponse)?; if object.get("action").and_then(Value::as_str) != Some(action.action_identifier()) { return Err(BRegActionError::InvalidResponse); } @@ -1020,10 +995,7 @@ fn decode_receipt( let results = values .iter() .map(|(effect, value)| { - let result = value - .as_object() - .filter(|result| result.len() == 3) - .ok_or(BRegActionError::InvalidResponse)?; + let result = value.as_object().ok_or(BRegActionError::InvalidResponse)?; let entity = result .get("recordType") .and_then(Value::as_str) diff --git a/crates/registry-breg-client/tests/action_recovery_registry_revision.rs b/crates/registry-breg-client/tests/action_recovery_registry_revision.rs index f3115f8689..a65fb67376 100644 --- a/crates/registry-breg-client/tests/action_recovery_registry_revision.rs +++ b/crates/registry-breg-client/tests/action_recovery_registry_revision.rs @@ -16,8 +16,9 @@ use axum::http::{Request, Response, StatusCode}; use axum::routing::any; use axum::Router; use registry_breg_client::{ - BRegActionInvocationRequest, BRegIdempotencyKey, BaseRegistryClient, BaseRegistryClientConfig, - BaseRegistryClientError, + BRegActionAvailabilityRequest, BRegActionInvocationRequest, BRegActionTargetConditionsRequest, + BRegIdempotencyKey, BRegPreparedAction, BRegProtocolFailure, BaseRegistryClient, + BaseRegistryClientConfig, BaseRegistryClientError, }; use registry_platform_httputil::client::{BearerToken, TokenError, TokenProvider}; use serde_json::{json, Map, Value}; @@ -72,23 +73,31 @@ impl TokenProvider for StaticToken { #[derive(Clone)] struct MockState { - responses: Arc>>, + responses: Arc>>, served: Arc, } -async fn handler(State(state): State, _request: Request) -> Response { +async fn handler(State(state): State, request: Request) -> Response { state.served.fetch_add(1, Ordering::SeqCst); let body = state .responses .lock() .expect("response queue lock") .pop_front() - .expect("a queued metadata response"); - let mut response = Response::new(Body::from(serde_json::to_vec(&body).expect("body"))); + .expect("a queued response"); + let mut response = Response::new(Body::from(body)); *response.status_mut() = StatusCode::OK; response .headers_mut() .insert("content-type", "application/json".parse().expect("header")); + if request.method() == axum::http::Method::POST { + response + .headers_mut() + .insert("cache-control", "no-store".parse().expect("header")); + response + .headers_mut() + .insert("vary", "authorization, accept".parse().expect("header")); + } response .headers_mut() .insert("traceparent", TRACEPARENT.parse().expect("header")); @@ -107,7 +116,7 @@ async fn caller_metadata_vocabulary_codes_prepare_and_recover_exactly() { }); let served = Arc::new(AtomicUsize::new(0)); let state = MockState { - responses: Arc::new(Mutex::new(VecDeque::from([metadata]))), + responses: Arc::new(Mutex::new(VecDeque::from([metadata.to_string()]))), served: served.clone(), }; let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -174,8 +183,8 @@ async fn saved_command_refuses_after_registry_revision_change() { let served = Arc::new(AtomicUsize::new(0)); let state = MockState { responses: Arc::new(Mutex::new(VecDeque::from([ - action_metadata(REVISION_A), - action_metadata(REVISION_B), + action_metadata(REVISION_A).to_string(), + action_metadata(REVISION_B).to_string(), ]))), served: served.clone(), }; @@ -255,3 +264,197 @@ async fn saved_command_refuses_after_registry_revision_change() { "prepare and recover perform no exchange" ); } + +#[tokio::test] +async fn action_responses_admit_additions_with_exact_bindings() { + let mut metadata = action_metadata(REVISION_A); + let action = &mut metadata["actions"][0]; + action["inputs"][0]["schema"] = json!({"type":"string","format":"uuid"}); + action["inputs"][0]["fieldType"] = + json!({"type":"reference","target":"incorporation","onDelete":"restrict"}); + action["referenceInputs"] = + json!([{"input":"reference","apiName":"reference","targetRecordType":"incorporation"}]); + action["requiredConditionKeys"] = json!(["reference"]); + for route in ["target-conditions", "availability"] { + let path = format!("/v1/actions/incorporate-company/{route}"); + let key = if route == "availability" { + "availability" + } else { + action["conditionRoute"] = json!(path); + "targetConditions" + }; + action["routes"][key] = json!({ + "method": "POST", "path": path, + "operationId": format!("actions.incorporate-company.{route}"), + "requiresIdempotencyKey": false, + "inputSchema": format!("action-incorporate-company-{route}-input"), + "responseSchema": format!("action-incorporate-company-{route}-response") + }); + } + + let invalid_availability = [ + r#"{"availability":{"available":true}}"#, + r#"{"availability":{"available":true,"observedRevision":3,"reason":"not-disclosed"}}"#, + r#"{"availability":{"available":true,"observedRevision":3,"extra":{"x":1,"x":2}}}"#, + ]; + let invalid_conditions = [ + r#"{"preconditions":{"reference":{"extra":true}}}"#, + r#"{"preconditions":{"reference":{"ifMatch":"W/\"r3\""}}}"#, + r#"{"preconditions":{"reference":{"ifMatch":"\"r3\""},"extra":{"ifMatch":"\"r3\""}}}"#, + r#"{"preconditions":{"reference":{"ifMatch":"\"r3\"","ifMatch":"\"r3\""}}}"#, + ]; + let invalid_receipts = [ + r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"record-incorporation":{"recordType":"incorporation","recordId":"00000000-0000-4000-8000-000000000001"}}}"#, + r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"record-incorporation":{"recordType":"other","recordId":"00000000-0000-4000-8000-000000000001","revision":4}}}"#, + r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"extra":{"recordType":"incorporation","recordId":"00000000-0000-4000-8000-000000000001","revision":4}}}"#, + r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"record-incorporation":{"recordType":"incorporation","recordId":"00000000-0000-4000-8000-000000000001","revision":4,"revision":4}}}"#, + ]; + let availability = + r#"{"availability":{"available":true,"observedRevision":3,"extra":true},"extra":{}}"#; + let conditions = + r#"{"preconditions":{"reference":{"ifMatch":"\"r3\"","extra":true}},"extra":{}}"#; + let receipt = r#"{"action":"incorporate-company","applicationId":"00000000-0000-4000-8000-000000000010","results":{"record-incorporation":{"recordType":"incorporation","recordId":"00000000-0000-4000-8000-000000000001","revision":4,"extra":true}},"extra":{}}"#; + let responses = [metadata.to_string()] + .into_iter() + .chain( + invalid_availability + .into_iter() + .chain([availability]) + .chain(invalid_conditions) + .chain([conditions]) + .chain(invalid_receipts) + .chain([receipt]) + .map(str::to_owned), + ) + .collect(); + let state = MockState { + responses: Arc::new(Mutex::new(responses)), + served: Arc::new(AtomicUsize::new(0)), + }; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let router = Router::new() + .fallback(any(handler)) + .with_state(state.clone()); + let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + let client = BaseRegistryClient::new( + BaseRegistryClientConfig::new_without_peer_policy( + format!("http://{address}/").parse().unwrap(), + ) + .with_token_provider(Arc::new(StaticToken(AtomicUsize::new(0)))) + .with_maximum_mutation_retries(0), + ) + .unwrap(); + let action = client + .registry_contract(Some("preparer")) + .await + .unwrap() + .value + .select_action("incorporate-company", "preparer") + .unwrap(); + let inputs = Map::from_iter([( + "reference".to_owned(), + json!("00000000-0000-4000-8000-000000000001"), + )]); + + let request = BRegActionAvailabilityRequest::new(&action, "reference", inputs.clone()).unwrap(); + for _ in invalid_availability { + let error = client + .action_availability(&action, &request) + .await + .err() + .unwrap(); + assert_action_body_error(error); + } + let availability = client + .action_availability(&action, &request) + .await + .expect("additive availability") + .value; + assert_eq!(availability.available(), Some(true)); + assert_eq!(availability.observed_revision(), Some(3)); + + let request = BRegActionTargetConditionsRequest::new(&action, inputs.clone()).unwrap(); + for _ in invalid_conditions { + let error = client + .action_target_conditions(&action, &request) + .await + .err() + .unwrap(); + assert_action_body_error(error); + } + let conditions = client + .action_target_conditions(&action, &request) + .await + .expect("additive target conditions") + .value; + assert_eq!( + serde_json::to_value(&conditions).unwrap(), + json!({"preconditions":{"reference":{"ifMatch":"\"r3\""}}}) + ); + let other_inputs = Map::from_iter([( + "reference".to_owned(), + json!("00000000-0000-4000-8000-000000000002"), + )]); + assert!(BRegActionInvocationRequest::new(&action, other_inputs, Some(&conditions)).is_err()); + + let request = + BRegActionInvocationRequest::new(&action, inputs.clone(), Some(&conditions)).unwrap(); + let key = BRegIdempotencyKey::parse("incorporate-1").unwrap(); + + // A caller-held prepared command still requires the exact canonical body. + let prepared = client.prepare_action(&action, &request, &key).unwrap(); + let mut saved: Value = serde_json::from_slice(prepared.as_bytes()).unwrap(); + let body = saved["body"].as_str().unwrap(); + let extended = body.replace( + r#"{"ifMatch":"\"r3\""}"#, + r#"{"ifMatch":"\"r3\"","extra":true}"#, + ); + assert_ne!(extended, body); + saved["body"] = json!(extended); + let saved = BRegPreparedAction::from_slice(&serde_json::to_vec(&saved).unwrap()).unwrap(); + assert!(client + .recover_action(&action, &saved, &inputs, &key) + .is_err()); + + for _ in invalid_receipts { + let error = client + .invoke_action(&action, &request, &key) + .await + .err() + .unwrap(); + assert!(error.is_outcome_unknown()); + assert_action_body_error(error); + } + let receipt = client + .invoke_action(&action, &request, &key) + .await + .expect("additive receipt") + .value; + let result = &receipt.results()["record-incorporation"]; + assert_eq!(result.revision(), 4); + assert_eq!( + result.record_identifier().to_string(), + inputs["reference"].as_str().unwrap() + ); + assert_eq!( + receipt.application_identifier().to_string(), + "00000000-0000-4000-8000-000000000010" + ); + assert!(state.responses.lock().unwrap().is_empty()); + server.abort(); +} + +fn assert_action_body_error(error: BaseRegistryClientError) { + assert!( + matches!( + error, + BaseRegistryClientError::Protocol { + status: 200, + failure: BRegProtocolFailure::Body, + .. + } + ), + "{error}" + ); +} From 8fdf66dc88ea85f9c446e8dec387e60d99d0239f Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 3 Dec 2026 01:41:24 +0000 Subject: [PATCH 2/9] fix(breg): admit Proposal callers before reporting request faults Signed-off-by: Jeremi Joslin --- crates/registry-breg/src/api/proposals.rs | 11 +- .../src/api/proposals/answers.rs | 19 ++- .../registry-breg/src/api/proposals/forms.rs | 5 + .../src/api/proposals/messages.rs | 128 +++++++++++------ .../src/mutation/proposal/forms.rs | 15 +- crates/registry-breg/src/problem_location.rs | 14 +- .../registry-breg/src/proposal_artifacts.rs | 8 +- .../registry-breg/tests/postgres_proposal.rs | 3 +- .../tests/postgres_proposal_messages.rs | 135 +++++++++++++++++- .../tests/proposal_messages_compiler.rs | 6 + .../tests/support/proposal_additions.rs | 33 ++++- .../tests/support/proposal_review_asks.rs | 35 +++++ 12 files changed, 338 insertions(+), 74 deletions(-) diff --git a/crates/registry-breg/src/api/proposals.rs b/crates/registry-breg/src/api/proposals.rs index 3bef869d84..e5fb636dd3 100644 --- a/crates/registry-breg/src/api/proposals.rs +++ b/crates/registry-breg/src/api/proposals.rs @@ -2318,7 +2318,7 @@ pub(super) async fn list( let Some(mutations) = &service.mutations else { return concealed(FailedCheck::Visibility); }; - let selected = match proposal_list_admission_profile(raw_query.as_deref()) { + let selected = match proposal_admission_profile(raw_query.as_deref()) { Ok(selected) => selected, Err(()) => { return audited_list_concealment( @@ -2400,7 +2400,7 @@ pub(super) async fn list( Ok(query) => query, Err(QueryParseError::InvalidAt("top")) => { return invalid_query_at_with_detail( - "top", + "query", "The Proposal list takes `limit` for its page size; `top` is not accepted.", ); } @@ -2416,7 +2416,7 @@ pub(super) async fn list( } } -fn proposal_list_admission_profile(raw: Option<&str>) -> Result, ()> { +fn proposal_admission_profile(raw: Option<&str>) -> Result, ()> { let Some(raw) = raw else { return Ok(None) }; if raw.len() > MAX_RAW_QUERY_BYTES { return Err(()); @@ -2454,7 +2454,6 @@ fn proposal_list_parameter(name: &str) -> Option<&'static str> { "target" => Some("target"), "cursor" => Some("cursor"), "limit" => Some("limit"), - "top" => Some("top"), _ => None, } } @@ -2476,6 +2475,9 @@ fn parse_proposal_list_query(raw: Option<&str>) -> Result) -> Result return Err(QueryParseError::InvalidAt("top")), _ if proposal_list_parameter(&name).is_some() => { return Err(proposal_list_error(&name)); } diff --git a/crates/registry-breg/src/api/proposals/answers.rs b/crates/registry-breg/src/api/proposals/answers.rs index b74db5166f..80317f10c1 100644 --- a/crates/registry-breg/src/api/proposals/answers.rs +++ b/crates/registry-breg/src/api/proposals/answers.rs @@ -58,12 +58,21 @@ pub(in crate::api) async fn answer( .await .map_err(|_| invalid_request())?; let value = parse_json_strict(&bytes).map_err(|_| invalid_request())?; - if value.get("text").is_some_and(Value::is_null) { - return Err(proposal_problem(MutationError::InvalidRequestAt( - crate::problem_location::RequestLocation::proposal_answer_text(), - ))); + if value.get("text").is_some_and(|text| !text.is_string()) { + return Err(invalid_request_at( + &crate::problem_location::RequestLocation::proposal_answer_text(), + )); } - let answer: AnswerBody = serde_json::from_value(value).map_err(|_| invalid_request())?; + let answer: AnswerBody = serde_path_to_error::deserialize(value).map_err(|error| { + match error.path().iter().next() { + Some(serde_path_to_error::Segment::Map { key }) if key == "formEntries" => { + invalid_request_at( + &crate::problem_location::RequestLocation::proposal_answer_form_entries(), + ) + } + _ => invalid_request(), + } + })?; Ok((key, etag, answer)) } .await; diff --git a/crates/registry-breg/src/api/proposals/forms.rs b/crates/registry-breg/src/api/proposals/forms.rs index 2edcc7f470..7c0627340f 100644 --- a/crates/registry-breg/src/api/proposals/forms.rs +++ b/crates/registry-breg/src/api/proposals/forms.rs @@ -82,6 +82,11 @@ pub(in crate::api) async fn add_form( .await .map_err(|_| invalid_request())?; let value = parse_json_strict(&bytes).map_err(|_| invalid_request())?; + if !value.get("input").is_some_and(Value::is_object) { + return Err(invalid_request_at( + &crate::problem_location::RequestLocation::input(), + )); + } let body: AddFormBody = serde_json::from_value(value).map_err(|_| invalid_request())?; Ok((key, etag, body.input)) } diff --git a/crates/registry-breg/src/api/proposals/messages.rs b/crates/registry-breg/src/api/proposals/messages.rs index 84e471e037..0fb53208fe 100644 --- a/crates/registry-breg/src/api/proposals/messages.rs +++ b/crates/registry-breg/src/api/proposals/messages.rs @@ -10,7 +10,7 @@ async fn admit( service: &HttpService, id: &str, claims: &VerifiedRequestClaims, - raw: Option<&str>, + selected: Result, ()>, method: HttpMethod, correlation: &RequestCorrelation, ) -> Result<(Uuid, CompiledAction, ProposalAuthority), Response> { @@ -21,7 +21,7 @@ async fn admit( Ok(id) if !id.is_nil() => id, _ => return Err(concealed(FailedCheck::Visibility)), }; - let selected = selected_profile(raw).map_err(|_| concealed(FailedCheck::Visibility))?; + let selected = selected.map_err(|_| concealed(FailedCheck::Visibility))?; let (action, authority) = authorize_target( service, mutations, @@ -109,7 +109,7 @@ pub(in crate::api) async fn write( &service, &id, &claims, - raw_query.as_deref(), + selected_profile(raw_query.as_deref()), HttpMethod::Post, &correlation, ) @@ -136,7 +136,7 @@ pub(in crate::api) async fn write( .map_err(|_| invalid_request())?; let value = parse_json_strict(&bytes).map_err(|_| invalid_request())?; let text = match value.as_object() { - Some(object) if object.len() == 1 => object.get("text"), + Some(object) if object.len() <= 1 => object.get("text"), _ => return Err(invalid_request()), }; let text = text @@ -205,31 +205,11 @@ pub(in crate::api) async fn list( Authenticated(claims): Authenticated, RawQuery(raw_query): RawQuery, ) -> Response { - // `after` and `limit` page the thread; every other parameter selects - // the access profile as on any Proposal read. - let mut after = None; - let mut limit = None; - let mut ordinary = Vec::new(); - for pair in raw_query.as_deref().unwrap_or("").split('&') { - if pair.is_empty() { - continue; - } - let Some((name, value)) = pair.split_once('=') else { - return concealed(FailedCheck::Visibility); - }; - match name { - "after" if after.is_none() => after = Some(value.to_owned()), - "limit" if limit.is_none() => limit = Some(value.to_owned()), - "after" | "limit" => return invalid_request(), - _ => ordinary.push(pair), - } - } - let ordinary = (!ordinary.is_empty()).then(|| ordinary.join("&")); let (id, _, authority) = match admit( &service, &id, &claims, - ordinary.as_deref(), + proposal_admission_profile(raw_query.as_deref()), HttpMethod::Get, &correlation, ) @@ -241,30 +221,15 @@ pub(in crate::api) async fn list( let Some(mutations) = &service.mutations else { return concealed(FailedCheck::Visibility); }; - let before = match after.as_deref().map(str::parse::) { - None => None, - Some(Ok(position)) if position > 0 => Some(position), - Some(_) => { + let (before, limit) = match page_inputs(raw_query.as_deref()) { + Ok(page) => page, + Err(error) => { return admitted_http_refusal( mutations, &authority, HttpMethod::Get, &correlation, - fixed_problem(crate::problem::ProblemCode::QueryCursorInvalid), - ) - .await - } - }; - let limit = match limit.as_deref().map(str::parse::) { - None => crate::proposal_messages::DOCUMENT_ITEMS, - Some(Ok(limit)) if (1..=crate::proposal_messages::MAX_PAGE_ITEMS).contains(&limit) => limit, - Some(_) => { - return admitted_http_refusal( - mutations, - &authority, - HttpMethod::Get, - &correlation, - invalid_request(), + error.problem(), ) .await } @@ -280,6 +245,77 @@ pub(in crate::api) async fn list( } } +/// Parse the page inputs only after the bounded profile selection and visibility check. +fn page_inputs(raw: Option<&str>) -> Result<(Option, i64), PageError> { + let mut cursor = None; + let mut limit = None; + for pair in raw.into_iter().flat_map(|query| query.split('&')) { + let (name, value) = pair.split_once('=').ok_or(PageError::InvalidQuery)?; + let name = percent_decode(name).map_err(|_| PageError::InvalidQuery)?; + let (slot, parameter) = match name.as_str() { + "accessProfile" => continue, + "cursor" => (&mut cursor, "cursor"), + "limit" => (&mut limit, "limit"), + "after" => return Err(PageError::RetiredAfter), + _ => return Err(PageError::InvalidQuery), + }; + if slot.replace(value).is_some() { + return Err(PageError::Parameter(ProblemCode::RequestInvalid, parameter)); + } + } + let position = |value| { + percent_decode(value) + .ok() + .and_then(|value| value.parse::().ok()) + }; + let before = cursor + .map(|value| { + percent_decode(value) + .ok() + .filter(|value| matches!(value.as_bytes().first(), Some(b'1'..=b'9'))) + .and_then(|value| value.parse::().ok()) + .ok_or(PageError::Parameter( + ProblemCode::QueryCursorInvalid, + "cursor", + )) + }) + .transpose()?; + let limit = limit + .map(|value| { + position(value) + .filter(|limit| (1..=crate::proposal_messages::MAX_PAGE_ITEMS).contains(limit)) + .ok_or(PageError::Parameter(ProblemCode::RequestInvalid, "limit")) + }) + .transpose()? + .unwrap_or(crate::proposal_messages::DOCUMENT_ITEMS); + Ok((before, limit)) +} + +enum PageError { + InvalidQuery, + RetiredAfter, + Parameter(ProblemCode, &'static str), +} + +impl PageError { + fn problem(self) -> Response { + match self { + Self::InvalidQuery => invalid_query_at("query"), + Self::RetiredAfter => invalid_query_at_with_detail( + "query", + "The Proposal thread takes `cursor` for its page position; `after` is not accepted.", + ), + Self::Parameter(code, parameter) => crate::correlation::problem_response_with_field_path( + StatusCode::BAD_REQUEST, + code.title(), + code.description(), + code.code(), + parameter, + ), + } + } +} + pub(in crate::api) async fn mark_read( State(service): State>, Path(id): Path, @@ -293,7 +329,7 @@ pub(in crate::api) async fn mark_read( &service, &id, &claims, - raw_query.as_deref(), + selected_profile(raw_query.as_deref()), HttpMethod::Post, &correlation, ) @@ -314,7 +350,7 @@ pub(in crate::api) async fn mark_read( .map_err(|_| invalid_request())?; let value = parse_json_strict(&bytes).map_err(|_| invalid_request())?; match value.as_object() { - Some(object) if object.len() == 1 => object + Some(object) if object.len() <= 1 => object .get("through") .and_then(Value::as_str) .and_then(|id| Uuid::parse_str(id).ok()) diff --git a/crates/registry-breg/src/mutation/proposal/forms.rs b/crates/registry-breg/src/mutation/proposal/forms.rs index 0a45a78cbd..7a9400044d 100644 --- a/crates/registry-breg/src/mutation/proposal/forms.rs +++ b/crates/registry-breg/src/mutation/proposal/forms.rs @@ -53,15 +53,12 @@ pub(super) async fn insert( FailedCheck::AccessProfile, )); } - for key in entry.values.keys() { - if !form.inputs.iter().any(|input| &input.api_name == key) { - let path = if crate::logical_names::valid_api_name(key) { - RequestLocation::action_input(key) - } else { - return Err(MutationError::InvalidRequest); - }; - return Err(MutationError::InvalidRequestAt(path)); - } + if entry + .values + .keys() + .any(|key| !form.inputs.iter().any(|input| &input.api_name == key)) + { + return Err(MutationError::InvalidRequestAt(RequestLocation::input())); } for input in &form.inputs { let valid = entry diff --git a/crates/registry-breg/src/problem_location.rs b/crates/registry-breg/src/problem_location.rs index a79f751c94..37c844bc31 100644 --- a/crates/registry-breg/src/problem_location.rs +++ b/crates/registry-breg/src/problem_location.rs @@ -182,6 +182,15 @@ impl RequestLocation { } } + /// The `input` member of an Action or Proposal body. + #[must_use] + pub fn input() -> Self { + Self { + pointer: "/input".to_owned(), + scope: Scope::Input, + } + } + /// One declared input of an Action or Proposal body. The caller passes /// only a compiled input API name; an over-long name falls back to /// `/input`. @@ -189,10 +198,7 @@ impl RequestLocation { pub fn action_input(api_name: &str) -> Self { let pointer = format!("/input/{}", escape_segment(api_name)); if pointer.chars().count() > MAX_FIELD_PATH_CHARS { - return Self { - pointer: "/input".to_owned(), - scope: Scope::Input, - }; + return Self::input(); } Self { pointer, diff --git a/crates/registry-breg/src/proposal_artifacts.rs b/crates/registry-breg/src/proposal_artifacts.rs index 450b1ad498..d5469a6fc9 100644 --- a/crates/registry-breg/src/proposal_artifacts.rs +++ b/crates/registry-breg/src/proposal_artifacts.rs @@ -568,7 +568,7 @@ fn append_message_openapi( let path = "/v1/proposals/{proposal_id}/messages"; let mut list = operation_document("proposals.list-messages", "get", profiles, false, additions); list["parameters"].as_array_mut().expect("query parameters").extend([ - json!({"name":"after","in":"query","schema":{"type":"string","pattern":"^[1-9][0-9]*$"}}), + json!({"name":"cursor","in":"query","schema":{"type":"string","pattern":"^[1-9][0-9]*$"}}), json!({"name":"limit","in":"query","schema":{"type":"integer","minimum":1,"maximum":50,"default":20}}), ]); list["responses"]["200"]["content"]["application/json"]["schema"] = json!({ @@ -962,7 +962,11 @@ pub(super) fn append_operation_problems(operation: &mut Value, method: &str) { codes.push(ProblemCode::ProposalMessageLimitReached); } if id == "proposals.list-messages" { - codes.extend([ProblemCode::QueryCursorInvalid, ProblemCode::RequestInvalid]); + codes.extend([ + ProblemCode::QueryCursorInvalid, + ProblemCode::QueryInvalid, + ProblemCode::RequestInvalid, + ]); } if id == "proposals.list" { codes.push(ProblemCode::QueryInvalid); diff --git a/crates/registry-breg/tests/postgres_proposal.rs b/crates/registry-breg/tests/postgres_proposal.rs index c24c9f9594..ae39a50fa0 100644 --- a/crates/registry-breg/tests/postgres_proposal.rs +++ b/crates/registry-breg/tests/postgres_proposal.rs @@ -2215,7 +2215,8 @@ async fn proposal_list_query_refusals_follow_authority_and_audit_concealment() { ("limit=0", "limit"), ("cursor=not-a-uuid", "cursor"), ("owner=another", "owner"), - ("top=1", "top"), + ("top=1", "query"), + ("limit=1&%74op=2", "query"), ] { let response = reqwest::get(format!( "{}/v1/proposals?accessProfile=clerk&{query}", diff --git a/crates/registry-breg/tests/postgres_proposal_messages.rs b/crates/registry-breg/tests/postgres_proposal_messages.rs index 2bfaa0a7b8..85823afed0 100644 --- a/crates/registry-breg/tests/postgres_proposal_messages.rs +++ b/crates/registry-breg/tests/postgres_proposal_messages.rs @@ -782,11 +782,12 @@ async fn the_applicant_and_the_reviewer_exchange_messages_and_an_unread_answer_i .as_str() .expect("a second page") .to_owned(); + let encoded_cursor: String = cursor.bytes().map(|byte| format!("%{byte:02X}")).collect(); let (status, _, rest) = request( &fixture, citizen(CITIZEN), "GET", - &format!("/v1/proposals/{id}/messages?accessProfile=citizen&limit=1&after={cursor}"), + &format!("/v1/proposals/{id}/messages?accessProfile=citizen&%6Cimit=%2B1&%63ursor={encoded_cursor}"), None, None, Value::Null, @@ -916,6 +917,124 @@ async fn the_owner_and_the_subject_post_and_read_and_a_neighbour_gets_not_found( fixture.finish().await; } +#[tokio::test] +async fn thread_page_faults_follow_visibility_and_are_audited() { + let fixture = fixture().await; + let id = filed( + &fixture, + citizen(CITIZEN), + "apply-for-licence", + CITIZEN, + "page-faults", + ) + .await; + let unknown = Uuid::new_v4(); + for (query, code, location) in [ + ("limit=1&%6Cimit=2", "request.invalid", "limit"), + ("limit=1&limit=2", "request.invalid", "limit"), + ("limit=%GG", "request.invalid", "limit"), + ("limit=0", "request.invalid", "limit"), + ("limit=51", "request.invalid", "limit"), + ("cursor=01", "query.cursor-invalid", "cursor"), + ("cursor=%2B1", "query.cursor-invalid", "cursor"), + ("cursor=1&%63ursor=2", "request.invalid", "cursor"), + ("cursor=opaque-canary", "query.cursor-invalid", "cursor"), + ("cursor=1&after=opaque-canary", "query.invalid", "query"), + ("cursor=1&%61fter=%GG", "query.invalid", "query"), + ("malformed-canary", "query.invalid", "query"), + ] { + let path = |id| format!("/v1/proposals/{id}/messages?{query}&accessProfile=citizen"); + let concealed = |mut body: Value| { + body.as_object_mut().unwrap().remove("traceId"); + body + }; + let (status, _, hidden) = request( + &fixture, + citizen(NEIGHBOUR), + "GET", + &path(id), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "{query}: {hidden}"); + let (status, _, missing) = request( + &fixture, + citizen(NEIGHBOUR), + "GET", + &path(unknown), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "{query}: {missing}"); + assert_eq!(hidden["code"], "resource.not-found"); + assert_eq!(concealed(hidden), concealed(missing)); + + let audit_start = fixture.audit_capture.entries().len(); + let (status, _, fault) = request( + &fixture, + citizen(CITIZEN), + "GET", + &path(id), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{query}: {fault}"); + assert_eq!(fault["code"], code, "{query}: {fault}"); + assert_eq!(fault["fieldPath"], location, "{query}: {fault}"); + assert!(!fault.to_string().contains("canary"), "{fault}"); + let entries = fixture.audit_capture.entries(); + let entries = &entries[audit_start..]; + assert!( + entries.iter().any(|entry| { + let record = &entry["record"]; + record["traceId"] == fault["traceId"] + && record["phase"] == "refusal" + && record["operationId"] == "proposals.apply-for-licence.message" + && record["selectedAccessProfile"] == "citizen" + }), + "{entries:?}" + ); + let audit = serde_json::to_string(entries).unwrap(); + assert!(!audit.contains("opaque-canary") && !audit.contains("malformed-canary")); + } + let (_, etag, _) = get(&fixture, citizen(CITIZEN), id).await; + for (suffix, location) in [("", "/text"), ("/read", "/through")] { + let (status, _, fault) = request( + &fixture, + citizen(CITIZEN), + "POST", + &format!("/v1/proposals/{id}/messages{suffix}?accessProfile=citizen"), + etag.as_deref(), + Some("missing-thread-body-member"), + json!({}), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{fault}"); + assert_eq!(fault["code"], "request.invalid", "{fault}"); + assert_eq!(fault["fieldPath"], location, "{fault}"); + } + fixture.audit_capture.fail_after(0); + let (status, _, fault) = request( + &fixture, + citizen(CITIZEN), + "GET", + &format!("/v1/proposals/{id}/messages?accessProfile=citizen&limit=1&limit=2"), + None, + None, + Value::Null, + ) + .await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{fault}"); + assert!(fault.get("fieldPath").is_none(), "{fault}"); + fixture.finish().await; +} + /// D6: an Action without review carries a thread. The office talks to the /// applicant and applies by hand; applying closes the thread for writes and /// leaves it readable. @@ -1866,6 +1985,20 @@ async fn bounded_office_staff_get_the_same_answer_for_a_hidden_proposal_and_an_u None, Value::Null, ), + ( + "GET", + format!("/v1/proposals/{target}/messages?limit=1&limit=2&accessProfile=district"), + None, + None, + Value::Null, + ), + ( + "GET", + format!("/v1/proposals/{target}/messages?cursor=%GG&accessProfile=district"), + None, + None, + Value::Null, + ), ( "POST", format!("/v1/proposals/{target}/messages/read?accessProfile=district"), diff --git a/crates/registry-breg/tests/proposal_messages_compiler.rs b/crates/registry-breg/tests/proposal_messages_compiler.rs index 3c7493de92..eb54336c90 100644 --- a/crates/registry-breg/tests/proposal_messages_compiler.rs +++ b/crates/registry-breg/tests/proposal_messages_compiler.rs @@ -226,6 +226,12 @@ fn message_openapi_describes_the_three_routes_and_their_preconditions() { let thread = &api["paths"]["/v1/proposals/{proposal_id}/messages"]; let send = &thread["post"]; assert_eq!(thread["get"]["operationId"], "proposals.list-messages"); + let parameters = thread["get"]["parameters"].as_array().unwrap(); + assert!(parameters.iter().any(|entry| entry["name"] == "cursor")); + assert!(parameters.iter().all(|entry| entry["name"] != "after")); + assert!(thread["get"] + .pointer("/responses/400/content/application~1problem+json/examples/query.invalid") + .is_some()); assert_eq!(send["operationId"], "proposals.message"); for header in ["If-Match", "Idempotency-Key"] { assert!(send["parameters"].as_array().unwrap().iter().any(|entry| { diff --git a/crates/registry-breg/tests/support/proposal_additions.rs b/crates/registry-breg/tests/support/proposal_additions.rs index 3d2c69d096..4a29b11cd7 100644 --- a/crates/registry-breg/tests/support/proposal_additions.rs +++ b/crates/registry-breg/tests/support/proposal_additions.rs @@ -1015,7 +1015,9 @@ async fn adding_a_form_entry_preserves_the_submission_and_fences_replay_and_limi for (input, field) in [ (json!({}), "/input/householdSize"), (json!({"householdSize":"four"}), "/input/householdSize"), - (json!({"householdSize":4,"unknown":true}), "/input/unknown"), + (json!({"householdSize":4,"unknownCanary":true}), "/input"), + (json!({"householdSize":4,"unknown/canary":true}), "/input"), + (json!(["malformed-canary"]), "/input"), ] { let response = add(Some(etag), "invalid-form", input).await.unwrap(); assert_eq!(response.status(), 400); @@ -1023,6 +1025,35 @@ async fn adding_a_form_entry_preserves_the_submission_and_fences_replay_and_limi assert_eq!(problem["code"], "request.invalid", "{problem}"); assert_eq!(problem["fieldPath"], field, "{problem}"); } + for (body, location) in [ + (json!({}), Some("/input")), + (json!({"input":null}), Some("/input")), + ( + json!({"input":{"householdSize":4},"extraCanary":true}), + None, + ), + ] { + let response = http + .post(&url) + .header("if-match", etag) + .header("idempotency-key", "malformed-form-envelope") + .json(&body) + .send() + .await + .unwrap(); + assert_eq!(response.status(), 400); + let problem: Value = response.json().await.unwrap(); + assert_eq!(problem["code"], "request.invalid", "{problem}"); + assert_eq!( + problem.get("fieldPath").and_then(Value::as_str), + location, + "{problem}" + ); + if location.is_none() { + assert!(problem.get("fieldPath").is_none(), "{problem}"); + assert!(!problem.to_string().contains("extraCanary"), "{problem}"); + } + } let input = json!({"householdSize":4}); let missing = add(None, "missing-if-match", input.clone()).await.unwrap(); assert_eq!(missing.status(), 428); diff --git a/crates/registry-breg/tests/support/proposal_review_asks.rs b/crates/registry-breg/tests/support/proposal_review_asks.rs index 1392ac90af..3f7290017b 100644 --- a/crates/registry-breg/tests/support/proposal_review_asks.rs +++ b/crates/registry-breg/tests/support/proposal_review_asks.rs @@ -3135,9 +3135,44 @@ async fn a_form_want_discloses_only_the_cited_entry_in_live_review_context() { } let answer_path = format!("{path}/asks/{ask}/answer"); + let mut concealed = Vec::new(); + for target in [id, Uuid::new_v4()] { + let (status, _, mut problem) = request_as( + &fixture, + caller_claims("other-applicant", registry_platform_oidc::ActorKind::Human), + "POST", + &format!("/v1/proposals/{target}/asks/{ask}/answer"), + Some(&etag), + Some("hidden-form-answer"), + json!({"formEntries":"malformed-canary"}), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "{problem}"); + assert_eq!(problem["code"], "resource.not-found", "{problem}"); + problem.as_object_mut().unwrap().remove("traceId"); + concealed.push(problem); + } + assert_eq!(concealed[0], concealed[1]); + for text in [json!(null), json!(false), json!(1), json!([]), json!({})] { + let (status, _, problem) = request( + &fixture, + "POST", + &answer_path, + Some(&etag), + Some("answer-malformed-text"), + json!({"text":text,"formEntries":[entries[2]]}), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{problem}"); + assert_eq!(problem["code"], "request.invalid", "{problem}"); + assert_eq!(problem["fieldPath"], "/text", "{problem}"); + } for (key, cited) in [ ("missing-form", json!([])), ("answer-wrong-form", json!([entries[0]])), + ("answer-form-wrong-type", json!("malformed-canary")), + ("answer-form-wrong-id-type", json!([false])), + ("answer-form-malformed-id", json!(["malformed-canary"])), ] { let (status, _, problem) = request( &fixture, From fc231dc54e48419236424d2f8b5ced3042141605 Mon Sep 17 00:00:00 2001 From: Jeremi Joslin Date: Thu, 3 Dec 2026 01:44:39 +0000 Subject: [PATCH 3/9] fix(breg): admit native reads before refusing retired paging Signed-off-by: Jeremi Joslin --- crates/registry-breg-client/src/geojson.rs | 15 +- crates/registry-breg-client/src/query.rs | 6 +- .../registry-breg/src/api/external_views.rs | 13 +- crates/registry-breg/src/api/gis.rs | 29 +- crates/registry-breg/src/api/mod.rs | 143 ++++++++- crates/registry-breg/src/cursor.rs | 9 +- .../src/postgres/external_runtime.rs | 85 ++++- crates/registry-breg/src/query.rs | 107 +++---- .../registry-breg/tests/disclosure/history.rs | 4 +- crates/registry-breg/tests/http_read_only.rs | 291 ++++++++++++++++-- .../tests/postgres_access_log.rs | 52 +++- .../tests/postgres_consent_access.rs | 16 +- .../tests/postgres_historical.rs | 10 +- .../tests/postgres_list_page_plans.rs | 6 +- .../tests/postgres_membership_access.rs | 10 +- .../registry-breg/tests/postgres_mutation.rs | 4 +- crates/registry-breg/tests/postgres_read.rs | 98 ++++-- .../tests/postgres_read_dependencies.rs | 6 +- .../tests/postgres_required_filters.rs | 6 +- .../tests/postgres_spatial_read.rs | 79 +++-- .../tests/postgres_statistics_http.rs | 2 +- .../tests/postgres_statistics_stock.rs | 4 +- products/breg/loadtest/support/loadenv.py | 2 +- .../breg/loadtest/support/test_harness.py | 2 +- .../breg/quickstart/support/quickstart.py | 4 +- .../scripts/test_check_client_capabilities.py | 2 +- products/platform/CONFIG-CONVENTIONS.md | 1 - 27 files changed, 802 insertions(+), 204 deletions(-) diff --git a/crates/registry-breg-client/src/geojson.rs b/crates/registry-breg-client/src/geojson.rs index cbce43fb39..06afc7c01d 100644 --- a/crates/registry-breg-client/src/geojson.rs +++ b/crates/registry-breg-client/src/geojson.rs @@ -227,7 +227,6 @@ pub struct BRegGeoJsonPage { #[serde(deny_unknown_fields, rename_all = "camelCase")] pub struct BRegGeoJsonContinuationProjection { pub route: String, - #[serde(alias = "skiptoken")] pub cursor: String, #[serde(skip_serializing_if = "Option::is_none")] pub access_profile: Option, @@ -581,6 +580,20 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn retired_saved_geojson_cursor_name_is_refused() { + let saved = json!({"route": "assets", "cursor": "opaque", "accessProfile": "reader"}); + let continuation = + serde_json::from_value::(saved.clone()).unwrap(); + assert_eq!(serde_json::to_value(continuation).unwrap(), saved); + for retired in [ + json!({"route": "assets", "skiptoken": "opaque"}), + json!({"route": "assets", "cursor": "opaque", "skiptoken": "opaque"}), + ] { + assert!(serde_json::from_value::(retired).is_err()); + } + } + #[test] fn feature_preserves_null_geometry_and_has_no_mutation_metadata() { let feature = decode_feature(json!({ diff --git a/crates/registry-breg-client/src/query.rs b/crates/registry-breg-client/src/query.rs index ca392aaede..477e7bd2b2 100644 --- a/crates/registry-breg-client/src/query.rs +++ b/crates/registry-breg-client/src/query.rs @@ -454,7 +454,6 @@ pub struct BRegContinuationProjection { /// Logical Base Registry Engine record route segment. pub route: String, /// Opaque Base Registry Engine `cursor`. - #[serde(alias = "skiptoken")] pub cursor: String, /// Representation selected for the original page. pub format: BRegRecordFormat, @@ -1222,10 +1221,7 @@ mod tests { let fields = legacy.as_object_mut().unwrap(); let cursor = fields.remove("cursor").unwrap(); fields.insert("skiptoken".to_owned(), cursor.clone()); - assert_eq!( - serde_json::from_value::(legacy.clone()).unwrap(), - continuation - ); + assert!(serde_json::from_value::(legacy.clone()).is_err()); legacy["cursor"] = cursor; assert!(serde_json::from_value::(legacy).is_err()); } diff --git a/crates/registry-breg/src/api/external_views.rs b/crates/registry-breg/src/api/external_views.rs index 05b4610a7d..0ae6a6409e 100644 --- a/crates/registry-breg/src/api/external_views.rs +++ b/crates/registry-breg/src/api/external_views.rs @@ -564,7 +564,15 @@ async fn handle( } else { Operation::List }; - let profile_selection = admission_profile(raw.as_deref()); + let retired_paging = has_retired_page_parameter(raw.as_deref()); + let profile_selection = if retired_paging { + match retired_page_admission_profile(raw.as_deref()) { + Ok(selection) => selection, + Err(_) => return concealed(FailedCheck::AccessProfile), + } + } else { + admission_profile(raw.as_deref()) + }; let context = match root_context( service, view, @@ -612,6 +620,9 @@ async fn handle( }, None => None, }; + if retired_paging { + return invalid_query_at("query"); + } let options = match QueryOptions::parse(raw.as_deref(), true) { Ok(value) => value, Err(error) => return error.problem(), diff --git a/crates/registry-breg/src/api/gis.rs b/crates/registry-breg/src/api/gis.rs index e8566a4117..663f5bbbea 100644 --- a/crates/registry-breg/src/api/gis.rs +++ b/crates/registry-breg/src/api/gis.rs @@ -19,10 +19,10 @@ use serde_json::{json, Map, Value}; use super::{ audited_read_concealment, audited_read_refusal, authorize_route_with_reason, concealed, - data_field_type, exact_non_record_no_store, invalid_query, percent_decode, - profile_not_authorized, read_query, unavailable, Authenticated, AuthorizedSurface, HttpService, - QueryOptions, QueryParseError, ReadQueryError, RecordReadKind, RecordReadRequest, - VerifiedRequestClaims, MAX_RAW_QUERY_BYTES, + data_field_type, exact_non_record_no_store, has_retired_page_parameter, invalid_query, + percent_decode, profile_not_authorized, read_query, unavailable, Authenticated, + AuthorizedSurface, HttpService, QueryOptions, QueryParseError, ReadQueryError, RecordReadKind, + RecordReadRequest, VerifiedRequestClaims, MAX_RAW_QUERY_BYTES, }; use crate::audit::ReadRefusalReason; use crate::contract::{FieldTypeSource, Operation}; @@ -304,17 +304,16 @@ async fn items( ) .await; } - // The feature surface speaks its own parameter names, so a refusal here - // stays unlocated rather than naming a native query parameter. + // GIS query errors use the feature surface's parameter contract. let query = match parse_items_query(raw_query.as_deref()) { Ok(query) => query, - Err(QueryParseError::Invalid | QueryParseError::InvalidAt(_)) => { + Err(error) => { return audited_read_refusal( &service, authorized.route, &authorized.surface, None, - invalid_query(), + error.problem(), &correlation, ) .await; @@ -760,6 +759,9 @@ fn parse_items_query(raw: Option<&str>) -> Result MAX_RAW_QUERY_BYTES { return Err(QueryParseError::Invalid); } + if has_retired_page_parameter(Some(raw)) { + return Err(QueryParseError::InvalidAt("query")); + } let pairs = decode_query_pairs(raw)?; let mut seen = BTreeSet::new(); let mut query = GisItemsQuery::default(); @@ -947,9 +949,16 @@ mod tests { assert_eq!(query.limit, Some(1000)); assert_eq!(query.cursor, None); - for raw in ["%24top=2", "%24skiptoken=opaque", "limit=2&limit=2"] { - assert_eq!(parse_items_query(Some(raw)), Err(QueryParseError::Invalid)); + for raw in ["%24top=2", "%24skiptoken=opaque"] { + assert_eq!( + parse_items_query(Some(raw)), + Err(QueryParseError::InvalidAt("query")) + ); } + assert_eq!( + parse_items_query(Some("limit=2&limit=2")), + Err(QueryParseError::Invalid) + ); assert_eq!( parse_items_query(Some("cursor=opaque&bbox=100,13,101,14")), Err(QueryParseError::Invalid) diff --git a/crates/registry-breg/src/api/mod.rs b/crates/registry-breg/src/api/mod.rs index 0a793c8d39..704ed7d13f 100644 --- a/crates/registry-breg/src/api/mod.rs +++ b/crates/registry-breg/src/api/mod.rs @@ -1009,8 +1009,26 @@ async fn read_dispatch( headers: HeaderMap, Path(path): Path>, ) -> Response { - let options = match QueryOptions::parse(raw_query.as_deref(), true) { + let retired_paging = has_retired_page_parameter(raw_query.as_deref()); + let parsed = if retired_paging { + QueryOptions::for_admission(raw_query.as_deref()) + } else { + QueryOptions::parse(raw_query.as_deref(), true) + }; + let options = match parsed { Ok(options) => options, + Err(_) if retired_paging => { + return audited_read_concealment( + &service, + &route, + &QueryOptions::default(), + &claims, + path.get("record_id"), + &correlation, + RouteRefusal::admission_check(FailedCheck::AccessProfile), + ) + .await; + } Err(error) => { return audited_known_read_refusal( &service, @@ -1129,6 +1147,17 @@ async fn read_dispatch( ) .await; } + if retired_paging { + return audited_read_refusal( + &service, + &route, + &surface, + Some(record_id), + invalid_query_at("query"), + &correlation, + ) + .await; + } let request = RecordReadRequest { entity_id: route.entity_id.clone(), operation_id: route.id.clone(), @@ -1175,6 +1204,24 @@ async fn read_dispatch( ) .await; } + if retired_paging { + let response = if representation == CursorRepresentation::GeoJson + && !geojson_available(&surface) + { + profile_not_authorized(FailedCheck::Disclosure) + } else { + invalid_query_at("query") + }; + return audited_read_refusal( + &service, + &route, + &surface, + path.get("record_id"), + response, + &correlation, + ) + .await; + } let query = match read_query( &service, &route, @@ -1298,8 +1345,26 @@ async fn lookup_dispatch( headers: HeaderMap, body: Body, ) -> Response { - let options = match QueryOptions::parse(raw_query.as_deref(), true) { + let retired_paging = has_retired_page_parameter(raw_query.as_deref()); + let parsed = if retired_paging { + QueryOptions::for_admission(raw_query.as_deref()) + } else { + QueryOptions::parse(raw_query.as_deref(), true) + }; + let options = match parsed { Ok(options) => options, + Err(_) if retired_paging => { + return audited_read_concealment( + &service, + &route, + &QueryOptions::default(), + &claims, + None, + &correlation, + RouteRefusal::admission_check(FailedCheck::AccessProfile), + ) + .await; + } Err(error) => { return audited_known_read_refusal( &service, @@ -1347,6 +1412,17 @@ async fn lookup_dispatch( if let Some(refusal) = field_encryption_refusal(&service, surface.entity) { return refusal; } + if retired_paging { + return audited_read_refusal( + &service, + &route, + &surface, + None, + invalid_query_at("query"), + &correlation, + ) + .await; + } if surface.read_path.is_some() || options.has_non_projection_query_members() { return audited_read_refusal( &service, @@ -1731,7 +1807,13 @@ async fn snapshot_dispatch( let Some(snapshots) = &service.snapshots else { return concealed(FailedCheck::Visibility); }; - let options = match QueryOptions::parse_snapshot(raw_query.as_deref()) { + let retired_paging = has_retired_page_parameter(raw_query.as_deref()); + let parsed = if retired_paging { + QueryOptions::for_admission(raw_query.as_deref()) + } else { + QueryOptions::parse_snapshot(raw_query.as_deref()) + }; + let options = match parsed { Ok(options) => options, Err(_) => { return audited_known_read_refusal( @@ -1780,6 +1862,17 @@ async fn snapshot_dispatch( if let Some(refusal) = field_encryption_refusal(&service, surface.entity) { return refusal; } + if retired_paging { + return audited_read_refusal( + &service, + &route, + &surface, + None, + invalid_query_at("query"), + &correlation, + ) + .await; + } let query = match read_query( &service, &route, @@ -5267,6 +5360,12 @@ struct HistoricalQueryOptions { } impl QueryOptions { + fn for_admission(raw: Option<&str>) -> Result { + let mut options = Self::default(); + options.parsed.access_profile = retired_page_admission_profile(raw)?; + Ok(options) + } + fn parse(raw: Option<&str>, allow_read_query: bool) -> Result { let Some(raw) = raw else { return Ok(Self::default()); @@ -5478,6 +5577,44 @@ impl ReadQueryError { } } +/// Detect retired page names independently of other query faults. Ignore +/// values here so aliases remain identifiable alongside malformed input. +fn has_retired_page_parameter(raw: Option<&str>) -> bool { + raw.filter(|raw| raw.len() <= MAX_RAW_QUERY_BYTES) + .is_some_and(|raw| { + raw.split('&').any(|pair| { + let name = pair.split_once('=').map_or(pair, |(name, _)| name); + matches!( + percent_decode(name).ok().as_deref(), + Some("$top" | "$skiptoken") + ) + }) + }) +} + +/// Read the explicit selector without allowing a malformed or repeated +/// selector to fall back to default profile selection. +fn retired_page_admission_profile(raw: Option<&str>) -> Result, QueryParseError> { + let Some(raw) = raw else { return Ok(None) }; + if raw.len() > MAX_RAW_QUERY_BYTES { + return Err(QueryParseError::Invalid); + } + let mut selected = None; + for pair in raw.split('&') { + let (name, value) = pair + .split_once('=') + .map_or((pair, None), |(name, value)| (name, Some(value))); + if percent_decode(name).ok().as_deref() != Some("accessProfile") { + continue; + } + let value = percent_decode(value.ok_or(QueryParseError::Invalid)?)?; + if !strict_query::valid_config_identifier(&value) || selected.replace(value).is_some() { + return Err(QueryParseError::Invalid); + } + } + Ok(selected) +} + /// Extract only the selector needed for admission. Full validation follows /// authorization, so malformed options cannot reveal an inaccessible target. fn admission_profile(raw: Option<&str>) -> Option { diff --git a/crates/registry-breg/src/cursor.rs b/crates/registry-breg/src/cursor.rs index 6c836f67d4..ae50cef932 100644 --- a/crates/registry-breg/src/cursor.rs +++ b/crates/registry-breg/src/cursor.rs @@ -707,7 +707,7 @@ mod tests { assert_eq!(token.len(), MAX_TOKEN_BYTES); assert_eq!(token.len(), crate::query::MAX_CURSOR_TOKEN_BYTES); assert!(codec.decode(&token, 1_001).is_ok()); - assert!(crate::query::parse_read_query([("$skiptoken", token.as_str())]).is_ok()); + assert!(crate::query::parse_read_query([("cursor", token.as_str())]).is_ok()); assert!(registry_breg_client::BRegContinuation::try_from_projection( registry_breg_client::BRegContinuationProjection { route: "assets".to_owned(), @@ -909,6 +909,13 @@ mod tests { let wire = URL_SAFE_NO_PAD.decode(token).expect("golden is base64url"); assert_eq!(wire[0], WIRE_VERSION); assert_eq!(wire[1..=NONCE_BYTES], [nonce; NONCE_BYTES]); + let query = crate::query::parse_read_query([("cursor", token)]) + .expect("preexisting cursor can be carried by the canonical parameter"); + assert!(matches!( + query.mode, + crate::query::ParsedReadQueryMode::SkipToken { token: parsed } if parsed == token + )); + assert!(crate::query::parse_read_query([("$skiptoken", token)]).is_err()); assert_eq!(codec.decode(token, 1_001).expect("golden opens"), payload()); } } diff --git a/crates/registry-breg/src/postgres/external_runtime.rs b/crates/registry-breg/src/postgres/external_runtime.rs index 738f449715..b36e2beb19 100644 --- a/crates/registry-breg/src/postgres/external_runtime.rs +++ b/crates/registry-breg/src/postgres/external_runtime.rs @@ -3124,12 +3124,71 @@ mod postgres_tests { } } + #[tokio::test] + async fn retired_external_paging_is_disclosed_only_for_admitted_views() { + use axum::http::StatusCode; + + let served = Served::new(Duration::from_secs(2)).await; + served.publish_all().await; + let caller = reader("reader-principal", &["allowed"]); + let (status, page) = served.get("&limit=1", caller.clone()).await; + assert_eq!(status, StatusCode::OK, "{page}"); + let cursor = page["nextCursor"].as_str().unwrap(); + let (status, page) = served + .get(&format!("&cursor={cursor}"), caller.clone()) + .await; + assert_eq!(status, StatusCode::OK, "{page}"); + + for query in [ + "&$top=1".to_owned(), + "&limit=1&%24top=private-canary".to_owned(), + format!("&%24skiptoken={cursor}"), + "&$skiptoken=one&$skiptoken=two".to_owned(), + ] { + let (status, problem) = served.get(&query, caller.clone()).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{query}"); + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + assert!(!problem.to_string().contains("private-canary")); + let (status, _, problem) = served + .send( + &format!("/v1/external-views/view/link/records?accessProfile=unknown{query}"), + caller.clone(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND, "{problem}"); + assert_ne!(problem["code"], "query.invalid"); + } + for selection in [ + "", + "&accessProfile", + "&%61ccessProfile=%ff", + "&accessProfile=", + "&accessProfile=reader&%61ccessProfile=reader", + ] { + let (status, _, problem) = served + .send( + &format!("/v1/external-views/view/link/records?%24top=1{selection}"), + caller.clone(), + ) + .await; + if selection.is_empty() { + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(problem["fieldPath"], "query"); + } else { + assert_eq!(status, StatusCode::NOT_FOUND, "{selection}"); + assert_eq!(problem["code"], "resource.not-found"); + } + } + served.fixture.cleanup().await; + } + #[tokio::test] async fn a_scope_lock_timeout_is_unavailable_never_incomplete_or_an_invalid_cursor() { let served = Served::new(Duration::from_millis(300)).await; served.publish_all().await; let caller = reader("reader-principal", &["allowed"]); - let (status, first) = served.get("&$top=1", caller.clone()).await; + let (status, first) = served.get("&limit=1", caller.clone()).await; assert_eq!(status, axum::http::StatusCode::OK, "{first}"); let cursor = first["nextCursor"].as_str().unwrap().to_owned(); @@ -3144,11 +3203,11 @@ mod postgres_tests { ) .await .unwrap(); - let (status, problem) = served.get("&$top=1", caller.clone()).await; + let (status, problem) = served.get("&limit=1", caller.clone()).await; assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE); assert_eq!(problem["code"], "source.unavailable", "{problem}"); let (status, problem) = served - .get(&format!("&$skiptoken={cursor}"), caller.clone()) + .get(&format!("&cursor={cursor}"), caller.clone()) .await; assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE); assert_eq!(problem["code"], "source.unavailable", "{problem}"); @@ -3160,7 +3219,7 @@ mod postgres_tests { .await .unwrap(); - let (status, next) = served.get(&format!("&$skiptoken={cursor}"), caller).await; + let (status, next) = served.get(&format!("&cursor={cursor}"), caller).await; assert_eq!(status, axum::http::StatusCode::OK, "{next}"); assert_eq!(labels(&next).len(), 1); served.fixture.cleanup().await; @@ -3171,7 +3230,7 @@ mod postgres_tests { let served = Served::new(Duration::from_secs(2)).await; served.publish_all().await; let caller = reader("reader-principal", &["allowed"]); - let ordered = "&$top=1&$orderby=label%20asc&$count=true"; + let ordered = "&limit=1&$orderby=label%20asc&$count=true"; let (status, first) = served.get(ordered, caller.clone()).await; assert_eq!(status, axum::http::StatusCode::OK, "{first}"); assert_eq!(labels(&first), ["first"]); @@ -3185,13 +3244,13 @@ mod postgres_tests { .publish_label(&served.scope, "third", "thirdly") .await; let (status, second) = served - .get(&format!("&$skiptoken={cursor}"), caller.clone()) + .get(&format!("&cursor={cursor}"), caller.clone()) .await; assert_eq!(status, axum::http::StatusCode::OK, "{second}"); assert_eq!(labels(&second), ["second"]); assert_eq!(second["count"], 3); let cursor = second["nextCursor"].as_str().unwrap().to_owned(); - let (status, third) = served.get(&format!("&$skiptoken={cursor}"), caller).await; + let (status, third) = served.get(&format!("&cursor={cursor}"), caller).await; assert_eq!(status, axum::http::StatusCode::OK, "{third}"); assert_eq!(labels(&third), ["thirdly"]); assert!(third.get("nextCursor").is_none()); @@ -3304,12 +3363,12 @@ mod postgres_tests { // A continuation of a plain list is as plain as its first page. let mut seen = BTreeMap::new(); - let (status, first) = served.get("&$top=2", caller.clone()).await; + let (status, first) = served.get("&limit=2", caller.clone()).await; assert_eq!(status, axum::http::StatusCode::OK, "{first}"); seen.extend(availabilities(&first)); let cursor = first["nextCursor"].as_str().unwrap().to_owned(); let (status, second) = served - .get(&format!("&$skiptoken={cursor}"), caller.clone()) + .get(&format!("&cursor={cursor}"), caller.clone()) .await; assert_eq!(status, axum::http::StatusCode::OK, "{second}"); assert_eq!(second["status"], "unavailable", "{second}"); @@ -3468,7 +3527,7 @@ mod postgres_tests { let served = Served::new(Duration::from_secs(2)).await; served.publish_all().await; let (status, first) = served - .get("&$top=1", reader("reader-principal", &["allowed"])) + .get("&limit=1", reader("reader-principal", &["allowed"])) .await; assert_eq!(status, axum::http::StatusCode::OK, "{first}"); let cursor = first["nextCursor"].as_str().unwrap().to_owned(); @@ -3482,7 +3541,7 @@ mod postgres_tests { "another row boundary", ), ] { - let (status, problem) = served.get(&format!("&$skiptoken={cursor}"), caller).await; + let (status, problem) = served.get(&format!("&cursor={cursor}"), caller).await; assert_eq!( status, axum::http::StatusCode::BAD_REQUEST, @@ -3495,7 +3554,7 @@ mod postgres_tests { } let (status, next) = served .get( - &format!("&$skiptoken={cursor}"), + &format!("&cursor={cursor}"), reader("reader-principal", &["allowed"]), ) .await; @@ -4860,7 +4919,7 @@ mod postgres_tests { ), (root_refresh(ROOTS[3].0, "desk"), desk_client()), ( - format!("{}&$top=1", root_refresh(ROOTS[0].0, "desk")), + format!("{}&limit=1", root_refresh(ROOTS[0].0, "desk")), desk_client(), ), ] { diff --git a/crates/registry-breg/src/query.rs b/crates/registry-breg/src/query.rs index e962e604e1..b6aafeafc3 100644 --- a/crates/registry-breg/src/query.rs +++ b/crates/registry-breg/src/query.rs @@ -623,13 +623,11 @@ where } /// The fixed query parameter names a refusal may name as its location. -pub const QUERY_PARAMETERS: [&str; 13] = [ +pub const QUERY_PARAMETERS: [&str; 11] = [ "$select", "$filter", "$orderby", - "$top", "$count", - "$skiptoken", "bbox", "accessProfile", "asOf", @@ -741,7 +739,7 @@ struct QueryBuilder { top: Option, count: Option, bbox: Option, - skiptoken: Option<(String, &'static str)>, + skiptoken: Option, } impl QueryBuilder { @@ -770,7 +768,7 @@ impl QueryBuilder { ensure_absent(self.orderby.is_none())?; self.orderby = Some(parse_orderby(value)?); } - "limit" | "$top" => { + "limit" => { ensure_absent(self.top.is_none())?; self.top = Some(parse_top(value)?); } @@ -782,14 +780,9 @@ impl QueryBuilder { ensure_absent(self.bbox.is_none())?; self.bbox = Some(parse_bbox(value)?); } - "cursor" | "$skiptoken" => { + "cursor" => { ensure_absent(self.skiptoken.is_none())?; - let name = if key == "cursor" { - "cursor" - } else { - "$skiptoken" - }; - self.skiptoken = Some((parse_opaque_value(value, MAX_CURSOR_TOKEN_BYTES)?, name)); + self.skiptoken = Some(parse_opaque_value(value, MAX_CURSOR_TOKEN_BYTES)?); } "fields" | "filter" | "sort" | "pageSize" | "$skip" | "$apply" | "$expand" | "$batch" => { @@ -804,7 +797,7 @@ impl QueryBuilder { } fn cursor_parameter(&self) -> Option<&'static str> { - self.skiptoken.as_ref().map(|(_, parameter)| *parameter) + self.skiptoken.as_ref().map(|_| "cursor") } /// A continuation carries its whole query, so a conflict names the @@ -824,7 +817,7 @@ impl QueryBuilder { bbox: self.bbox, }; let mode = match self.skiptoken { - Some((token, _)) => { + Some(token) => { if self.as_of.is_some() || options.has_any_option() { return Err(QueryParseError::ConflictingOptions); } @@ -1825,7 +1818,7 @@ mod tests { ("$select", "case-code,status"), ("$filter", "status eq 'open'"), ("$orderby", "opened-on desc"), - ("$top", "50"), + ("limit", "50"), ("$count", "false"), ]) .expect("query parses"); @@ -1901,27 +1894,36 @@ mod tests { ); } assert_eq!( - parse([("$top", "10"), ("$top", "11")]), + parse([("limit", "10"), ("limit", "11")]), Err(QueryParseError::DuplicateOption) ); } #[test] - fn pagination_names_share_query_and_cursor_rules() { - assert_eq!(parse([("limit", "10")]), parse([("$top", "10")])); - assert_eq!( - parse([("accessProfile", "reader"), ("cursor", "opaque-token")]), - parse([("accessProfile", "reader"), ("$skiptoken", "opaque-token"),]) - ); - for (parameters, duplicate) in [ - ([("$top", "10"), ("limit", "10")], "limit"), - ([("limit", "10"), ("$top", "10")], "$top"), - ([("$skiptoken", "same"), ("cursor", "same")], "cursor"), - ([("cursor", "same"), ("$skiptoken", "same")], "$skiptoken"), + fn retired_page_names_have_no_public_parameter_location() { + for (alias, value) in [("$top", "10"), ("$skiptoken", "opaque")] { + assert_eq!( + parse_read_query_located([(alias, value)]).unwrap_err().1, + None + ); + assert_eq!( + parse_snapshot_query_located([(alias, value)]) + .unwrap_err() + .1, + None + ); + } + } + + #[test] + fn canonical_page_names_keep_their_fault_locations() { + for (parameters, member) in [ + ([("limit", "10"), ("limit", "11")], "limit"), + ([("cursor", "same"), ("cursor", "same")], "cursor"), ] { assert_eq!( parse_read_query_located(parameters), - Err((QueryParseError::DuplicateOption, Some(duplicate))) + Err((QueryParseError::DuplicateOption, Some(member))) ); } assert_eq!( @@ -1932,18 +1934,16 @@ mod tests { parse_read_query_located([("cursor", "opaque-token"), ("limit", "10")]), Err((QueryParseError::ConflictingOptions, Some("cursor"))) ); - for key in ["cursor", "$skiptoken"] { - assert_eq!( - parse_snapshot_query_located([(key, "opaque-token"), ("validAt", "later")]), - Err((QueryParseError::ConflictingOptions, Some(key))) - ); - } + assert_eq!( + parse_snapshot_query_located([("cursor", "opaque-token"), ("validAt", "later")]), + Err((QueryParseError::ConflictingOptions, Some("cursor"))) + ); } #[test] - fn skiptoken_only_allows_access_profile() { - let query = parse([("accessProfile", "reader"), ("$skiptoken", "opaque-token")]) - .expect("skiptoken query parses"); + fn cursor_only_allows_access_profile() { + let query = parse([("accessProfile", "reader"), ("cursor", "opaque-token")]) + .expect("cursor query parses"); assert!(matches!(query.mode, ParsedReadQueryMode::SkipToken { .. })); for pair in [ @@ -1951,11 +1951,11 @@ mod tests { ("$select", "field"), ("$filter", "field eq 'value'"), ("$orderby", "field"), - ("$top", "10"), + ("limit", "10"), ("$count", "true"), ] { assert_eq!( - parse([("$skiptoken", "opaque-token"), pair]), + parse([("cursor", "opaque-token"), pair]), Err(QueryParseError::ConflictingOptions) ); } @@ -1963,16 +1963,19 @@ mod tests { #[test] fn top_and_count_are_strict() { - assert!(parse([("$top", "1")]) + assert!(parse([("limit", "1")]) .unwrap() .canonical() .contains("top=1")); - assert!(parse([("$top", "100")]) + assert!(parse([("limit", "100")]) .unwrap() .canonical() .contains("top=100")); for value in ["", "0", "101", "-1", "1.0", "+1", "true"] { - assert_eq!(parse([("$top", value)]), Err(QueryParseError::InvalidValue)); + assert_eq!( + parse([("limit", value)]), + Err(QueryParseError::InvalidValue) + ); } assert!(parse([("$count", "true")]) .unwrap() @@ -2162,8 +2165,8 @@ mod tests { ); let token = "a".repeat(MAX_CURSOR_TOKEN_BYTES); - assert!(parse_read_query([("$skiptoken", token.as_str())]).is_ok()); - assert!(parse_snapshot_query([("$skiptoken", token.as_str())]).is_ok()); + assert!(parse_read_query([("cursor", token.as_str())]).is_ok()); + assert!(parse_snapshot_query([("cursor", token.as_str())]).is_ok()); assert!(parse_snapshot_query([("snapshot", "a".repeat(MAX_OPAQUE_VALUE_BYTES))]).is_ok()); assert_eq!( parse_snapshot_query([("snapshot", token.as_str())]), @@ -2171,7 +2174,7 @@ mod tests { ); let large_token = "a".repeat(MAX_CURSOR_TOKEN_BYTES + 1); assert_eq!( - parse_read_query([("$skiptoken", large_token.as_str())]), + parse_read_query([("cursor", large_token.as_str())]), Err(QueryParseError::InvalidValue) ); } @@ -2233,7 +2236,7 @@ mod tests { #[test] fn bbox_conflicts_with_skiptoken_and_is_value_free_in_debug() { assert_eq!( - parse([("$skiptoken", "cursor-canary"), ("bbox", "0,0,1,1")]), + parse([("cursor", "cursor-canary"), ("bbox", "0,0,1,1")]), Err(QueryParseError::ConflictingOptions) ); let parsed = parse([("bbox", "100.1,10.2,100.3,10.4")]).expect("bbox parses"); @@ -2315,7 +2318,7 @@ mod tests { ("$select", "household_id,valid_from"), ("$filter", "status eq 'active'"), ("$orderby", "valid_from"), - ("$top", "20"), + ("limit", "20"), ("$count", "true"), ]) .expect("snapshot query syntax"); @@ -2344,20 +2347,20 @@ mod tests { fn snapshot_continuations_cannot_override_the_bound_query() { assert!(parse_snapshot_query([ ("accessProfile", "caseworker"), - ("$skiptoken", "cursor-canary"), + ("cursor", "cursor-canary"), ]) .is_ok()); for key in [ - "snapshot", "validAt", "$select", "$filter", "$orderby", "$top", "$count", + "snapshot", "validAt", "$select", "$filter", "$orderby", "limit", "$count", ] { let value = match key { "$filter" => "field eq 'value'", - "$top" => "10", + "limit" => "10", "$count" => "true", _ => "value", }; assert_eq!( - parse_snapshot_query([("$skiptoken", "cursor-canary"), (key, value)]), + parse_snapshot_query([("cursor", "cursor-canary"), (key, value)]), Err(QueryParseError::ConflictingOptions) ); } @@ -2411,7 +2414,7 @@ mod tests { assert!(!debug.contains("secret")); assert!(!debug.contains("literal-canary")); - let cursor = parse([("$skiptoken", "cursor-canary")]).expect("cursor query parses"); + let cursor = parse([("cursor", "cursor-canary")]).expect("cursor query parses"); assert!(!format!("{cursor:?}").contains("cursor-canary")); } diff --git a/crates/registry-breg/tests/disclosure/history.rs b/crates/registry-breg/tests/disclosure/history.rs index 827eb15c02..fb02bb846b 100644 --- a/crates/registry-breg/tests/disclosure/history.rs +++ b/crates/registry-breg/tests/disclosure/history.rs @@ -306,7 +306,7 @@ impl History { async fn snapshot(&self, route: &str, profile: &str) -> Reply { self.get( - &format!("/v1/records/{route}:snapshot?$count=true&$top=100"), + &format!("/v1/records/{route}:snapshot?$count=true&limit=100"), profile, ) .await @@ -866,7 +866,7 @@ async fn an_old_snapshot_reference_does_not_read_a_record_marked_since() { history .get( &format!( - "/v1/records/{route}:snapshot?$count=true&$top=100&snapshot={reference}" + "/v1/records/{route}:snapshot?$count=true&limit=100&snapshot={reference}" ), REGISTRAR, ) diff --git a/crates/registry-breg/tests/http_read_only.rs b/crates/registry-breg/tests/http_read_only.rs index eb555471c8..29fbb52590 100644 --- a/crates/registry-breg/tests/http_read_only.rs +++ b/crates/registry-breg/tests/http_read_only.rs @@ -725,7 +725,7 @@ async fn snapshot_route_requires_its_own_current_authority_and_never_calls_live_ } assert!(snapshots.requests.lock().unwrap().is_empty()); let response = send_to(&app, Method::GET, - "/v1/records/assignments:snapshot?validAt=2026-06-05&$select=label&$filter=label%20eq%20'A'&$top=3&$count=true", + "/v1/records/assignments:snapshot?validAt=2026-06-05&$select=label&$filter=label%20eq%20'A'&limit=3&$count=true", Some(caseworker_claims("case-management"))).await; assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.headers()["cache-control"], "no-store"); @@ -913,6 +913,179 @@ async fn snapshot_validity_is_typed_optional_and_has_no_clock_default() { assert!(snapshots.requests.lock().unwrap().is_empty()); } +#[tokio::test] +async fn retired_snapshot_paging_is_disclosed_only_to_the_selected_profile() { + let (app, records, snapshots) = snapshot_harness(SNAPSHOT_PROJECT, &[]); + for query in [ + "$top=1", + "%24top=private-canary&limit=1", + "cursor=opaque&%24skiptoken=private-canary", + "$top=1&$top=2", + ] { + for (profile, claims, expected) in [ + ("history", public_claims(), StatusCode::FORBIDDEN), + ( + "live-only", + caseworker_claims("case-management"), + StatusCode::FORBIDDEN, + ), + ] { + let response = send_to( + &app, + Method::GET, + &format!("/v1/records/assignments:snapshot?accessProfile={profile}&{query}"), + Some(claims), + ) + .await; + assert_eq!(response.status(), expected, "{query}"); + assert_ne!(body_json(response).await["code"], "query.invalid"); + } + let response = send_to( + &app, + Method::GET, + &format!("/v1/records/assignments:snapshot?{query}"), + Some(caseworker_claims("case-management")), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{query}"); + let problem = body_json(response).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + assert!(!problem.to_string().contains("private-canary")); + } + assert!(snapshots.requests.lock().unwrap().is_empty()); + assert_eq!(records.calls(), 0); +} + +#[tokio::test] +async fn retired_get_paging_waits_for_admission_and_audit() { + assert_retired_exact_paging( + Method::GET, + "/v1/records/households/00000000-0000-4000-8000-000000000001", + ) + .await; +} + +#[tokio::test] +async fn retired_lookup_paging_waits_for_admission_and_audit() { + assert_retired_exact_paging(Method::POST, "/v1/records/households:lookup").await; +} + +async fn assert_retired_exact_paging(method: Method, route: &str) { + let harness = Harness::from_project(LOOKUP_PATH_PROJECT, true); + for (profile, claims, status, code) in [ + ( + "accessProfile=unknown&", + caseworker_claims("case-management"), + StatusCode::FORBIDDEN, + "profile.not-authorized", + ), + ( + "accessProfile=operator&", + caseworker_claims("wrong-purpose"), + StatusCode::FORBIDDEN, + "profile.not-authorized", + ), + ( + "", + caseworker_claims("case-management"), + StatusCode::BAD_REQUEST, + "query.invalid", + ), + ( + "%61ccessProfile=operator&", + caseworker_claims("case-management"), + StatusCode::BAD_REQUEST, + "query.invalid", + ), + ] { + let before = harness.records.refusal_calls(); + let response = harness + .send_json( + method.clone(), + &format!("{route}?{profile}%24top=private-canary"), + Some(claims), + json!({"selector": "by-household-code", "values": {"householdCode": "example"}}), + ) + .await; + assert_eq!(response.status(), status, "{route} {profile}"); + let problem = body_json(response).await; + assert_eq!(problem["code"], code); + if code == "query.invalid" { + assert_eq!(problem["fieldPath"], "query"); + } + assert!(!problem.to_string().contains("private-canary")); + assert_eq!(harness.records.refusal_calls(), before + 1); + } + assert_eq!(harness.records.calls(), 0); +} + +#[tokio::test] +async fn retired_paging_refuses_malformed_explicit_profile_selection() { + let harness = Harness::from_project(LOOKUP_PATH_PROJECT, true); + let (snapshots_app, snapshot_records, snapshots) = snapshot_harness(SNAPSHOT_PROJECT, &[]); + for selector in [ + "accessProfile", + "%61ccessProfile=%ff", + "accessProfile=", + "accessProfile=badProfile", + "accessProfile=operator&%61ccessProfile=operator", + "accessProfile=history&%61ccessProfile=history", + ] { + let claims = Some(caseworker_claims("case-management")); + let response = harness + .send( + Method::GET, + &format!("/v1/records/households?$top=1&{selector}"), + claims.clone(), + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{selector}"); + assert_eq!(body_json(response).await["code"], "profile.not-authorized"); + + let response = send_to( + &snapshots_app, + Method::GET, + &format!("/v1/records/assignments:snapshot?$top=1&{selector}"), + claims, + ) + .await; + assert_eq!(response.status(), StatusCode::NOT_FOUND, "{selector}"); + assert_eq!(body_json(response).await["code"], "resource.not-found"); + } + assert_eq!(harness.records.calls(), 0); + assert_eq!(snapshot_records.calls(), 0); + assert!(snapshots.requests.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn retired_record_paging_has_a_fixed_location_after_admission() { + let harness = Harness::new(true); + for accept in [Some("application/json"), Some("application/ld+json")] { + for query in [ + "$top=1", + "limit=1&%24top=private-canary", + "%24skiptoken=private-canary&cursor=opaque", + "$skiptoken=one&$skiptoken=two", + ] { + let response = harness + .send_with_accept( + Method::GET, + &format!("/v1/records/cases?{query}"), + Some(public_claims()), + accept, + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{query}"); + let problem = body_json(response).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + assert!(!problem.to_string().contains("private-canary")); + } + } + assert_eq!(harness.records.calls(), 0); +} + #[tokio::test] async fn snapshot_rejects_ambiguous_time_and_cursor_overrides_before_history_io() { let (app, records, snapshots) = snapshot_harness(SNAPSHOT_PROJECT, &[]); @@ -922,11 +1095,11 @@ async fn snapshot_rejects_ambiguous_time_and_cursor_overrides_before_history_io( "snapshot=forged-canary", "snapshot=a&snapshot=b", "validAt=2026-06-05&validAt=2026-07-05", - "$skiptoken=canary&validAt=2026-06-05", - "$skiptoken=canary&snapshot=canary", + "cursor=canary&validAt=2026-06-05", + "cursor=canary&snapshot=canary", "$expand=household", "$select=hidden", - "$top=101", + "limit=101", ] { let response = send_to( &app, @@ -1047,7 +1220,7 @@ async fn closed_query_grammar_reaches_record_service_as_compiled_query() { let accepted = harness .send( Method::GET, - "/v1/records/cases?$select=label&$filter=startswith(label,'Visible')&$orderby=label&$top=25", + "/v1/records/cases?$select=label&$filter=startswith(label,'Visible')&$orderby=label&limit=25", Some(public_claims()), ) .await; @@ -1115,7 +1288,7 @@ async fn bbox_reaches_record_service_only_with_declared_spatial_grant() { let accepted = harness .send_with_accept( Method::GET, - "/v1/records/sites?bbox=100,10,101,11&$filter=code%20eq%20'SITE-A'&$top=25", + "/v1/records/sites?bbox=100,10,101,11&$filter=code%20eq%20'SITE-A'&limit=25", Some(public_claims()), Some("application/geo+json"), ) @@ -1690,7 +1863,7 @@ async fn relationship_route_uses_path_grant_not_direct_target_rights() { .send( Method::GET, &format!( - "/v1/records/households/{root}/people?accessProfile=operator&$select=personCode&$filter=startswith(personCode,'P-')&$orderby=personCode&$top=5&$count=true" + "/v1/records/households/{root}/people?accessProfile=operator&$select=personCode&$filter=startswith(personCode,'P-')&$orderby=personCode&limit=5&$count=true" ), Some(caseworker_claims("case-management")), ) @@ -2047,7 +2220,7 @@ async fn derived_fields_are_discoverable_as_read_only_response_properties() { async fn continuation_requests_refuse_query_overrides_before_record_io() { let harness = Harness::new(true); let before = harness.records.calls(); - for parameter in ["cursor", "$skiptoken"] { + for parameter in ["cursor", "%63ursor"] { let response = harness .send( Method::GET, @@ -2058,7 +2231,7 @@ async fn continuation_requests_refuse_query_overrides_before_record_io() { assert_eq!(response.status(), StatusCode::BAD_REQUEST); let problem = body_json(response).await; assert_eq!(problem["code"], "query.invalid"); - assert_eq!(problem["fieldPath"], parameter); + assert_eq!(problem["fieldPath"], "cursor"); } assert_eq!(harness.records.calls(), before); } @@ -2118,9 +2291,9 @@ fn retired_proposal_history_query_name_is_not_advertised() { } #[tokio::test] -async fn record_list_accepts_limit_and_top_and_refuses_ambiguous_sizes() { +async fn record_list_accepts_limit_and_refuses_ambiguous_sizes() { let harness = Harness::new(true); - for query in ["limit=0", "$top=1&limit=1"] { + for query in ["limit=0", "limit=1&%6cimit=1"] { let response = harness .send( Method::GET, @@ -2135,7 +2308,7 @@ async fn record_list_accepts_limit_and_top_and_refuses_ambiguous_sizes() { } assert_eq!(harness.records.calls(), 0); - for query in ["limit=1", "$top=1"] { + for query in ["limit=1", "%6cimit=1"] { let accepted = harness .send( Method::GET, @@ -2149,7 +2322,7 @@ async fn record_list_accepts_limit_and_top_and_refuses_ambiguous_sizes() { } #[tokio::test] -async fn count_requires_compiled_permission_and_top_is_bounded() { +async fn count_requires_compiled_permission_and_limit_is_bounded() { let harness = Harness::new(true); let public_count = harness .send( @@ -2164,7 +2337,7 @@ async fn count_requires_compiled_permission_and_top_is_bounded() { let caseworker_count = harness .send( Method::GET, - "/v1/records/cases?accessProfile=caseworker&$count=true&$top=1", + "/v1/records/cases?accessProfile=caseworker&$count=true&limit=1", Some(caseworker_claims("case-management")), ) .await; @@ -2315,7 +2488,7 @@ async fn a_list_that_satisfies_an_alternative_runs() { async fn a_list_that_pins_no_alternative_is_refused_before_any_query() { for query in [ "", - "&$top=5", + "&limit=5", "&$filter=startswith(label,'Vis')", "&$filter=label%20ne%20'x'", "&$filter=label%20eq%20null", @@ -2450,7 +2623,7 @@ async fn continuation_keeps_the_criteria_and_cannot_drop_them() { let first_query = request_query(&first_request); let token = required_filters_cursor(first_query); - for parameter in ["cursor", "$skiptoken"] { + for parameter in ["cursor", "%63ursor"] { let next = required_filters_list(&harness, &format!("&{parameter}={token}")).await; assert_eq!(next.status(), StatusCode::OK, "{parameter}"); let next_request = harness.records.last_request(); @@ -2459,6 +2632,14 @@ async fn continuation_keeps_the_criteria_and_cannot_drop_them() { assert_eq!(single_filter_predicate(next_query).field_id, "label"); } + let calls = harness.records.calls(); + let retired = required_filters_list(&harness, &format!("&%24skiptoken={token}")).await; + assert_eq!(retired.status(), StatusCode::BAD_REQUEST); + let problem = body_json(retired).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + assert_eq!(harness.records.calls(), calls); + // The same cursor without its filter no longer matches its own binding. let mut stripped = serde_json::to_value(&first_query.cursor_query).expect("query serializes"); stripped["filter"] = Value::Null; @@ -2478,7 +2659,7 @@ async fn continuation_keeps_the_criteria_and_cannot_drop_them() { let _ = &mut payload; let forged = codec.encode(&payload).expect("cursor encodes"); let calls = harness.records.calls(); - let refused = required_filters_list(&harness, &format!("&$skiptoken={forged}")).await; + let refused = required_filters_list(&harness, &format!("&cursor={forged}")).await; assert_eq!(refused.status(), StatusCode::BAD_REQUEST); assert_eq!(body_json(refused).await["code"], "query.cursor-invalid"); assert_eq!(harness.records.calls(), calls); @@ -2572,8 +2753,8 @@ fn strict_query_debug_output_redacts_identifiers_literals_and_tokens() { assert!(!rendered.contains("secret")); assert!(!rendered.contains("literal-canary")); - let token_query = strict_query::parse_read_query([("$skiptoken", "cursor-canary")]) - .expect("cursor query parses"); + let token_query = + strict_query::parse_read_query([("cursor", "cursor-canary")]).expect("cursor query parses"); assert!(!format!("{token_query:?}").contains("cursor-canary")); } @@ -3293,7 +3474,7 @@ async fn projection_can_only_reduce_the_authorized_profile() { let caller_limit = harness .send( Method::GET, - "/v1/records/cases?$top=101", + "/v1/records/cases?limit=101", Some(public_claims()), ) .await; @@ -3917,7 +4098,7 @@ async fn real_router_serves_only_authorized_explicit_revision_routes() { let malformed_query = send_to( &app, Method::GET, - &format!("{list_path}?accessProfile=caseworker&$top"), + &format!("{list_path}?accessProfile=caseworker&limit"), Some(caseworker_claims("case-management")), ) .await; @@ -4007,7 +4188,7 @@ async fn real_router_serves_only_authorized_explicit_revision_routes() { let audit_failure = send_to( &app, Method::GET, - &format!("{list_path}?$top=2"), + &format!("{list_path}?limit=2"), Some(caseworker_claims("case-management")), ) .await; @@ -4754,7 +4935,7 @@ async fn workspace_temporal_capabilities_and_no_store_cover_success_and_refusal( "/v1/records/public-records/00000000-0000-4000-8000-000000000001", "/v1/registry?accessProfile=unknown", "/v1/schemas/protected-ledger", - "/v1/records/public-records?$top=0", + "/v1/records/public-records?limit=0", "/missing", ] { let response = harness.send(Method::GET, uri, Some(public_claims())).await; @@ -4846,6 +5027,70 @@ async fn missing_row_boundary_claim_refuses_list_current_and_as_of_reads() { } } +#[tokio::test] +async fn retired_temporal_page_names_do_not_bypass_row_boundary_admission() { + let harness = Harness::from_project(TEMPORAL_ROW_BOUNDARY_PROJECT, true); + for uri in [ + "/v1/records/licences:current?%24top=1", + "/v1/records/licences:as-of?asOf=2026-06-05&%24skiptoken=opaque", + ] { + let response = harness + .send(Method::GET, uri, Some(claims_without_jurisdictions())) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN, "{uri}"); + assert_eq!(body_json(response).await["code"], "profile.not-authorized"); + let response = harness + .send( + Method::GET, + uri, + Some(caseworker_claims_with_direct("case-management", [])), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{uri}"); + let problem = body_json(response).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + } + assert_eq!(harness.records.calls(), 0); +} + +#[tokio::test] +async fn retired_related_page_names_follow_path_admission_and_root_format_checks() { + let harness = Harness::from_project(LOOKUP_PATH_PROJECT, true); + let root = "00000000-0000-4000-8000-000000000001"; + for (root_id, path, profile, expected) in [ + (root, "people", "operator", StatusCode::BAD_REQUEST), + (root, "people", "viewer", StatusCode::FORBIDDEN), + (root, "unknown-path", "operator", StatusCode::NOT_FOUND), + ("bad-root", "people", "operator", StatusCode::NOT_FOUND), + ] { + let response = harness + .send( + Method::GET, + &format!( + "/v1/records/households/{root_id}/{path}?accessProfile={profile}&%24top=1" + ), + Some(caseworker_claims_with_direct( + "case-management", + [( + "household_id", + VerifiedClaimValue::direct_string(root).unwrap(), + )], + )), + ) + .await; + assert_eq!(response.status(), expected, "{root_id}/{path} {profile}"); + let problem = body_json(response).await; + if expected == StatusCode::BAD_REQUEST { + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "query"); + } else { + assert_ne!(problem["code"], "query.invalid"); + } + } + assert_eq!(harness.records.calls(), 0); +} + /// Every public refusal names a problem type on the shared Registry Stack /// identifier host, so an adopter can resolve the type it was handed. A dot in /// the code separates path segments under the product prefix. diff --git a/crates/registry-breg/tests/postgres_access_log.rs b/crates/registry-breg/tests/postgres_access_log.rs index c41c65470b..df5b6e5065 100644 --- a/crates/registry-breg/tests/postgres_access_log.rs +++ b/crates/registry-breg/tests/postgres_access_log.rs @@ -494,7 +494,7 @@ async fn subject_access_log_requires_current_record_ownership_and_records_each_r &app, &agency, Method::GET, - "/v1/records/entries?$top=1", + "/v1/records/entries?limit=1", None, None ) @@ -551,7 +551,7 @@ async fn subject_access_log_requires_current_record_ownership_and_records_each_r &app, &agency, Method::GET, - "/v1/records/entries?$top=2", + "/v1/records/entries?limit=2", None, None ) @@ -1265,7 +1265,7 @@ async fn head_on_record_reads_is_refused_without_a_journaled_read() { let agency = token(&idp, "agency", "officer"); for uri in [ format!("/v1/records/entries/{RECORD_A}"), - "/v1/records/entries?$top=1".to_owned(), + "/v1/records/entries?limit=1".to_owned(), ] { assert_head_is_refused_like_an_unaccepted_method(&db, &app, &agency, &uri).await; } @@ -1405,7 +1405,7 @@ async fn a_request_without_its_required_access_reason_is_refused_before_any_reco &app, &agency, Method::GET, - "/v1/records/entries?accessProfile=reasoned&$top=1", + "/v1/records/entries?accessProfile=reasoned&limit=1", None, None, ) @@ -1429,6 +1429,46 @@ async fn a_request_without_its_required_access_reason_is_refused_before_any_reco db.cleanup().await; } +#[tokio::test] +async fn retired_exact_and_lookup_paging_waits_for_required_attribution() { + let (db, app, idp) = setup_registry(compiled_with_access_reason()).await; + let agency = token(&idp, "agency", "officer"); + let reason = reason_header("Review the synthetic record"); + for (method, route, body) in [ + (Method::GET, format!("/v1/records/entries/{RECORD_A}"), None), + ( + Method::POST, + "/v1/records/entries:lookup".to_owned(), + Some(json!({"selector":"by-subject","values":{"subject":SUBJECT}})), + ), + ] { + for (header, code) in [ + (None, "request.access-reason-required"), + (Some("not base64url!"), "request.access-reason-required"), + (Some(reason.as_str()), "query.invalid"), + ] { + let (status, problem) = send_reasoned( + &app, + &agency, + method.clone(), + &format!("{route}?accessProfile=reasoned&%24skiptoken=private-canary"), + body.clone(), + header, + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(problem["code"], code); + if code == "query.invalid" { + assert_eq!(problem["fieldPath"], "query"); + } + } + } + assert_eq!(access_log_rows(&db).await, 0); + drop(app); + drop(idp); + db.cleanup().await; +} + #[tokio::test] async fn an_invalid_access_reason_is_refused_like_a_missing_one() { let (db, app, idp) = setup_registry(compiled_with_access_reason()).await; @@ -1621,7 +1661,7 @@ async fn a_read_under_an_alerting_profile_emits_one_event_per_access_log_entry() &app, &agency, Method::GET, - "/v1/records/entries?accessProfile=reasoned&$top=2", + "/v1/records/entries?accessProfile=reasoned&limit=2", None, Some(&reason_header(reason)), ) @@ -1674,7 +1714,7 @@ async fn a_read_under_a_profile_the_hook_does_not_name_emits_none() { let agency = token(&idp, "agency", "officer"); for uri in [ format!("/v1/records/entries/{RECORD_A}"), - "/v1/records/entries?$top=2".to_owned(), + "/v1/records/entries?limit=2".to_owned(), ] { let (status, _) = send_reasoned(&app, &agency, Method::GET, &uri, None, None).await; assert_eq!(status, StatusCode::OK); diff --git a/crates/registry-breg/tests/postgres_consent_access.rs b/crates/registry-breg/tests/postgres_consent_access.rs index 521953d1bd..281217c34d 100644 --- a/crates/registry-breg/tests/postgres_consent_access.rs +++ b/crates/registry-breg/tests/postgres_consent_access.rs @@ -469,7 +469,7 @@ async fn real_postgres_consent_gates_every_read_operation_on_id_and_on_reference assert_eq!(ids(&page), expected, "{route}"); let first = h .get( - &format!("/v1/records/{route}?accessProfile={SCOPE}&$top=1&$count=true"), + &format!("/v1/records/{route}?accessProfile={SCOPE}&limit=1&$count=true"), &wfp, ) .await; @@ -629,7 +629,7 @@ async fn real_postgres_consent_gates_every_read_operation_on_id_and_on_reference for (route, cursor) in &cursors { let page = h .get( - &format!("/v1/records/{route}?accessProfile={SCOPE}&$skiptoken={cursor}"), + &format!("/v1/records/{route}?accessProfile={SCOPE}&cursor={cursor}"), &wfp, ) .await; @@ -950,7 +950,7 @@ async fn real_postgres_consent_matches_recipient_sets_purpose_and_scope_exactly( let alpha_give = h.decide(decision(&alpha_only, "ngo-alpha", "given")).await; let feed = h .get( - "/v1/records/consent-decisions?accessProfile=recipient-feed&$top=100", + "/v1/records/consent-decisions?accessProfile=recipient-feed&limit=100", &h.feed(WFP_CLIENT), ) .await; @@ -998,7 +998,7 @@ async fn real_postgres_consent_matches_recipient_sets_purpose_and_scope_exactly( ); let alpha_feed = h .get( - "/v1/records/consent-decisions?accessProfile=recipient-feed&$top=100", + "/v1/records/consent-decisions?accessProfile=recipient-feed&limit=100", &h.feed(ALPHA_CLIENT), ) .await; @@ -1019,7 +1019,7 @@ async fn real_postgres_consent_matches_recipient_sets_purpose_and_scope_exactly( let (status, body) = send( &h.app, Method::GET, - "/v1/records/consent-decisions?accessProfile=recipient-feed&$top=100", + "/v1/records/consent-decisions?accessProfile=recipient-feed&limit=100", Value::Null, None, &forged_feed, @@ -1105,7 +1105,7 @@ async fn real_postgres_consent_refusals_reach_no_recipient_through_an_authored_s let beta = h.feed(BETA_CLIENT); let feed = h .get( - "/v1/records/consent-decisions?accessProfile=recipient-feed&$top=100", + "/v1/records/consent-decisions?accessProfile=recipient-feed&limit=100", &beta, ) .await; @@ -1360,7 +1360,7 @@ async fn real_postgres_consent_probe_runs_once_per_list_and_count() { let wfp = h.reader(WFP_CLIENT, PURPOSE); let page = h .get( - &format!("/v1/records/persons?accessProfile={SCOPE}&$top=100&$count=true"), + &format!("/v1/records/persons?accessProfile={SCOPE}&limit=100&$count=true"), &wfp, ) .await; @@ -1585,7 +1585,7 @@ async fn real_postgres_consent_gated_list_latency_budget() { admin_task.abort(); let token = h.reader(WFP_CLIENT, PURPOSE); - let uri = format!("/v1/records/persons?accessProfile={SCOPE}&$top=100&$count=true"); + let uri = format!("/v1/records/persons?accessProfile={SCOPE}&limit=100&$count=true"); h.get(&uri, &token).await; let mut samples = Vec::with_capacity(SAMPLES); for _ in 0..SAMPLES { diff --git a/crates/registry-breg/tests/postgres_historical.rs b/crates/registry-breg/tests/postgres_historical.rs index d6363ac379..969b693eb3 100644 --- a/crates/registry-breg/tests/postgres_historical.rs +++ b/crates/registry-breg/tests/postgres_historical.rs @@ -124,7 +124,7 @@ async fn snapshot_http_reconstructs_before_filters_and_keeps_pages_pinned() { let vocabulary_search = send( &app, &format!( - "/v1/records/memberships:snapshot?snapshot={}&validAt=2026-06-05&$select=jurisdiction&$filter=contains(jurisdiction,'ONE-A')&$top=1", + "/v1/records/memberships:snapshot?snapshot={}&validAt=2026-06-05&$select=jurisdiction&$filter=contains(jurisdiction,'ONE-A')&limit=1", snapshot_ref(OLD_REFERENCE_UUID) ), Some(history_claims(["zone-a"])), @@ -207,7 +207,7 @@ async fn snapshot_http_reconstructs_before_filters_and_keeps_pages_pinned() { let first_page = send( &app, - "/v1/records/memberships:snapshot?validAt=2026-06-05&$select=householdCode&$orderby=householdCode&$top=1&$count=true", + "/v1/records/memberships:snapshot?validAt=2026-06-05&$select=householdCode&$orderby=householdCode&limit=1&$count=true", Some(history_claims(["zone-a"])), ) .await; @@ -225,7 +225,7 @@ async fn snapshot_http_reconstructs_before_filters_and_keeps_pages_pinned() { let second_page = send( &app, - &format!("/v1/records/memberships:snapshot?$skiptoken={cursor}"), + &format!("/v1/records/memberships:snapshot?cursor={cursor}"), Some(history_claims(["zone-a"])), ) .await; @@ -483,7 +483,7 @@ async fn snapshot_count_filter_probe_stays_bounded_and_pinned() { let started = Instant::now(); let first_page = send( &app, - "/v1/records/memberships:snapshot?$select=householdCode&$filter=householdCode%20eq%20'probe-even'&$orderby=householdCode&$top=100&$count=true", + "/v1/records/memberships:snapshot?$select=householdCode&$filter=householdCode%20eq%20'probe-even'&$orderby=householdCode&limit=100&$count=true", Some(history_claims(["zone-a"])), ) .await; @@ -504,7 +504,7 @@ async fn snapshot_count_filter_probe_stays_bounded_and_pinned() { let second_page = send( &app, - &format!("/v1/records/memberships:snapshot?$skiptoken={cursor}"), + &format!("/v1/records/memberships:snapshot?cursor={cursor}"), Some(history_claims(["zone-a"])), ) .await; diff --git a/crates/registry-breg/tests/postgres_list_page_plans.rs b/crates/registry-breg/tests/postgres_list_page_plans.rs index dade7fa7b1..0ce5e9a90a 100644 --- a/crates/registry-breg/tests/postgres_list_page_plans.rs +++ b/crates/registry-breg/tests/postgres_list_page_plans.rs @@ -200,7 +200,7 @@ impl Fixture { let (status, mut body) = send( &self.app, &format!( - "/v1/records/assets?accessProfile=reader&$filter=kind%20eq%20'kind-1'{order}&$top={PAGE}" + "/v1/records/assets?accessProfile=reader&$filter=kind%20eq%20'kind-1'{order}&limit={PAGE}" ), ) .await; @@ -217,7 +217,7 @@ impl Fixture { self.take_plan(); let (status, next) = send( &self.app, - &format!("/v1/records/assets?accessProfile=reader&$skiptoken={cursor}"), + &format!("/v1/records/assets?accessProfile=reader&cursor={cursor}"), ) .await; assert_eq!(status, StatusCode::OK, "{next}"); @@ -230,7 +230,7 @@ impl Fixture { while let Some(cursor) = body["pageInfo"]["nextCursor"].as_str().map(str::to_owned) { let (status, next) = send( &self.app, - &format!("/v1/records/assets?accessProfile=reader&$skiptoken={cursor}"), + &format!("/v1/records/assets?accessProfile=reader&cursor={cursor}"), ) .await; assert_eq!(status, StatusCode::OK, "{next}"); diff --git a/crates/registry-breg/tests/postgres_membership_access.rs b/crates/registry-breg/tests/postgres_membership_access.rs index 23b65d599a..84be848426 100644 --- a/crates/registry-breg/tests/postgres_membership_access.rs +++ b/crates/registry-breg/tests/postgres_membership_access.rs @@ -221,7 +221,7 @@ async fn real_postgres_membership_reads_recheck_live_membership_and_hide_process let (_, _, page) = send( &app, Method::GET, - &format!("/v1/records/{route}?accessProfile=member&$top=1&$count=true"), + &format!("/v1/records/{route}?accessProfile=member&limit=1&$count=true"), Value::Null, None, &member, @@ -232,7 +232,7 @@ async fn real_postgres_membership_reads_recheck_live_membership_and_hide_process let (_, _, snapshot) = send( &app, Method::GET, - &format!("/v1/records/{route}:snapshot?accessProfile=member&$count=true&$top=1"), + &format!("/v1/records/{route}:snapshot?accessProfile=member&$count=true&limit=1"), Value::Null, None, &member, @@ -353,11 +353,9 @@ async fn real_postgres_membership_reads_recheck_live_membership_and_hide_process ); for uri in [ format!("/v1/records/{route}?accessProfile=member&$count=true"), - format!("/v1/records/{route}?accessProfile=member&$skiptoken={cursor}"), + format!("/v1/records/{route}?accessProfile=member&cursor={cursor}"), format!("/v1/records/{route}:snapshot?accessProfile=member&$count=true"), - format!( - "/v1/records/{route}:snapshot?accessProfile=member&$skiptoken={snapshot_cursor}" - ), + format!("/v1/records/{route}:snapshot?accessProfile=member&cursor={snapshot_cursor}"), ] { let (status, _, body) = send(&app, Method::GET, &uri, Value::Null, None, &member).await; assert_eq!(status, StatusCode::OK, "{body}"); diff --git a/crates/registry-breg/tests/postgres_mutation.rs b/crates/registry-breg/tests/postgres_mutation.rs index 1c860ce21e..b144d4dc63 100644 --- a/crates/registry-breg/tests/postgres_mutation.rs +++ b/crates/registry-breg/tests/postgres_mutation.rs @@ -3743,8 +3743,8 @@ async fn record_and_query_refusals_name_only_fixed_members_and_admitted_fields() assert_identical_problems(&filter_unknown, &filter_withheld); let filter_syntax = problem(query("/v1/records/widgets?$filter=label%20eq").await).await; assert_query_invalid_at(&filter_syntax, Some("$filter")); - let top = problem(query("/v1/records/widgets?$top=0").await).await; - assert_query_invalid_at(&top, Some("$top")); + let limit = problem(query("/v1/records/widgets?limit=0").await).await; + assert_query_invalid_at(&limit, Some("limit")); let orderby = problem(query("/v1/records/widgets?$orderby=secret").await).await; assert_query_invalid_at(&orderby, Some("$orderby")); let invented = problem(query("/v1/records/widgets?noSuchParameter=1").await).await; diff --git a/crates/registry-breg/tests/postgres_read.rs b/crates/registry-breg/tests/postgres_read.rs index cf03dfac4b..eb3fb019a5 100644 --- a/crates/registry-breg/tests/postgres_read.rs +++ b/crates/registry-breg/tests/postgres_read.rs @@ -135,7 +135,7 @@ async fn benchmark_audited_record_read(workload: ReadBenchmark) { ReadBenchmark::ListCountContinuation => { let first = send( &app, - "/v1/records/widgets?$select=label&$filter=jurisdiction%20in%20('zone-b','zone-a')&$orderby=ordinal&$top=100&$count=true", + "/v1/records/widgets?$select=label&$filter=jurisdiction%20in%20('zone-b','zone-a')&$orderby=ordinal&limit=100&$count=true", Some(read_claims(["zone-a"])), ) .await; @@ -177,7 +177,7 @@ async fn benchmark_audited_record_read(workload: ReadBenchmark) { }); ( "audited_record_list_count_continuation", - format!("/v1/records/widgets?$skiptoken={cursor}"), + format!("/v1/records/widgets?cursor={cursor}"), serde_json::to_vec(&expected).expect("expected list response serializes"), ) } @@ -429,7 +429,7 @@ async fn real_postgres_read_is_authorized_bounded_minimized_and_audit_gated() { let repeated_in = send( &app, - "/v1/records/widgets?$select=label&$filter=jurisdiction%20in%20('zone-b','zone-a')&$top=2", + "/v1/records/widgets?$select=label&$filter=jurisdiction%20in%20('zone-b','zone-a')&limit=2", Some(read_claims(["zone-a"])), ) .await; @@ -483,7 +483,7 @@ async fn real_postgres_read_is_authorized_bounded_minimized_and_audit_gated() { } let vocabulary_search = send( &app, - "/v1/records/widgets?$select=jurisdiction&$filter=contains(jurisdiction,'ONE-A')&$top=1", + "/v1/records/widgets?$select=jurisdiction&$filter=contains(jurisdiction,'ONE-A')&limit=1", Some(read_claims(["zone-a"])), ) .await; @@ -522,7 +522,7 @@ async fn real_postgres_read_is_authorized_bounded_minimized_and_audit_gated() { let continuation = send( &app, - &format!("/v1/records/widgets?$skiptoken={next_cursor}"), + &format!("/v1/records/widgets?cursor={next_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -550,7 +550,7 @@ async fn real_postgres_read_is_authorized_bounded_minimized_and_audit_gated() { let tampered = String::from_utf8(tampered).expect("cursor remains UTF-8"); let refused_cursor = send( &app, - &format!("/v1/records/widgets?$skiptoken={tampered}"), + &format!("/v1/records/widgets?cursor={tampered}"), Some(read_claims(["zone-a"])), ) .await; @@ -793,9 +793,48 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { assert!(current["items"][0]["domainData"].get("valid-to").is_none()); assert!(!current.to_string().contains(TEMPORAL_OTHER_BOUNDARY_RECORD)); + let as_of_route = "/v1/records/assignments:as-of"; + let at = "2020-05-31T23:59:59Z"; + let claims = Some(read_claims(["zone-a", "zone-b"])); + let first = send( + &app, + &format!( + "{as_of_route}?accessProfile=operator&asOf={at}&$select=label&$orderby=label&limit=1" + ), + claims.clone(), + ) + .await; + assert_eq!(first.status(), StatusCode::OK); + let first = body_json(first).await; + assert_eq!(first["meta"]["asOf"], at); + let cursor = first["pageInfo"]["nextCursor"].as_str().unwrap(); + let continuation = format!("{as_of_route}?accessProfile=operator&cursor={cursor}"); + let second = send(&app, &continuation, claims.clone()).await; + assert_eq!(second.status(), StatusCode::OK); + let second = body_json(second).await; + assert_eq!(second["meta"]["asOf"], at); + assert!(second["pageInfo"]["nextCursor"].is_null()); + assert_eq!( + second["items"][0]["domainData"], + json!({"label": "lease-b"}) + ); + assert_ids(first, &[TEMPORAL_OLD_RECORD]); + assert_ids(second, &[TEMPORAL_OTHER_BOUNDARY_RECORD]); + + let override_time = send( + &app, + &format!("{continuation}&asOf=2020-06-01T00:00:00Z"), + claims, + ) + .await; + assert_eq!(override_time.status(), StatusCode::BAD_REQUEST); + let problem = body_json(override_time).await; + assert_eq!(problem["code"], "query.invalid"); + assert_eq!(problem["fieldPath"], "cursor"); + let sorted_first = send( &app, - "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&$top=2", + "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&limit=2", Some(read_claims(["zone-a"])), ) .await; @@ -811,7 +850,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { .to_owned(); let sorted_second = send( &app, - &format!("/v1/records/widgets?$skiptoken={sorted_second_cursor}"), + &format!("/v1/records/widgets?cursor={sorted_second_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -828,7 +867,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { .to_owned(); let sorted_third = send( &app, - &format!("/v1/records/widgets?$skiptoken={sorted_third_cursor}"), + &format!("/v1/records/widgets?cursor={sorted_third_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -839,7 +878,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { let counted_first = send( &app, - "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&$top=2&$count=true", + "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&limit=2&$count=true", Some(read_claims(["zone-a"])), ) .await; @@ -859,7 +898,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { .to_owned(); let counted_second = send( &app, - &format!("/v1/records/widgets?$skiptoken={counted_cursor}"), + &format!("/v1/records/widgets?cursor={counted_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -883,29 +922,29 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { let replay_cursor = next_cursor( &app, - "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&$top=2", + "/v1/records/widgets?$select=label,rank&$filter=startswith(label,'sort-key-')&$orderby=rank&limit=2", Some(read_claims(["zone-a"])), ) .await; for (uri, claims) in [ ( - format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + format!("/v1/records/widgets?cursor={replay_cursor}"), read_claims_with(PRINCIPAL_CANARY, "audit-review", ["zone-a"]), ), ( - format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + format!("/v1/records/widgets?cursor={replay_cursor}"), read_claims_with("other-principal-value", "case-management", ["zone-a"]), ), ( - format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + format!("/v1/records/widgets?cursor={replay_cursor}"), read_claims_with(PRINCIPAL_CANARY, "case-management", ["zone-b"]), ), ( - format!("/v1/records/widgets?accessProfile=auditor&$skiptoken={replay_cursor}"), + format!("/v1/records/widgets?accessProfile=auditor&cursor={replay_cursor}"), read_claims(["zone-a"]), ), ( - format!("/v1/records/assignments?$skiptoken={replay_cursor}"), + format!("/v1/records/assignments?cursor={replay_cursor}"), read_claims(["zone-a"]), ), ] { @@ -928,14 +967,14 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { ); assert_cursor_invalid( &package_changed_app, - &format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + &format!("/v1/records/widgets?cursor={replay_cursor}"), Some(read_claims(["zone-a"])), ) .await; let projection_cursor = next_cursor( &app, - "/v1/records/widgets?$select=label,amount&$filter=startswith(label,'label-')&$orderby=ordinal&$top=2", + "/v1/records/widgets?$select=label,amount&$filter=startswith(label,'label-')&$orderby=ordinal&limit=2", Some(read_claims(["zone-a"])), ) .await; @@ -952,7 +991,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { ); assert_cursor_invalid( &projection_changed_app, - &format!("/v1/records/widgets?$skiptoken={projection_cursor}"), + &format!("/v1/records/widgets?cursor={projection_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -974,7 +1013,7 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { ); assert_cursor_invalid( &changed_app, - &format!("/v1/records/widgets?$skiptoken={replay_cursor}"), + &format!("/v1/records/widgets?cursor={replay_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -993,13 +1032,13 @@ async fn real_postgres_temporal_keyset_and_cursor_binding_edges_are_enforced() { ); let expired_cursor = next_cursor( &expiring_app, - "/v1/records/widgets?$select=label&$orderby=ordinal&$top=1", + "/v1/records/widgets?$select=label&$orderby=ordinal&limit=1", Some(read_claims(["zone-a"])), ) .await; assert_cursor_invalid( &expiring_app, - &format!("/v1/records/widgets?$skiptoken={expired_cursor}"), + &format!("/v1/records/widgets?cursor={expired_cursor}"), Some(read_claims(["zone-a"])), ) .await; @@ -1506,6 +1545,19 @@ async fn seed_records( ] { insert_assignment_row(transaction.transaction_for_test(), registry, row).await; } + } else { + insert_assignment_row( + transaction.transaction_for_test(), + registry, + AssignmentRow { + record_id: TEMPORAL_OTHER_BOUNDARY_RECORD, + jurisdiction, + label: "lease-b", + valid_from: "2020-01-01T00:00:00Z", + valid_to: None, + }, + ) + .await; } transaction .commit() diff --git a/crates/registry-breg/tests/postgres_read_dependencies.rs b/crates/registry-breg/tests/postgres_read_dependencies.rs index 68e440203e..a4ec61f56e 100644 --- a/crates/registry-breg/tests/postgres_read_dependencies.rs +++ b/crates/registry-breg/tests/postgres_read_dependencies.rs @@ -259,7 +259,7 @@ async fn exercise_read_dependencies(case: &str, invalid_population: bool, active // still reach their derived relation, including its cardinality guard. for query in [ "/v1/records/entries?$select=code&$filter=not%20(population%20lt%2032%20or%20population%20gt%2032)&$count=true", - "/v1/records/entries?$select=code&$orderby=population&$top=1", + "/v1/records/entries?$select=code&$orderby=population&limit=1", ] { let (status, body) = send(&app, query, false, "visible").await; if invalid_population { @@ -279,7 +279,7 @@ async fn exercise_combined_dependencies(app: &axum::Router, plans: &Mutex