Skip to main content

odp_directory/
client.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    net::IpAddr,
4    sync::Arc,
5};
6
7use odp_core::{Protocol, derive_service_origin, is_public, parse_agent_service_document};
8use serde_json::{Value, json};
9use thiserror::Error;
10use url::{Host, Url};
11
12use crate::{
13    DirectoryService, Environment, HttpRequest, HttpResponse, IterationOptions,
14    ResourceSearchRequest, SearchPage, SearchRequest, SearchResponse, ServiceIssue,
15    SuggestionRequest, Transport, TransportError, default_transport,
16};
17
18const MAXIMUM_REDIRECTS: usize = 5;
19const MAXIMUM_RESPONSE_BYTES: usize = 524_288;
20/// ERR-21: a failure is described far more tightly than a result is returned.
21const MAXIMUM_ERROR_BYTES: usize = 16_384;
22/// How much of a failure body is worth repeating to a caller.
23const MAXIMUM_ERROR_MESSAGE: usize = 2_048;
24const MAXIMUM_ITEMS_PER_PAGE: usize = 100;
25const MAXIMUM_FACET_ENTRIES: usize = 100;
26const MAXIMUM_SUGGESTIONS: usize = 25;
27const MAXIMUM_TRAVERSAL: usize = 10_000;
28const MAXIMUM_REFERENCE_CHARACTERS: usize = 2_048;
29const MAXIMUM_PAGES: usize = 16;
30
31#[derive(Debug, Error)]
32pub enum DirectoryError {
33    #[error(transparent)]
34    Transport(#[from] TransportError),
35    #[error("invalid Directory request: {0}")]
36    InvalidRequest(String),
37    #[error("invalid Directory response: {0}")]
38    InvalidResponse(String),
39    #[error("Directory request failed with HTTP {status}: {message}")]
40    Request {
41        headers: BTreeMap<String, String>,
42        message: String,
43        status: u16,
44    },
45}
46
47#[derive(Clone)]
48pub struct DirectoryClient {
49    environment: Environment,
50    transport: Arc<dyn Transport>,
51}
52
53impl DirectoryClient {
54    pub fn new(environment: Environment) -> Result<Self, DirectoryError> {
55        Ok(Self {
56            environment,
57            transport: default_transport()?,
58        })
59    }
60
61    pub fn with_transport(environment: Environment, transport: Arc<dyn Transport>) -> Self {
62        Self {
63            environment,
64            transport,
65        }
66    }
67
68    pub const fn environment(&self) -> Environment {
69        self.environment
70    }
71
72    pub async fn search(
73        &self,
74        request: &ResourceSearchRequest,
75    ) -> Result<SearchResponse, DirectoryError> {
76        validate_search(&request.query, request.limit, request.filters.as_ref())?;
77        if let Some(types) = &request.types {
78            if types.is_empty() || types.len() > 2 || (types.len() == 2 && types[0] == types[1]) {
79                return Err(DirectoryError::InvalidRequest(
80                    "types must contain distinct service or collection values".to_owned(),
81                ));
82            }
83        }
84        let body = serde_json::to_vec(request)
85            .map_err(|error| DirectoryError::InvalidRequest(error.to_string()))?;
86        let target = self.continuation_url("/v1/directory/search")?;
87        let response = self.request("POST", target, body).await?;
88        crate::results::decode(&response.body)
89    }
90
91    pub async fn continue_search(&self, next: &str) -> Result<SearchResponse, DirectoryError> {
92        let target = self.continuation_url(next)?;
93        let response = self.request("GET", target, Vec::new()).await?;
94        crate::results::decode(&response.body)
95    }
96
97    pub async fn search_services(
98        &self,
99        request: &SearchRequest,
100    ) -> Result<SearchPage, DirectoryError> {
101        validate_search_request(request)?;
102        let body = serde_json::to_vec(request)
103            .map_err(|error| DirectoryError::InvalidRequest(error.to_string()))?;
104        self.request_page(
105            "POST",
106            &format!("{}/v1/services/search", self.environment.origin()),
107            body,
108        )
109        .await
110    }
111
112    pub async fn continue_search_services(&self, next: &str) -> Result<SearchPage, DirectoryError> {
113        let target = self.continuation_url(next)?;
114        self.request_page("GET", target.as_str(), Vec::new()).await
115    }
116
117    /// Every page of a search, up to `max_pages`.
118    ///
119    /// The last page returned still carries its `next`, so a caller that wants to go further can
120    /// resume from it: reaching the bound is not the same as reaching the end.
121    pub async fn search_pages(
122        &self,
123        request: &SearchRequest,
124        options: IterationOptions,
125    ) -> Result<Vec<SearchPage>, DirectoryError> {
126        self.traverse(request, options, usize::MAX)
127            .await
128            .map(|(pages, _)| pages)
129    }
130
131    pub async fn collect_services(
132        &self,
133        request: &SearchRequest,
134        options: IterationOptions,
135    ) -> Result<Vec<DirectoryService>, DirectoryError> {
136        let maximum_items = bounded(options.max_items, MAXIMUM_TRAVERSAL, "max_items")?;
137        let (pages, _) = self.traverse(request, options, maximum_items).await?;
138        Ok(pages
139            .into_iter()
140            .flat_map(|page| page.items)
141            .take(maximum_items)
142            .collect())
143    }
144
145    /// Walks a search from its first page, stopping at whichever bound is reached first.
146    ///
147    /// A page is only fetched when something still wants it, so a caller asking for ten Services
148    /// does not pay for a hundred, and a cursor that repeats is refused rather than followed.
149    async fn traverse(
150        &self,
151        request: &SearchRequest,
152        options: IterationOptions,
153        maximum_items: usize,
154    ) -> Result<(Vec<SearchPage>, usize), DirectoryError> {
155        let maximum_pages = bounded(options.max_pages, MAXIMUM_PAGES, "max_pages")?;
156        // Validated here as well, so `search_pages` refuses the same requests `search_services` does.
157        bounded(options.max_items, MAXIMUM_TRAVERSAL, "max_items")?;
158        let mut pages = Vec::new();
159        let mut visited = BTreeSet::new();
160        let mut items = 0_usize;
161        let mut page = self.search_services(request).await?;
162        loop {
163            items += page.items.len();
164            let next = page.next.clone();
165            pages.push(page);
166            if next.is_empty() || pages.len() >= maximum_pages || items >= maximum_items {
167                return Ok((pages, items));
168            }
169            let target = self.continuation_url(&next)?;
170            if !visited.insert(target.to_string()) {
171                return Err(DirectoryError::InvalidResponse(
172                    "Directory pagination loop detected".to_owned(),
173                ));
174            }
175            page = self
176                .request_page("GET", target.as_str(), Vec::new())
177                .await?;
178        }
179    }
180
181    pub async fn suggest(
182        &self,
183        request: &SuggestionRequest,
184    ) -> Result<Vec<String>, DirectoryError> {
185        self.suggestions("/v1/directory/suggestions", request, true)
186            .await
187    }
188
189    pub async fn suggest_services(
190        &self,
191        request: &SuggestionRequest,
192    ) -> Result<Vec<String>, DirectoryError> {
193        self.suggestions("/v1/services/suggestions", request, false)
194            .await
195    }
196
197    async fn suggestions(
198        &self,
199        path: &str,
200        request: &SuggestionRequest,
201        mixed: bool,
202    ) -> Result<Vec<String>, DirectoryError> {
203        let prefix = request.prefix.trim();
204        if prefix.is_empty() || prefix.chars().count() > 128 {
205            return Err(DirectoryError::InvalidRequest(
206                "prefix must contain from 1 through 128 characters".to_owned(),
207            ));
208        }
209        if request.limit > 25 {
210            return Err(DirectoryError::InvalidRequest(
211                "limit must be from 1 through 25".to_owned(),
212            ));
213        }
214        let mut target = Url::parse(&format!("{}{}", self.environment.origin(), path))
215            .map_err(|error| DirectoryError::InvalidRequest(error.to_string()))?;
216        let response = if mixed {
217            validate_search("", 0, request.filters.as_ref())?;
218            let payload = SuggestionRequest {
219                prefix: prefix.to_owned(),
220                ..request.clone()
221            };
222            let body = serde_json::to_vec(&payload)
223                .map_err(|error| DirectoryError::InvalidRequest(error.to_string()))?;
224            self.request("POST", target, body).await?
225        } else {
226            if request.filters.is_some() {
227                return Err(DirectoryError::InvalidRequest(
228                    "Service-only suggestions do not support filters".to_owned(),
229                ));
230            }
231            target.query_pairs_mut().append_pair("prefix", prefix);
232            if request.limit != 0 {
233                target
234                    .query_pairs_mut()
235                    .append_pair("limit", &request.limit.to_string());
236            }
237            self.request("GET", target, Vec::new()).await?
238        };
239        parse_suggestions(&response.body)
240    }
241
242    async fn request_page(
243        &self,
244        method: &str,
245        target: &str,
246        body: Vec<u8>,
247    ) -> Result<SearchPage, DirectoryError> {
248        let target = Url::parse(target)
249            .map_err(|error| DirectoryError::InvalidRequest(error.to_string()))?;
250        let response = self.request(method, target, body).await?;
251        let mut value = serde_json::from_slice::<Value>(&response.body)
252            .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
253        let object = value.as_object_mut().ok_or_else(|| {
254            DirectoryError::InvalidResponse("Directory search page must be an object".to_owned())
255        })?;
256        require_continuation(object.get("next"))?;
257        require_facets(object.get("facets"))?;
258        let raw = object
259            .get_mut("items")
260            .and_then(Value::as_array_mut)
261            .ok_or_else(|| {
262                DirectoryError::InvalidResponse(
263                    "Directory search page items are invalid".to_owned(),
264                )
265            })?;
266        if raw.len() > MAXIMUM_ITEMS_PER_PAGE {
267            return Err(DirectoryError::InvalidResponse(
268                "Directory search page exceeds 100 Services".to_owned(),
269            ));
270        }
271        // ROLE-03: one record this client cannot read is a note about that record. Withholding the
272        // whole page would let a single bad row in an index nobody controls deny every other Service.
273        let mut items = Vec::with_capacity(raw.len());
274        let mut issues = Vec::new();
275        for (index, item) in raw.iter_mut().enumerate() {
276            match read_service(item) {
277                Ok(service) => items.push(service),
278                Err(error) => issues.push(ServiceIssue {
279                    index,
280                    message: error.to_string(),
281                }),
282            }
283        }
284        object.insert("items".to_owned(), Value::Array(Vec::new()));
285        let mut page = serde_json::from_value::<SearchPage>(value)
286            .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
287        page.items = items;
288        page.issues = issues;
289        Ok(page)
290    }
291
292    async fn request(
293        &self,
294        mut method: &str,
295        mut target: Url,
296        mut body: Vec<u8>,
297    ) -> Result<HttpResponse, DirectoryError> {
298        let mut redirects = 0_usize;
299        loop {
300            let mut headers =
301                BTreeMap::from([("accept".to_owned(), "application/json".to_owned())]);
302            if !body.is_empty() {
303                headers.insert("content-type".to_owned(), "application/json".to_owned());
304            }
305            let response = self
306                .transport
307                .send(HttpRequest {
308                    body: body.clone(),
309                    headers,
310                    method: method.to_owned(),
311                    url: target.to_string(),
312                })
313                .await?;
314            if !matches!(response.status, 301 | 302 | 303 | 307 | 308) {
315                return consume_response(response);
316            }
317            if redirects == MAXIMUM_REDIRECTS {
318                return Err(DirectoryError::InvalidResponse(
319                    "Directory response exceeded five redirects".to_owned(),
320                ));
321            }
322            let location = response.headers.get("location").ok_or_else(|| {
323                DirectoryError::InvalidResponse("Directory redirect omitted Location".to_owned())
324            })?;
325            let next = target
326                .join(location)
327                .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
328            if next.origin() != target.origin() {
329                return Err(DirectoryError::InvalidResponse(
330                    "Directory redirect changed origin".to_owned(),
331                ));
332            }
333            if response.status == 303 || (matches!(response.status, 301 | 302) && method == "POST")
334            {
335                method = "GET";
336                body.clear();
337            }
338            target = next;
339            redirects += 1;
340        }
341    }
342
343    fn continuation_url(&self, next: &str) -> Result<Url, DirectoryError> {
344        if next.trim().is_empty() {
345            return Err(DirectoryError::InvalidRequest(
346                "Directory continuation is empty".to_owned(),
347            ));
348        }
349        let origin = Url::parse(self.environment.origin())
350            .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
351        let target = origin
352            .join(next)
353            .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
354        if target.origin() != origin.origin()
355            || !target.username().is_empty()
356            || target.password().is_some()
357        {
358            return Err(DirectoryError::InvalidResponse(
359                "Directory continuation changed canonical origin".to_owned(),
360            ));
361        }
362        Ok(target)
363    }
364}
365
366/// Reads one Directory record, or says why it cannot be used.
367fn read_service(item: &mut Value) -> Result<DirectoryService, DirectoryError> {
368    let object = item.as_object_mut().ok_or_else(|| {
369        DirectoryError::InvalidResponse("Directory Service must be an object".to_owned())
370    })?;
371    require_service_origin(object.get("service_origin"))?;
372    require_indexed_at(object.get("indexed_at"))?;
373    normalize_service_protocols(object)?;
374    serde_json::from_value::<DirectoryService>(item.take())
375        .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))
376}
377
378/// SVC-17 and SEC-08: an origin an index published is checked before a caller is handed it.
379fn require_service_origin(value: Option<&Value>) -> Result<(), DirectoryError> {
380    let origin = value.and_then(Value::as_str).ok_or_else(|| {
381        DirectoryError::InvalidResponse("Directory Service origin is missing".to_owned())
382    })?;
383    let canonical = derive_service_origin(origin)
384        .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
385    if canonical != origin {
386        return Err(DirectoryError::InvalidResponse(
387            "Directory Service origin is not canonical".to_owned(),
388        ));
389    }
390    let url =
391        Url::parse(origin).map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
392    require_public_host(&url)
393}
394
395pub(crate) fn require_public_host(url: &Url) -> Result<(), DirectoryError> {
396    // An address literal is judged outright. A name is not resolved here: nothing is being
397    // reached, and an Agent that later connects resolves and judges it again for itself.
398    let reachable = match url.host() {
399        Some(Host::Ipv4(value)) => is_public(IpAddr::V4(value)),
400        Some(Host::Ipv6(value)) => is_public(IpAddr::V6(value)),
401        Some(Host::Domain(value)) => !is_local_name(value),
402        None => false,
403    };
404    if !reachable {
405        return Err(DirectoryError::InvalidResponse(
406            "Directory Service origin names a non-public address".to_owned(),
407        ));
408    }
409    Ok(())
410}
411
412fn is_local_name(host: &str) -> bool {
413    let host = host.trim_end_matches('.').to_ascii_lowercase();
414    host == "localhost" || host.ends_with(".localhost")
415}
416
417/// An indexing time is an RFC 3339 timestamp, not whatever a date parser happens to accept.
418pub(crate) fn require_indexed_at(value: Option<&Value>) -> Result<(), DirectoryError> {
419    let indexed_at = value.and_then(Value::as_str).ok_or_else(|| {
420        DirectoryError::InvalidResponse("Directory indexing time is missing".to_owned())
421    })?;
422    if !is_rfc3339(indexed_at) {
423        return Err(DirectoryError::InvalidResponse(
424            "Directory indexing time is not an RFC 3339 timestamp".to_owned(),
425        ));
426    }
427    Ok(())
428}
429
430fn is_rfc3339(value: &str) -> bool {
431    let bytes = value.as_bytes();
432    if bytes.len() < 20 || value.chars().count() > 64 {
433        return false;
434    }
435    let digits = |range: std::ops::Range<usize>| bytes[range].iter().all(u8::is_ascii_digit);
436    if !digits(0..4) || bytes[4] != b'-' || !digits(5..7) || bytes[7] != b'-' || !digits(8..10) {
437        return false;
438    }
439    if !matches!(bytes[10], b'T' | b't') {
440        return false;
441    }
442    if !digits(11..13) || bytes[13] != b':' || !digits(14..16) || bytes[16] != b':' {
443        return false;
444    }
445    if !digits(17..19) {
446        return false;
447    }
448    let mut rest = &value[19..];
449    if let Some(fraction) = rest.strip_prefix('.') {
450        let taken = fraction.chars().take_while(char::is_ascii_digit).count();
451        if taken == 0 {
452            return false;
453        }
454        rest = &fraction[taken..];
455    }
456    if matches!(rest, "Z" | "z") {
457        return true;
458    }
459    let offset = rest.as_bytes();
460    offset.len() == 6
461        && matches!(offset[0], b'+' | b'-')
462        && offset[1..3].iter().all(u8::is_ascii_digit)
463        && offset[3] == b':'
464        && offset[4..6].iter().all(u8::is_ascii_digit)
465}
466
467/// A continuation the Directory offers is a reference this client could actually use.
468fn require_continuation(value: Option<&Value>) -> Result<(), DirectoryError> {
469    let Some(value) = value else {
470        return Ok(());
471    };
472    if value.is_null() {
473        return Ok(());
474    }
475    let next = value.as_str().ok_or_else(|| {
476        DirectoryError::InvalidResponse("Directory continuation is invalid".to_owned())
477    })?;
478    if next.trim() != next || next.chars().count() > MAXIMUM_REFERENCE_CHARACTERS {
479        return Err(DirectoryError::InvalidResponse(
480            "Directory continuation is invalid".to_owned(),
481        ));
482    }
483    Ok(())
484}
485
486/// A facet describes how many Services share a value, so the counts have to be countable.
487fn require_facets(value: Option<&Value>) -> Result<(), DirectoryError> {
488    let Some(Value::Object(groups)) = value else {
489        return Ok(());
490    };
491    // A trust facet counts Services by trust protocol. `tap` is the only one this ODP version
492    // names, and a descriptor carries nothing but that name, so anything else describes a
493    // vocabulary this client cannot read and the page as a whole is not usable.
494    if let Some(entries) = groups.get("trust").and_then(Value::as_array) {
495        let readable = entries.iter().all(|entry| {
496            entry
497                .get("value")
498                .and_then(Value::as_object)
499                .is_some_and(|descriptor| {
500                    descriptor.len() == 1
501                        && descriptor.get("name").and_then(Value::as_str) == Some("tap")
502                })
503        });
504        if !readable {
505            return Err(DirectoryError::InvalidResponse(
506                "Directory trust facets are invalid".to_owned(),
507            ));
508        }
509    }
510    for entries in groups.values() {
511        let Some(entries) = entries.as_array() else {
512            return Err(DirectoryError::InvalidResponse(
513                "Directory facets are invalid".to_owned(),
514            ));
515        };
516        if entries.len() > MAXIMUM_FACET_ENTRIES {
517            return Err(DirectoryError::InvalidResponse(
518                "Directory facet exceeds 100 entries".to_owned(),
519            ));
520        }
521        for entry in entries {
522            let countable = entry
523                .get("count")
524                .is_some_and(|count| count.as_u64().is_some());
525            if !countable {
526                return Err(DirectoryError::InvalidResponse(
527                    "Directory facet count is invalid".to_owned(),
528                ));
529            }
530        }
531    }
532    Ok(())
533}
534
535/// The Directory answers suggestions as an envelope, and repeats nothing this client would not.
536fn parse_suggestions(body: &[u8]) -> Result<Vec<String>, DirectoryError> {
537    let value = serde_json::from_slice::<Value>(body)
538        .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
539    let items = value
540        .as_object()
541        .and_then(|object| object.get("items"))
542        .and_then(Value::as_array)
543        .ok_or_else(|| {
544            DirectoryError::InvalidResponse("Directory suggestions are invalid".to_owned())
545        })?;
546    let mut seen = BTreeSet::new();
547    let mut suggestions = Vec::new();
548    for item in items {
549        let suggestion = item.as_str().filter(|value| {
550            !value.trim().is_empty() && value.trim() == *value && value.chars().count() <= 128
551        });
552        let Some(suggestion) = suggestion else {
553            return Err(DirectoryError::InvalidResponse(
554                "Directory suggestions are invalid".to_owned(),
555            ));
556        };
557        if seen.insert(suggestion.to_owned()) {
558            suggestions.push(suggestion.to_owned());
559        }
560        if suggestions.len() == MAXIMUM_SUGGESTIONS {
561            break;
562        }
563    }
564    Ok(suggestions)
565}
566
567/// `read_service` has already established that `object` is a Service-shaped object.
568fn normalize_service_protocols(
569    object: &mut serde_json::Map<String, Value>,
570) -> Result<(), DirectoryError> {
571    let Some(protocols) = object.get("protocols").cloned() else {
572        return Ok(());
573    };
574    let candidate = json!({
575        "description": "Directory protocol validation",
576        "http": {"endpoint_base": "/"},
577        "language": "en",
578        "localizations": ["en"],
579        "name": "Directory Service",
580        "odp_version": "1.0",
581        "operations": [
582            {"authentication": "not-required", "name": "get-offering"},
583            {"authentication": "not-required", "name": "list-offerings"}
584        ],
585        "protocols": protocols
586    });
587    let encoded = serde_json::to_vec(&candidate)
588        .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
589    let document = parse_agent_service_document(&encoded)
590        .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?;
591    if let Some(protocols) = document.protocols {
592        object.insert(
593            "protocols".to_owned(),
594            serde_json::to_value(protocols)
595                .map_err(|error| DirectoryError::InvalidResponse(error.to_string()))?,
596        );
597    } else {
598        object.remove("protocols");
599    }
600    Ok(())
601}
602
603fn bounded(value: usize, maximum: usize, name: &str) -> Result<usize, DirectoryError> {
604    let value = if value == 0 { maximum } else { value };
605    if value > maximum {
606        return Err(DirectoryError::InvalidRequest(format!(
607            "{name} must be from 1 through {maximum}"
608        )));
609    }
610    Ok(value)
611}
612
613fn validate_search_request(request: &SearchRequest) -> Result<(), DirectoryError> {
614    validate_search(&request.query, request.limit, request.filters.as_ref())
615}
616
617fn validate_search(
618    query: &str,
619    limit: usize,
620    filters: Option<&crate::ServiceFilters>,
621) -> Result<(), DirectoryError> {
622    if limit > MAXIMUM_ITEMS_PER_PAGE {
623        return Err(DirectoryError::InvalidRequest(
624            "limit must be from 1 through 100".to_owned(),
625        ));
626    }
627    if query.trim() != query || query.chars().count() > 512 {
628        return Err(DirectoryError::InvalidRequest(
629            "query must contain at most 512 characters without surrounding whitespace".to_owned(),
630        ));
631    }
632    let Some(filters) = filters else {
633        return Ok(());
634    };
635    if let Some(sources) = &filters.sources {
636        if sources.is_empty() || sources.len() > 2 {
637            return Err(DirectoryError::InvalidRequest(
638                "sources must contain one or two distinct odp or openapi values".to_owned(),
639            ));
640        }
641        require_unique(sources, "sources")?;
642    }
643    if filters.keywords.len() > 32
644        || filters
645            .keywords
646            .iter()
647            .any(|value| value.trim().is_empty() || value.chars().count() > 64)
648    {
649        return Err(DirectoryError::InvalidRequest(
650            "keywords must contain at most 32 values of at most 64 characters".to_owned(),
651        ));
652    }
653    require_unique(&filters.keywords, "keywords")?;
654    // A Directory rejects the whole request over a repeated filter, so a caller hears about it
655    // here rather than as an opaque 400.
656    if filters.enrollment.len() > 1 {
657        return Err(DirectoryError::InvalidRequest(
658            "enrollment must contain at most 1 value".to_owned(),
659        ));
660    }
661    if filters.operations.len() > 21 {
662        return Err(DirectoryError::InvalidRequest(
663            "operations must contain at most 21 values".to_owned(),
664        ));
665    }
666    require_unique(&filters.operations, "operations")?;
667    if filters.payments.len() > 32 {
668        return Err(DirectoryError::InvalidRequest(
669            "payments must contain at most 32 values".to_owned(),
670        ));
671    }
672    require_unique(&filters.payments, "payments")?;
673    for payment in &filters.payments {
674        require_unique(&payment.options, "payment options")?;
675    }
676    // A trust filter, when present, is the single-item array `[{"name":"tap"}]`: `tap` is the only
677    // trust protocol this ODP version names, and the Directory refuses anything else.
678    if !filters.trust.is_empty()
679        && (filters.trust.len() != 1 || filters.trust[0].name != Protocol::Tap)
680    {
681        return Err(DirectoryError::InvalidRequest(
682            "trust must be the single-item array [{\"name\":\"tap\"}]".to_owned(),
683        ));
684    }
685    Ok(())
686}
687
688fn require_unique<T: PartialEq>(values: &[T], name: &str) -> Result<(), DirectoryError> {
689    for (index, value) in values.iter().enumerate() {
690        if values[..index].contains(value) {
691            return Err(DirectoryError::InvalidRequest(format!(
692                "{name} must not repeat a value"
693            )));
694        }
695    }
696    Ok(())
697}
698
699fn consume_response(response: HttpResponse) -> Result<HttpResponse, DirectoryError> {
700    let declared = response
701        .headers
702        .get("content-length")
703        .and_then(|value| value.trim().parse::<usize>().ok());
704    let failed = !(200..300).contains(&response.status);
705    // ERR-21: a failure is read under a far tighter limit than a result.
706    let limit = if failed {
707        MAXIMUM_ERROR_BYTES
708    } else {
709        MAXIMUM_RESPONSE_BYTES
710    };
711    if failed {
712        return Err(DirectoryError::Request {
713            message: failure_message(&response, limit, declared),
714            headers: response.headers,
715            status: response.status,
716        });
717    }
718    if declared.is_some_and(|value| value > limit) || response.body.len() > limit {
719        return Err(DirectoryError::InvalidResponse(
720            "Directory response exceeds 524288 bytes".to_owned(),
721        ));
722    }
723    if !media_type(&response.headers).eq_ignore_ascii_case("application/json") {
724        return Err(DirectoryError::InvalidResponse(
725            "Directory response must use application/json".to_owned(),
726        ));
727    }
728    Ok(response)
729}
730
731/// What a failure is worth repeating to a caller.
732///
733/// The status already says what happened; this is the Directory's own account of why. The body
734/// belongs to whoever answered, so it is read only when it claims to be one of the two shapes
735/// that carry a reason, only up to the limit, and only as printable text of bounded length.
736/// Anything else leaves the account empty rather than repeating an unread body.
737fn failure_message(response: &HttpResponse, limit: usize, declared: Option<usize>) -> String {
738    let media_type = media_type(&response.headers);
739    let describable = media_type.eq_ignore_ascii_case("application/json")
740        || media_type.eq_ignore_ascii_case("application/problem+json");
741    if !describable || declared.is_some_and(|value| value > limit) || response.body.len() > limit {
742        return String::new();
743    }
744    let text = String::from_utf8_lossy(&response.body);
745    let detail = serde_json::from_str::<Value>(&text)
746        .ok()
747        .filter(Value::is_object)
748        .and_then(|value| {
749            ["detail", "title", "message"]
750                .iter()
751                .filter_map(|member| value.get(*member).and_then(Value::as_str))
752                .find(|found| !found.trim().is_empty())
753                .map(str::to_owned)
754        })
755        .unwrap_or_else(|| text.into_owned());
756    printable(&detail)
757}
758
759/// Flattens control characters and keeps the excerpt short enough to read.
760fn printable(value: &str) -> String {
761    let flattened = value
762        .chars()
763        .map(|character| {
764            if character.is_control() {
765                ' '
766            } else {
767                character
768            }
769        })
770        .collect::<String>();
771    let collapsed = flattened.split_whitespace().collect::<Vec<_>>().join(" ");
772    if collapsed.chars().count() <= MAXIMUM_ERROR_MESSAGE {
773        return collapsed;
774    }
775    let mut truncated = collapsed
776        .chars()
777        .take(MAXIMUM_ERROR_MESSAGE)
778        .collect::<String>();
779    truncated.push('…');
780    truncated
781}
782
783fn media_type(headers: &BTreeMap<String, String>) -> &str {
784    headers
785        .get("content-type")
786        .map(|value| value.split(';').next().unwrap_or_default().trim())
787        .unwrap_or_default()
788}
789
790#[cfg(test)]
791mod tests {
792    use crate::{Facet, ServiceFilters};
793    use std::sync::Mutex;
794
795    use async_trait::async_trait;
796
797    use super::*;
798
799    struct MockTransport {
800        requests: Mutex<Vec<HttpRequest>>,
801    }
802
803    struct ResponseTransport(Vec<u8>);
804
805    #[async_trait]
806    impl Transport for ResponseTransport {
807        async fn send(&self, _request: HttpRequest) -> Result<HttpResponse, TransportError> {
808            Ok(HttpResponse {
809                body: self.0.clone(),
810                headers: BTreeMap::from([(
811                    "content-type".to_owned(),
812                    "application/json".to_owned(),
813                )]),
814                status: 200,
815            })
816        }
817    }
818
819    #[async_trait]
820    impl Transport for MockTransport {
821        async fn send(&self, request: HttpRequest) -> Result<HttpResponse, TransportError> {
822            self.requests.lock().unwrap().push(request);
823            Ok(HttpResponse {
824                body: br#"{"items":[{"description":"Plants","indexed_at":"2026-08-25T00:00:00Z","language":"en","localizations":["en"],"name":"Indica Flowers","operations":[{"authentication":"not-required","name":"get-offering"},{"authentication":"not-required","name":"list-offerings"}],"protocols":{"trust":[{"name":"tap"}]},"service_origin":"https://demo.inflowpay.ai"}]}"#.to_vec(),
825                headers: BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
826                status: 200,
827            })
828        }
829    }
830
831    #[tokio::test]
832    async fn searches_only_the_selected_canonical_directory() {
833        let transport = Arc::new(MockTransport {
834            requests: Mutex::new(Vec::new()),
835        });
836        let client = DirectoryClient::with_transport(Environment::Sandbox, transport.clone());
837        let page = client
838            .search_services(&SearchRequest {
839                filters: Some(ServiceFilters {
840                    trust: vec![odp_core::TrustProtocol {
841                        name: odp_core::Protocol::Tap,
842                    }],
843                    ..ServiceFilters::default()
844                }),
845                query: "plants".to_owned(),
846                ..SearchRequest::default()
847            })
848            .await
849            .unwrap();
850        assert_eq!(page.items[0].name, "Indica Flowers");
851        assert_eq!(
852            page.items[0].protocols.as_ref().unwrap().trust,
853            [odp_core::TrustProtocol {
854                name: odp_core::Protocol::Tap
855            }]
856        );
857        let requests = transport.requests.lock().unwrap();
858        assert_eq!(
859            requests[0].url,
860            "https://sandbox.inflowpay.ai/v1/services/search"
861        );
862        assert_eq!(requests[0].method, "POST");
863        assert_eq!(
864            serde_json::from_slice::<Value>(&requests[0].body).unwrap(),
865            serde_json::json!({"filters":{"trust":[{"name":"tap"}]},"query":"plants"})
866        );
867    }
868
869    #[tokio::test]
870    async fn decodes_typed_trust_facets() {
871        let body = br#"{"items":[],"facets":{"trust":[{"value":{"name":"tap"},"count":2}]}}"#;
872        let client = DirectoryClient::with_transport(
873            Environment::Production,
874            Arc::new(ResponseTransport(body.to_vec())),
875        );
876
877        let page = client
878            .search_services(&SearchRequest::default())
879            .await
880            .unwrap();
881
882        assert_eq!(
883            page.facets.unwrap().trust,
884            [Facet {
885                count: 2,
886                value: odp_core::TrustProtocol {
887                    name: odp_core::Protocol::Tap,
888                },
889            }]
890        );
891
892        let invalid = br#"{"items":[],"facets":{"trust":[{"value":{"name":"mpp"},"count":2}]}}"#;
893        let client = DirectoryClient::with_transport(
894            Environment::Production,
895            Arc::new(ResponseTransport(invalid.to_vec())),
896        );
897        assert!(
898            client
899                .search_services(&SearchRequest::default())
900                .await
901                .is_err()
902        );
903    }
904
905    #[tokio::test]
906    async fn rejects_unbounded_directory_traversal() {
907        let client = DirectoryClient::with_transport(
908            Environment::Production,
909            Arc::new(MockTransport {
910                requests: Mutex::new(Vec::new()),
911            }),
912        );
913        let error = client
914            .collect_services(
915                &SearchRequest::default(),
916                IterationOptions {
917                    max_items: 10_001,
918                    max_pages: 0,
919                },
920            )
921            .await
922            .unwrap_err();
923        assert!(error.to_string().contains("max_items"));
924    }
925
926    #[tokio::test]
927    async fn rejects_unsupported_trust_filters() {
928        let client = DirectoryClient::with_transport(
929            Environment::Production,
930            Arc::new(MockTransport {
931                requests: Mutex::new(Vec::new()),
932            }),
933        );
934        let error = client
935            .search_services(&SearchRequest {
936                filters: Some(ServiceFilters {
937                    trust: vec![odp_core::TrustProtocol {
938                        name: odp_core::Protocol::Mpp,
939                    }],
940                    ..ServiceFilters::default()
941                }),
942                ..SearchRequest::default()
943            })
944            .await
945            .unwrap_err();
946        assert!(error.to_string().contains("trust"));
947    }
948
949    #[tokio::test]
950    async fn filters_unknown_protocols_and_rejects_malformed_known_protocols() {
951        let body = br#"{"items":[{"description":"Plants","indexed_at":"2026-08-25T00:00:00Z","language":"en","localizations":["en"],"name":"Plants","operations":[],"protocols":{"payments":[{"authentication":"not-required","name":"future-payment"},{"authentication":"not-required","name":"mpp"}],"trust":[{"name":"future-trust"},{"name":"tap"}]},"service_origin":"https://demo.inflowpay.ai"}]}"#;
952        let client = DirectoryClient::with_transport(
953            Environment::Production,
954            Arc::new(ResponseTransport(body.to_vec())),
955        );
956        let page = client
957            .search_services(&SearchRequest::default())
958            .await
959            .unwrap();
960        let protocols = page.items[0].protocols.as_ref().unwrap();
961        assert_eq!(protocols.payments.len(), 1);
962        assert_eq!(protocols.trust.len(), 1);
963
964        let malformed = String::from_utf8_lossy(body)
965            .replace("\"name\":\"mpp\"", "\"name\":\"mpp\",\"unexpected\":true");
966        let client = DirectoryClient::with_transport(
967            Environment::Production,
968            Arc::new(ResponseTransport(malformed.into_bytes())),
969        );
970        // A malformed known protocol makes that one record unusable, and says so, rather than
971        // withholding every other Service on the page.
972        let page = client
973            .search_services(&SearchRequest::default())
974            .await
975            .unwrap();
976        assert!(page.items.is_empty());
977        assert_eq!(page.issues.len(), 1);
978        assert_eq!(page.issues[0].index, 0);
979    }
980}