1use canton_core::{Auth, Error, Result, TokenSource};
19use serde::{Deserialize, Serialize};
20
21use crate::context::{ChoiceContext, ChoiceContextRequest, WireChoiceContext};
22
23const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
28
29#[derive(Clone, Debug)]
31pub struct RegistryClient {
32 base: reqwest::Url,
33 http: reqwest::Client,
34 auth: Auth,
35}
36
37#[derive(Clone, Debug, Deserialize)]
39#[serde(rename_all = "camelCase")]
40#[non_exhaustive]
41pub struct RegistryInfo {
42 pub admin_id: String,
45 #[serde(default)]
47 pub supported_apis: std::collections::BTreeMap<String, i32>,
48}
49
50#[derive(Clone, Debug, Deserialize)]
52#[serde(rename_all = "camelCase")]
53#[non_exhaustive]
54pub struct Instrument {
55 pub id: String,
57 pub name: String,
59 pub symbol: String,
61 #[serde(default)]
63 pub total_supply: Option<String>,
64 #[serde(default)]
66 pub total_supply_as_of: Option<String>,
67 #[serde(default = "default_decimals")]
74 pub decimals: i32,
75 #[serde(default)]
77 pub supported_apis: std::collections::BTreeMap<String, i32>,
78 #[serde(default)]
81 pub paused: bool,
82 #[serde(default)]
84 pub pause_info: Option<PauseInfo>,
85 #[serde(default)]
89 pub account_input_fields_to_show: Option<Vec<String>>,
90}
91
92#[derive(Clone, Debug, Deserialize)]
94#[serde(rename_all = "camelCase")]
95#[non_exhaustive]
96pub struct PauseInfo {
97 #[serde(default)]
99 pub reason: Option<String>,
100 #[serde(default)]
102 pub until: Option<String>,
103}
104
105fn default_decimals() -> i32 {
107 10
108}
109
110#[derive(Debug, Deserialize)]
111#[serde(rename_all = "camelCase")]
112struct ListInstrumentsResponse {
113 #[serde(default)]
114 instruments: Vec<Instrument>,
115 #[serde(default)]
116 next_page_token: Option<String>,
117}
118
119#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
126#[serde(rename_all = "lowercase")]
127#[non_exhaustive]
128pub enum TransferKind {
129 #[serde(rename = "self")]
131 SelfTransfer,
132 Direct,
134 Offer,
136 #[serde(other)]
144 Unknown,
145}
146
147#[derive(Clone, Debug)]
149#[non_exhaustive]
150pub struct FactoryWithContext {
151 pub factory_id: String,
153 pub transfer_kind: Option<TransferKind>,
156 pub context: ChoiceContext,
158}
159
160#[derive(Debug, Deserialize)]
162#[serde(rename_all = "camelCase")]
163struct WireTransferFactory {
164 factory_id: String,
165 transfer_kind: TransferKind,
166 choice_context: WireChoiceContext,
167}
168
169#[derive(Debug, Deserialize)]
174#[serde(rename_all = "camelCase")]
175struct WireFactory {
176 factory_id: String,
177 choice_context: WireChoiceContext,
178}
179
180#[derive(Debug, Serialize)]
190#[serde(rename_all = "camelCase")]
191struct GetFactoryRequest<'a> {
192 choice_arguments: &'a serde_json::Value,
193 #[serde(skip_serializing_if = "std::ops::Not::not")]
194 exclude_debug_fields: bool,
195}
196
197impl RegistryClient {
198 pub fn new(base_url: &str) -> Result<Self> {
209 let http = reqwest::Client::builder()
213 .timeout(DEFAULT_TIMEOUT)
214 .redirect(reqwest::redirect::Policy::none())
215 .build()
216 .map_err(|e| Error::InvalidRequest(format!("cannot build an HTTP client: {e}")))?;
217 Self::with_http_client(base_url, http)
218 }
219
220 pub fn with_http_client(base_url: &str, http: reqwest::Client) -> Result<Self> {
228 let base = parse_base_url(base_url, "registry")?;
229 Ok(Self {
230 base,
231 http,
232 auth: Auth::None,
233 })
234 }
235
236 #[must_use]
242 pub fn with_token(mut self, token: impl Into<String>) -> Self {
243 self.auth = Auth::Static(token.into());
244 self
245 }
246
247 #[must_use]
250 pub fn with_token_source(mut self, source: impl TokenSource + 'static) -> Self {
251 self.auth = Auth::Dynamic(std::sync::Arc::new(source));
252 self
253 }
254
255 async fn authorized(
257 &self,
258 request: reqwest::RequestBuilder,
259 ) -> Result<reqwest::RequestBuilder> {
260 Ok(match self.auth.bearer().await? {
261 Some(token) => request.bearer_auth(token),
262 None => request,
263 })
264 }
265
266 fn url(&self, segments: &[&str]) -> Result<reqwest::Url> {
279 check_segments(segments)?;
280 let mut url = self.base.clone();
281 url.path_segments_mut()
282 .map_err(|()| Error::InvalidRequest("the registry URL cannot have a path".to_string()))?
283 .pop_if_empty()
284 .extend(segments);
285 Ok(url)
286 }
287
288 pub async fn info(&self) -> Result<RegistryInfo> {
295 self.get(self.url(&["registry", "metadata", "v1", "info"])?)
296 .await
297 }
298
299 pub async fn list_instruments(
306 &self,
307 page_size: Option<u32>,
308 page_token: Option<&str>,
309 ) -> Result<(Vec<Instrument>, Option<String>)> {
310 let mut url = self.url(&["registry", "metadata", "v1", "instruments"])?;
311 {
312 let mut query = url.query_pairs_mut();
316 if let Some(size) = page_size {
317 query.append_pair("pageSize", &size.to_string());
318 }
319 if let Some(token) = page_token {
320 query.append_pair("pageToken", token);
321 }
322 }
323 let response: ListInstrumentsResponse = self.get(url).await?;
324 Ok((response.instruments, response.next_page_token))
325 }
326
327 pub async fn instrument(&self, instrument_id: &str) -> Result<Option<Instrument>> {
339 let url = self.url(&["registry", "metadata", "v1", "instruments", instrument_id])?;
340 let response = self
341 .authorized(self.http.get(url.clone()))
342 .await?
343 .send()
344 .await
345 .map_err(connection)?;
346 if response.status() == reqwest::StatusCode::NOT_FOUND {
347 let body = read_error_body(response, url.as_str(), REGISTRY).await?;
351 let trimmed = body.trim();
352 if trimmed.is_empty() || serde_json::from_str::<serde_json::Value>(trimmed).is_ok() {
353 return Ok(None);
354 }
355 tracing::warn!(%url, "a 404 that is not the registry's own — check the base URL");
359 return Err(Error::http_at(404, truncate(trimmed), url.as_str()));
360 }
361 Ok(Some(Self::decode(response, url.as_str()).await?))
362 }
363
364 pub async fn transfer_factory(
372 &self,
373 choice_arguments: &serde_json::Value,
374 ) -> Result<FactoryWithContext> {
375 let url = self.url(&["registry", "transfer-instruction", "v1", "transfer-factory"])?;
376 let wire: WireTransferFactory = self.post_factory(url, choice_arguments).await?;
377 Ok(FactoryWithContext {
378 factory_id: wire.factory_id,
379 transfer_kind: Some(wire.transfer_kind),
380 context: ChoiceContext::from_wire(wire.choice_context)?,
381 })
382 }
383
384 pub async fn allocation_factory(
389 &self,
390 choice_arguments: &serde_json::Value,
391 ) -> Result<FactoryWithContext> {
392 let url = self.url(&[
393 "registry",
394 "allocation-instruction",
395 "v1",
396 "allocation-factory",
397 ])?;
398 let wire: WireFactory = self.post_factory(url, choice_arguments).await?;
399 Ok(FactoryWithContext {
400 factory_id: wire.factory_id,
401 transfer_kind: None,
402 context: ChoiceContext::from_wire(wire.choice_context)?,
403 })
404 }
405
406 pub async fn transfer_factory_v2(
422 &self,
423 choice_arguments: &serde_json::Value,
424 ) -> Result<FactoryWithContext> {
425 let url = self.url(&["registry", "transfer-instruction", "v2", "transfer-factory"])?;
426 let wire: WireTransferFactory = self.post_factory(url, choice_arguments).await?;
427 Ok(FactoryWithContext {
428 factory_id: wire.factory_id,
429 transfer_kind: Some(wire.transfer_kind),
430 context: ChoiceContext::from_wire(wire.choice_context)?,
431 })
432 }
433
434 pub async fn allocation_factory_v2(
441 &self,
442 choice_arguments: &serde_json::Value,
443 ) -> Result<FactoryWithContext> {
444 let url = self.url(&[
445 "registry",
446 "allocation-instruction",
447 "v2",
448 "allocation-factory",
449 ])?;
450 let wire: WireFactory = self.post_factory(url, choice_arguments).await?;
451 Ok(FactoryWithContext {
452 factory_id: wire.factory_id,
453 transfer_kind: None,
454 context: ChoiceContext::from_wire(wire.choice_context)?,
455 })
456 }
457
458 pub async fn settlement_factory_v2(
475 &self,
476 choice_arguments: &serde_json::Value,
477 ) -> Result<FactoryWithContext> {
478 let url = self.url(&["registry", "allocation", "v2", "settlement-factory"])?;
479 let wire: WireFactory = self.post_factory(url, choice_arguments).await?;
480 Ok(FactoryWithContext {
481 factory_id: wire.factory_id,
482 transfer_kind: None,
483 context: ChoiceContext::from_wire(wire.choice_context)?,
484 })
485 }
486
487 pub async fn transfer_instruction_context_v2(
494 &self,
495 transfer_instruction_id: &str,
496 choice: TransferInstructionChoice,
497 request: &ChoiceContextRequest,
498 ) -> Result<ChoiceContext> {
499 self.choice_context(
500 self.url(&[
501 "registry",
502 "transfer-instruction",
503 "v2",
504 transfer_instruction_id,
505 "choice-contexts",
506 choice.path(),
507 ])?,
508 request,
509 )
510 .await
511 }
512
513 pub async fn allocation_context_v2(
524 &self,
525 allocation_id: &str,
526 choice: AllocationChoice,
527 request: &ChoiceContextRequest,
528 ) -> Result<ChoiceContext> {
529 if choice == AllocationChoice::ExecuteTransfer {
530 return Err(Error::InvalidRequest(
531 "V2 allocations are settled through the settlement factory, not an \
532 execute-transfer context — see `settlement_factory_v2`"
533 .to_string(),
534 ));
535 }
536 self.choice_context(
537 self.url(&[
538 "registry",
539 "allocations",
540 "v2",
541 allocation_id,
542 "choice-contexts",
543 choice.path(),
544 ])?,
545 request,
546 )
547 .await
548 }
549
550 pub async fn allocation_instruction_context_v2(
560 &self,
561 allocation_instruction_id: &str,
562 choice: AllocationInstructionChoice,
563 request: &ChoiceContextRequest,
564 ) -> Result<ChoiceContext> {
565 self.choice_context(
566 self.url(&[
567 "registry",
568 "allocation-instruction",
569 "v2",
570 allocation_instruction_id,
571 "choice-contexts",
572 choice.path(),
573 ])?,
574 request,
575 )
576 .await
577 }
578
579 pub async fn transfer_instruction_context(
584 &self,
585 transfer_instruction_id: &str,
586 choice: TransferInstructionChoice,
587 request: &ChoiceContextRequest,
588 ) -> Result<ChoiceContext> {
589 self.choice_context(
590 self.url(&[
591 "registry",
592 "transfer-instruction",
593 "v1",
594 transfer_instruction_id,
595 "choice-contexts",
596 choice.path(),
597 ])?,
598 request,
599 )
600 .await
601 }
602
603 pub async fn allocation_context(
608 &self,
609 allocation_id: &str,
610 choice: AllocationChoice,
611 request: &ChoiceContextRequest,
612 ) -> Result<ChoiceContext> {
613 self.choice_context(
614 self.url(&[
615 "registry",
616 "allocations",
617 "v1",
618 allocation_id,
619 "choice-contexts",
620 choice.path(),
621 ])?,
622 request,
623 )
624 .await
625 }
626
627 async fn post_factory<T: serde::de::DeserializeOwned>(
628 &self,
629 url: reqwest::Url,
630 choice_arguments: &serde_json::Value,
631 ) -> Result<T> {
632 let response = self
633 .authorized(self.http.post(url.clone()))
634 .await?
635 .json(&GetFactoryRequest {
636 choice_arguments,
637 exclude_debug_fields: true,
641 })
642 .send()
643 .await
644 .map_err(connection)?;
645 Self::decode(response, url.as_str()).await
646 }
647
648 async fn choice_context(
649 &self,
650 url: reqwest::Url,
651 request: &ChoiceContextRequest,
652 ) -> Result<ChoiceContext> {
653 let response = self
654 .authorized(self.http.post(url.clone()))
655 .await?
656 .json(request)
657 .send()
658 .await
659 .map_err(connection)?;
660 let wire: WireChoiceContext = Self::decode(response, url.as_str()).await?;
661 ChoiceContext::from_wire(wire)
662 }
663
664 async fn get<T: serde::de::DeserializeOwned>(&self, url: reqwest::Url) -> Result<T> {
665 let response = self
666 .authorized(self.http.get(url.clone()))
667 .await?
668 .send()
669 .await
670 .map_err(connection)?;
671 Self::decode(response, url.as_str()).await
672 }
673
674 async fn decode<T: serde::de::DeserializeOwned>(
677 response: reqwest::Response,
678 url: &str,
679 ) -> Result<T> {
680 let status = response.status();
681 let body = if status.is_success() {
682 read_body(response, MAX_RESPONSE_BYTES, url).await?
683 } else {
684 read_error_body(response, url, REGISTRY).await?
685 };
686 if status == reqwest::StatusCode::CONFLICT {
687 let message = serde_json::from_str::<ErrorResponse>(&body)
694 .map(|e| e.error)
695 .unwrap_or(body);
696 return Err(Error::Connection(format!(
697 "{url}: the registry reports a contract mid-reassignment (409), retry shortly: {}",
698 truncate(&message)
699 )));
700 }
701 if !status.is_success() {
702 tracing::warn!(%url, status = status.as_u16(), "the registry answered with an error");
710 let message = serde_json::from_str::<ErrorResponse>(&body)
711 .map(|e| e.error)
712 .unwrap_or(body);
713 return Err(Error::http_at(status.as_u16(), truncate(&message), url));
714 }
715 serde_json::from_str(&body).map_err(|e| {
716 Error::UnexpectedResponse(format!(
717 "{url} returned a body this does not understand: {e}"
718 ))
719 })
720 }
721}
722
723#[derive(Deserialize)]
724pub(crate) struct ErrorResponse {
725 pub(crate) error: String,
726}
727
728const REGISTRY: &str = "the registry";
730
731pub(crate) fn check_segments(segments: &[&str]) -> Result<()> {
738 match segments.iter().find(|segment| {
739 matches!(**segment, "" | "." | "..") || segment.chars().any(char::is_control)
740 }) {
741 Some(segment) => Err(Error::InvalidRequest(format!(
742 "{segment:?} cannot be a path segment: it would address another resource"
743 ))),
744 None => Ok(()),
745 }
746}
747
748pub(crate) fn parse_base_url(base_url: &str, what: &str) -> Result<reqwest::Url> {
754 let trimmed = base_url.trim().trim_end_matches(['/', '\\']);
755 let base = reqwest::Url::parse(&format!("{trimmed}/")).map_err(|e| {
756 Error::InvalidRequest(format!(
757 "`{}` is not a {what} URL: {e}",
758 canton_core::redact_url(base_url)
759 ))
760 })?;
761 if base.query().is_some() || base.fragment().is_some() {
762 let mut shown = base.clone();
766 let _ = shown.set_username("");
767 let _ = shown.set_password(None);
768 shown.set_query(None);
769 shown.set_fragment(None);
770 return Err(Error::InvalidRequest(format!(
771 "the {what} URL `{shown}` has a query or a fragment, which it cannot carry"
772 )));
773 }
774 Ok(base)
775}
776
777pub(crate) const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024;
794pub(crate) const ERROR_BODY_CAP: usize = 64 * 1024;
796
797async fn read_body(response: reqwest::Response, cap: usize, url: &str) -> Result<String> {
801 read_body_from(response, cap, url, REGISTRY).await
802}
803
804pub(crate) async fn read_error_body(
810 mut response: reqwest::Response,
811 url: &str,
812 who: &str,
813) -> Result<String> {
814 let mut buffer: Vec<u8> = Vec::new();
815 while buffer.len() < ERROR_BODY_CAP {
816 let Some(chunk) = response
817 .chunk()
818 .await
819 .map_err(|e| transport_error(e, who))?
820 else {
821 break;
822 };
823 let room = ERROR_BODY_CAP.saturating_sub(buffer.len());
824 buffer.extend_from_slice(chunk.get(..room).unwrap_or(&chunk));
825 }
826 tracing::trace!(%url, bytes = buffer.len(), "read an error body");
827 Ok(String::from_utf8_lossy(&buffer).into_owned())
828}
829
830pub(crate) async fn read_body_from(
833 mut response: reqwest::Response,
834 cap: usize,
835 url: &str,
836 who: &str,
837) -> Result<String> {
838 if let Some(declared) = response
839 .content_length()
840 .filter(|declared| usize::try_from(*declared).map_or(true, |n| n > cap))
841 {
842 {
843 return Err(Error::UnexpectedResponse(format!(
844 "{url}: {who} answered with a {declared}-byte body, above the {cap}-byte limit"
845 )));
846 }
847 }
848 let mut buffer: Vec<u8> = Vec::new();
849 while let Some(chunk) = response
850 .chunk()
851 .await
852 .map_err(|e| transport_error(e, who))?
853 {
854 if buffer.len() + chunk.len() > cap {
855 return Err(Error::UnexpectedResponse(format!(
856 "{url}: {who} answered with a body above the {cap}-byte limit"
857 )));
858 }
859 buffer.extend_from_slice(&chunk);
860 }
861 String::from_utf8(buffer).map_err(|e| {
862 Error::UnexpectedResponse(format!(
863 "{url}: {who} answered with a body that is not UTF-8: {e}"
864 ))
865 })
866}
867
868fn connection(e: reqwest::Error) -> Error {
871 transport_error(e, REGISTRY)
872}
873
874pub(crate) fn transport_error(e: reqwest::Error, who: &str) -> Error {
877 let kind = if e.is_timeout() {
878 Transport::Timeout
879 } else if e.is_builder() {
880 Transport::Builder
881 } else if e.is_redirect() {
882 Transport::Redirect
883 } else if e.is_decode() {
884 Transport::Decode
885 } else {
886 Transport::Connect
887 };
888 let at = e
892 .url()
893 .map(|url| canton_core::redact_url(url.as_str()).into_owned());
894 classify_transport(
895 kind,
896 &canton_core::chain(&e.without_url()),
897 who,
898 at.as_deref(),
899 )
900}
901
902#[derive(Clone, Copy, Debug, PartialEq, Eq)]
906enum Transport {
907 Timeout,
908 Builder,
909 Redirect,
910 Decode,
911 Connect,
913}
914
915fn classify_transport(kind: Transport, detail: &str, who: &str, at: Option<&str>) -> Error {
918 let at = at.map(|url| format!(" ({url})")).unwrap_or_default();
919 match kind {
920 Transport::Timeout => return Error::Timeout,
923 Transport::Builder | Transport::Redirect => {
924 return Error::InvalidRequest(format!("{who} request could not be made{at}: {detail}"));
925 }
926 Transport::Decode => {
927 return Error::UnexpectedResponse(format!(
928 "{who}'s reply could not be read{at}: {detail}"
929 ));
930 }
931 Transport::Connect => {}
932 }
933 let lower = detail.to_ascii_lowercase();
939 if lower.contains("certificate") {
940 return Error::InvalidRequest(format!(
941 "{who}'s TLS certificate could not be verified{at}: {detail}"
942 ));
943 }
944 Error::Connection(format!("cannot reach {who}{at}: {detail}"))
945}
946
947#[derive(Clone, Copy, Debug, Eq, PartialEq)]
949#[non_exhaustive]
950pub enum TransferInstructionChoice {
951 Accept,
953 Reject,
955 Withdraw,
957}
958
959impl TransferInstructionChoice {
960 fn path(self) -> &'static str {
961 match self {
962 Self::Accept => "accept",
963 Self::Reject => "reject",
964 Self::Withdraw => "withdraw",
965 }
966 }
967}
968
969#[derive(Clone, Copy, Debug, Eq, PartialEq)]
974#[non_exhaustive]
975pub enum AllocationInstructionChoice {
976 Accept,
978 Withdraw,
980}
981
982impl AllocationInstructionChoice {
983 fn path(self) -> &'static str {
984 match self {
985 Self::Accept => "accept",
986 Self::Withdraw => "withdraw",
987 }
988 }
989}
990
991#[derive(Clone, Copy, Debug, Eq, PartialEq)]
993#[non_exhaustive]
994pub enum AllocationChoice {
995 ExecuteTransfer,
997 Withdraw,
999 Cancel,
1001}
1002
1003impl AllocationChoice {
1004 fn path(self) -> &'static str {
1005 match self {
1006 Self::ExecuteTransfer => "execute-transfer",
1007 Self::Withdraw => "withdraw",
1008 Self::Cancel => "cancel",
1009 }
1010 }
1011}
1012
1013pub(crate) fn truncate(body: &str) -> String {
1016 const LIMIT: usize = 200;
1017 if body.len() <= LIMIT {
1018 return body.to_string();
1019 }
1020 let cut = body
1021 .char_indices()
1022 .map(|(i, _)| i)
1023 .take_while(|i| *i <= LIMIT)
1024 .last()
1025 .unwrap_or(0);
1026 format!("{}…", body.get(..cut).unwrap_or(body))
1027}
1028
1029#[cfg(test)]
1030#[allow(clippy::unwrap_used, clippy::expect_used)]
1031mod tests {
1032 use super::*;
1033
1034 #[test]
1037 fn the_choice_paths_are_the_ones_the_standard_publishes() {
1038 assert_eq!(TransferInstructionChoice::Accept.path(), "accept");
1039 assert_eq!(TransferInstructionChoice::Reject.path(), "reject");
1040 assert_eq!(TransferInstructionChoice::Withdraw.path(), "withdraw");
1041 assert_eq!(AllocationChoice::ExecuteTransfer.path(), "execute-transfer");
1042 assert_eq!(AllocationChoice::Withdraw.path(), "withdraw");
1043 assert_eq!(AllocationChoice::Cancel.path(), "cancel");
1044 }
1045
1046 #[test]
1049 fn the_transfer_kinds_decode_from_the_words_the_wire_uses() {
1050 let kinds: Vec<TransferKind> =
1051 serde_json::from_str(r#"["self", "direct", "offer"]"#).expect("decodes");
1052 assert_eq!(
1053 kinds,
1054 [
1055 TransferKind::SelfTransfer,
1056 TransferKind::Direct,
1057 TransferKind::Offer
1058 ]
1059 );
1060 }
1061
1062 #[test]
1065 fn a_trailing_slash_on_the_base_url_does_not_double_up() {
1066 let client = RegistryClient::new("https://scan.example.com/").unwrap();
1067 assert_eq!(
1068 client
1069 .url(&["registry", "metadata", "v1", "info"])
1070 .unwrap()
1071 .as_str(),
1072 "https://scan.example.com/registry/metadata/v1/info"
1073 );
1074 }
1075
1076 #[test]
1081 fn a_hostile_path_segment_cannot_redirect_the_request() {
1082 let client = RegistryClient::new("https://scan.example.com").unwrap();
1083 for hostile in ["a?b", "a#b", "../../info", "a/b"] {
1084 let url = client
1085 .url(&["registry", "metadata", "v1", "instruments", hostile])
1086 .unwrap();
1087 assert_eq!(
1088 url.query(),
1089 None,
1090 "`{hostile}` must not become a query: {url}"
1091 );
1092 assert_eq!(
1093 url.path_segments().map(Iterator::count),
1094 Some(5),
1095 "`{hostile}` must stay one segment: {url}"
1096 );
1097 assert!(
1098 url.as_str()
1099 .starts_with("https://scan.example.com/registry/metadata/v1/instruments/"),
1100 "`{hostile}` escaped the collection: {url}"
1101 );
1102 }
1103 }
1104
1105 #[test]
1110 fn a_base_url_that_is_not_a_url_is_refused_immediately() {
1111 let err = RegistryClient::new("not a url").expect_err("not a URL");
1112 assert!(!err.is_retriable(), "a typo is not worth retrying: {err}");
1113 assert!(err.to_string().contains("not a url"), "{err}");
1114 }
1115
1116 #[test]
1117 fn the_factory_request_is_the_shape_the_standard_specifies() {
1118 let args = serde_json::json!({ "expectedAdmin": "dso::1220", "transfer": {} });
1119 let request = GetFactoryRequest {
1120 choice_arguments: &args,
1121 exclude_debug_fields: true,
1122 };
1123 assert_eq!(
1124 serde_json::to_value(&request).unwrap(),
1125 serde_json::json!({
1126 "choiceArguments": { "expectedAdmin": "dso::1220", "transfer": {} },
1127 "excludeDebugFields": true
1128 })
1129 );
1130 }
1131
1132 #[test]
1135 fn a_factory_response_decodes_and_its_context_is_translated() {
1136 let json = serde_json::json!({
1137 "factoryId": "00factory",
1138 "transferKind": "direct",
1139 "choiceContext": {
1140 "choiceContextData": { "values": {} },
1141 "disclosedContracts": [{
1142 "templateId": "pkg:Splice.AmuletRules:AmuletRules",
1143 "contractId": "001",
1144 "createdEventBlob": "AQI=",
1145 "synchronizerId": "sync::1220ab"
1146 }]
1147 }
1148 });
1149 let wire: WireTransferFactory = serde_json::from_value(json).expect("decodes");
1150 assert_eq!(wire.factory_id, "00factory");
1151 assert_eq!(wire.transfer_kind, TransferKind::Direct);
1152
1153 let context = ChoiceContext::from_wire(wire.choice_context).expect("translates");
1154 assert_eq!(context.disclosed_contracts().len(), 1);
1155 assert_eq!(context.disclosed_contracts()[0].created_event_blob, [1, 2]);
1156 }
1157
1158 #[test]
1163 fn the_allocation_factory_response_has_no_transfer_kind() {
1164 let json = serde_json::json!({
1165 "factoryId": "00factory",
1166 "choiceContext": { "choiceContextData": {}, "disclosedContracts": [] }
1167 });
1168 let wire: WireFactory = serde_json::from_value(json).expect("decodes");
1169 assert_eq!(wire.factory_id, "00factory");
1170
1171 let json = serde_json::json!({
1174 "factoryId": "00factory",
1175 "choiceContext": { "choiceContextData": {}, "disclosedContracts": [] }
1176 });
1177 assert!(serde_json::from_value::<WireTransferFactory>(json).is_err());
1178 }
1179
1180 #[test]
1183 fn an_unknown_transfer_kind_decodes_instead_of_failing_the_response() {
1184 let json = serde_json::json!({
1185 "factoryId": "00factory",
1186 "transferKind": "escrow-something-new",
1187 "choiceContext": { "choiceContextData": {}, "disclosedContracts": [] }
1188 });
1189 let wire: WireTransferFactory =
1190 serde_json::from_value(json).expect("an unknown kind is a value, not a decode failure");
1191 assert_eq!(wire.transfer_kind, TransferKind::Unknown);
1192 }
1193
1194 #[test]
1198 fn an_absent_decimals_is_the_standards_default_and_not_unknown() {
1199 let instrument: Instrument = serde_json::from_value(serde_json::json!({
1200 "id": "Amulet", "name": "Canton Coin", "symbol": "CC"
1201 }))
1202 .expect("decodes");
1203 assert_eq!(instrument.decimals, 10);
1204 }
1205
1206 #[test]
1207 fn instruments_decode_with_the_optional_fields_absent() {
1208 let json = serde_json::json!({
1209 "instruments": [{ "id": "Amulet", "name": "Canton Coin", "symbol": "CC" }]
1210 });
1211 let response: ListInstrumentsResponse = serde_json::from_value(json).expect("decodes");
1212 assert_eq!(response.instruments.len(), 1);
1213 assert_eq!(response.instruments[0].id, "Amulet");
1214 assert_eq!(response.instruments[0].total_supply, None);
1215 assert_eq!(response.instruments[0].decimals, 10);
1216 assert_eq!(response.next_page_token, None);
1217 }
1218
1219 #[test]
1224 fn a_certificate_failure_is_permanent_and_a_dropped_handshake_is_not() {
1225 let hung_up = classify_transport(
1226 Transport::Connect,
1227 "client error (Connect): tls handshake eof",
1228 REGISTRY,
1229 None,
1230 );
1231 assert!(matches!(hung_up, Error::Connection(_)), "{hung_up:?}");
1232 assert!(hung_up.is_retriable(), "{hung_up}");
1233
1234 for detail in [
1235 "error sending request: invalid peer certificate: UnknownIssuer",
1236 "CERTIFICATE verify failed",
1237 ] {
1238 let error = classify_transport(Transport::Connect, detail, REGISTRY, None);
1239 assert!(
1240 matches!(error, Error::InvalidRequest(_)),
1241 "{detail}: {error:?}"
1242 );
1243 assert!(!error.is_retriable(), "{detail}");
1244 assert!(error.to_string().contains("TLS certificate"), "{error}");
1245 }
1246 let refused = classify_transport(
1247 Transport::Connect,
1248 "connection refused (os error 61)",
1249 REGISTRY,
1250 None,
1251 );
1252 assert!(matches!(refused, Error::Connection(_)), "{refused:?}");
1253 assert!(refused.is_retriable());
1254 assert!(
1255 refused.to_string().contains("connection refused"),
1256 "{refused}"
1257 );
1258 }
1259
1260 #[test]
1264 fn the_typed_verdicts_are_read_before_the_strings() {
1265 let timeout = classify_transport(
1266 Transport::Timeout,
1267 "certificate", REGISTRY,
1269 None,
1270 );
1271 assert!(matches!(timeout, Error::Timeout), "{timeout:?}");
1272
1273 for kind in [Transport::Builder, Transport::Redirect] {
1274 let error = classify_transport(kind, "x", REGISTRY, None);
1275 assert!(
1276 matches!(&error, Error::InvalidRequest(m) if m.contains("could not be made")),
1277 "{kind:?}: {error:?}"
1278 );
1279 }
1280
1281 let decode = classify_transport(Transport::Decode, "x", REGISTRY, None);
1282 assert!(matches!(decode, Error::UnexpectedResponse(_)), "{decode:?}");
1283 }
1284
1285 #[tokio::test]
1289 async fn a_refused_connection_is_retriable_whatever_the_url_spells() {
1290 let failed = reqwest::Client::new()
1291 .get("http://user:secret@127.0.0.1:1/certificate-service/registry/metadata/v1/info")
1292 .send()
1293 .await
1294 .expect_err("nothing listens there");
1295 let error = transport_error(failed, REGISTRY);
1296 assert!(matches!(error, Error::Connection(_)), "{error:?}");
1297 assert!(error.is_retriable(), "{error}");
1298 let message = error.to_string();
1299 assert!(
1300 message.contains("127.0.0.1:1/certificate-service"),
1301 "{message}"
1302 );
1303 assert!(!message.contains("secret"), "{message}");
1304 }
1305
1306 #[tokio::test]
1310 async fn a_dot_or_empty_path_segment_is_refused_before_sending() {
1311 let client = RegistryClient::new("http://127.0.0.1:1").unwrap();
1312 for id in ["..", ".", ""] {
1313 let error = client.instrument(id).await.unwrap_err();
1314 assert!(
1315 matches!(error, Error::InvalidRequest(_)),
1316 "{id:?}: {error:?}"
1317 );
1318 assert!(error.to_string().contains("path segment"), "{error}");
1319 }
1320 let error = client.instrument("a..b").await.unwrap_err();
1322 assert!(matches!(error, Error::Connection(_)), "{error:?}");
1323 }
1324
1325 #[tokio::test]
1328 async fn a_control_character_in_a_path_segment_is_refused_before_sending() {
1329 let client = RegistryClient::new("http://127.0.0.1:1").unwrap();
1330 for id in ["USD\tC", "Amulet\n", "A\r\nmulet", ".\t.", "\t", "x\u{7f}"] {
1331 let error = client.instrument(id).await.unwrap_err();
1332 assert!(
1333 matches!(error, Error::InvalidRequest(_)),
1334 "{id:?}: {error:?}"
1335 );
1336 }
1337 }
1338
1339 #[test]
1342 fn the_base_url_has_no_query_or_fragment_and_is_trimmed() {
1343 for base in [
1344 "https://r.example/api?apikey=abc",
1345 "https://r.example/api#x",
1346 "https://alice:s3cret@r.example/api?apikey=abc",
1347 "https:alice:s3cret@r.example/api?apikey=abc",
1348 "https:/alice:s3cret@r.example/api#x",
1349 ] {
1350 match RegistryClient::new(base) {
1351 Err(Error::InvalidRequest(message)) => {
1353 assert!(!message.contains("s3cret"), "{message}");
1354 assert!(!message.contains("apikey=abc"), "{message}");
1355 }
1356 other => panic!("{base}: {:?}", other.map(|_| ())),
1357 }
1358 }
1359 let client = RegistryClient::new(r" https://r.example/api\ ").unwrap();
1360 assert_eq!(
1361 client
1362 .url(&["registry", "metadata", "v1", "info"])
1363 .unwrap()
1364 .as_str(),
1365 "https://r.example/api/registry/metadata/v1/info"
1366 );
1367 }
1368
1369 #[test]
1372 fn truncate_cuts_past_the_limit_and_on_a_character_boundary() {
1373 let exact = "x".repeat(200);
1374 assert_eq!(truncate(&exact), exact);
1375
1376 let over = "x".repeat(201);
1377 let cut = truncate(&over);
1378 assert!(cut.ends_with('…'), "{cut}");
1379 assert_eq!(cut.trim_end_matches('…').len(), 200);
1380
1381 let straddle = format!("{}€€", "x".repeat(199));
1383 let cut = truncate(&straddle);
1384 assert!(cut.ends_with('…'), "{cut}");
1385 assert!(cut.starts_with(&"x".repeat(199)), "{cut}");
1386 }
1387}