Skip to main content

odp_service/
service.rs

1use std::{collections::BTreeMap, sync::Arc};
2
3use async_trait::async_trait;
4use odp_core::{
5    AdditionalMembers, AuthenticationRequirement, Collection, CollectionSearchRequest,
6    EnrollmentProtocol, HttpConfiguration, McpEndpoint, Offering, OfferingPage,
7    OfferingSearchRequest, Operation, OperationDescriptor, Page, PaymentProtocol, ProblemDetails,
8    Representation, SearchCapabilities, ServiceBranding, ServiceDocument, ServiceOpenApi,
9    ServiceProtocols, TrustProtocol, VERSION, is_local_resource_identifier, parse_collection,
10    parse_collection_search_request, parse_offering, parse_offering_search_request,
11    parse_offering_search_response, parse_page, parse_service_document,
12};
13use serde_json::json;
14use sha2::{Digest, Sha256};
15use thiserror::Error;
16use url::form_urlencoded;
17
18pub const MEDIA_TYPE: &str = "application/odp+json";
19pub const PROBLEM_MEDIA_TYPE: &str = "application/problem+json";
20const MAXIMUM_REQUEST_BYTES: usize = 65_536;
21const MAXIMUM_RESOURCE_BYTES: usize = 524_288;
22/// ERR-04: the bounds a Problem Details object's own schema puts on what it says.
23const MAXIMUM_TITLE_CHARACTERS: usize = 128;
24const MAXIMUM_DETAIL_CHARACTERS: usize = 2_048;
25/// ERR-32: a Service that turns a request away has to say when to come back.
26const DEFAULT_RETRY_AFTER: u64 = 1;
27
28#[derive(Clone, Debug, Default, Eq, PartialEq)]
29pub struct Request {
30    pub body: Vec<u8>,
31    pub headers: BTreeMap<String, String>,
32    pub method: String,
33    pub path: String,
34    pub query: String,
35}
36
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct Response {
39    pub body: Vec<u8>,
40    pub headers: BTreeMap<String, String>,
41    pub status: u16,
42}
43
44#[derive(Clone, Debug, PartialEq)]
45pub struct CatalogRequest {
46    /// The `Accept-Language` field as the Agent sent it.
47    pub accept_language: Option<String>,
48    pub cursor: Option<String>,
49    /// SVC-58: the localization the Service selected by RFC 4647 Lookup, which is what the
50    /// catalog should answer in. Empty only when the Service advertises no localizations.
51    pub language: String,
52    pub limit: usize,
53    pub path: String,
54    pub representation: Representation,
55}
56
57impl Default for CatalogRequest {
58    fn default() -> Self {
59        Self {
60            accept_language: None,
61            cursor: None,
62            language: String::new(),
63            limit: 0,
64            path: String::new(),
65            representation: Representation::Terse,
66        }
67    }
68}
69
70#[derive(Debug, Error)]
71pub enum ServiceError {
72    #[error("invalid Service configuration: {0}")]
73    InvalidConfiguration(String),
74    #[error("invalid Service response: {0}")]
75    InvalidResponse(String),
76    #[error("catalog operation failed: {0}")]
77    Catalog(String),
78    #[error("{message}")]
79    Request {
80        code: &'static str,
81        message: String,
82        /// ERR-32 and ERR-33: how many seconds an Agent should wait. A `429` that names none
83        /// is given a default, because the field is required there.
84        retry_after: Option<u64>,
85        status: u16,
86    },
87}
88
89impl ServiceError {
90    /// A failure an Agent caused, described the way ODP describes one.
91    #[must_use]
92    pub fn request(status: u16, code: &'static str, message: impl Into<String>) -> Self {
93        Self::Request {
94            code,
95            message: message.into(),
96            retry_after: None,
97            status,
98        }
99    }
100
101    /// A failure an Agent should retry after `seconds`.
102    #[must_use]
103    pub fn retry_after(
104        status: u16,
105        code: &'static str,
106        message: impl Into<String>,
107        seconds: u64,
108    ) -> Self {
109        Self::Request {
110            code,
111            message: message.into(),
112            retry_after: Some(seconds),
113            status,
114        }
115    }
116}
117
118#[async_trait]
119pub trait Catalog: Send + Sync {
120    fn operations(&self) -> Vec<Operation>;
121
122    /// Resumes a search using the opaque cursor, without reconstructing the original query.
123    async fn continue_offering_search(
124        &self,
125        _request: CatalogRequest,
126    ) -> Result<OfferingPage<Offering>, ServiceError> {
127        Err(ServiceError::request(
128            410,
129            "CONTINUATION_EXPIRED",
130            "Search continuation is unavailable",
131        ))
132    }
133
134    /// Resumes a Collection search using the opaque cursor.
135    async fn continue_collection_search(
136        &self,
137        _request: CatalogRequest,
138    ) -> Result<Page<Collection>, ServiceError> {
139        Err(ServiceError::request(
140            410,
141            "CONTINUATION_EXPIRED",
142            "Search continuation is unavailable",
143        ))
144    }
145
146    async fn list_offerings(
147        &self,
148        request: CatalogRequest,
149    ) -> Result<OfferingPage<Offering>, ServiceError>;
150
151    async fn get_offering(
152        &self,
153        id: &str,
154        request: CatalogRequest,
155    ) -> Result<Option<Offering>, ServiceError>;
156
157    async fn search_offerings(
158        &self,
159        _query: OfferingSearchRequest,
160        _request: CatalogRequest,
161    ) -> Result<OfferingPage<Offering>, ServiceError> {
162        Err(ServiceError::Catalog(
163            "search-offerings is unsupported".to_owned(),
164        ))
165    }
166
167    async fn list_collections(
168        &self,
169        _request: CatalogRequest,
170    ) -> Result<Page<Collection>, ServiceError> {
171        Err(ServiceError::Catalog(
172            "list-collections is unsupported".to_owned(),
173        ))
174    }
175
176    async fn get_collection(
177        &self,
178        _id: &str,
179        _request: CatalogRequest,
180    ) -> Result<Option<Collection>, ServiceError> {
181        Err(ServiceError::Catalog(
182            "get-collection is unsupported".to_owned(),
183        ))
184    }
185
186    async fn search_collections(
187        &self,
188        _query: CollectionSearchRequest,
189        _request: CatalogRequest,
190    ) -> Result<Page<Collection>, ServiceError> {
191        Err(ServiceError::Catalog(
192            "search-collections is unsupported".to_owned(),
193        ))
194    }
195
196    async fn list_collection_offerings(
197        &self,
198        _collection_id: &str,
199        _request: CatalogRequest,
200    ) -> Result<OfferingPage<Offering>, ServiceError> {
201        Err(ServiceError::Catalog(
202            "list-collection-offerings is unsupported".to_owned(),
203        ))
204    }
205}
206
207pub struct ServiceBuilder {
208    document: ServiceDocument,
209}
210
211impl ServiceBuilder {
212    pub fn new(
213        name: impl Into<String>,
214        description: impl Into<String>,
215        language: impl Into<String>,
216        endpoint_base: impl Into<String>,
217    ) -> Self {
218        let language = language.into();
219        Self {
220            document: ServiceDocument {
221                additional: AdditionalMembers::new(),
222                branding: None,
223                description: description.into(),
224                documentation_url: String::new(),
225                http: HttpConfiguration {
226                    additional: AdditionalMembers::new(),
227                    endpoint_base: endpoint_base.into(),
228                    openapi: None,
229                },
230                keywords: Vec::new(),
231                language: language.clone(),
232                localizations: vec![language],
233                mcp: Vec::new(),
234                name: name.into(),
235                odp_version: VERSION.to_owned(),
236                operations: Vec::new(),
237                payment_origins: Vec::new(),
238                protocols: None,
239                search_capabilities: None,
240                status_url: String::new(),
241                support_url: String::new(),
242                website_url: String::new(),
243            },
244        }
245    }
246
247    pub fn branding(mut self, branding: ServiceBranding) -> Self {
248        self.document.branding = Some(branding);
249        self
250    }
251
252    pub fn documentation_url(mut self, url: impl Into<String>) -> Self {
253        self.document.documentation_url = url.into();
254        self
255    }
256
257    pub fn keywords<I, S>(mut self, keywords: I) -> Self
258    where
259        I: IntoIterator<Item = S>,
260        S: Into<String>,
261    {
262        self.document.keywords = keywords.into_iter().map(Into::into).collect();
263        self
264    }
265
266    pub fn localizations<I, S>(mut self, localizations: I) -> Self
267    where
268        I: IntoIterator<Item = S>,
269        S: Into<String>,
270    {
271        self.document.localizations = localizations.into_iter().map(Into::into).collect();
272        self
273    }
274
275    pub fn mcp(mut self, endpoints: Vec<McpEndpoint>) -> Self {
276        self.document.mcp = endpoints;
277        self
278    }
279
280    pub fn openapi(mut self, openapi: ServiceOpenApi) -> Self {
281        self.document.http.openapi = Some(openapi);
282        self
283    }
284
285    pub fn operation_authentication(
286        mut self,
287        operation: Operation,
288        authentication: AuthenticationRequirement,
289    ) -> Self {
290        if let Some(descriptor) = self
291            .document
292            .operations
293            .iter_mut()
294            .find(|descriptor| descriptor.name == operation)
295        {
296            descriptor.authentication = authentication;
297        } else {
298            self.document.operations.push(OperationDescriptor {
299                authentication,
300                name: operation,
301            });
302        }
303        self
304    }
305
306    pub fn payment_origins<I, S>(mut self, origins: I) -> Self
307    where
308        I: IntoIterator<Item = S>,
309        S: Into<String>,
310    {
311        self.document.payment_origins = origins.into_iter().map(Into::into).collect();
312        self
313    }
314
315    pub fn protocols(
316        mut self,
317        enrollment: Vec<EnrollmentProtocol>,
318        payments: Vec<PaymentProtocol>,
319    ) -> Self {
320        self.document.protocols = Some(ServiceProtocols {
321            enrollment,
322            payments,
323            trust: Vec::new(),
324        });
325        self
326    }
327
328    pub fn trust(mut self, protocols: Vec<TrustProtocol>) -> Self {
329        self.document
330            .protocols
331            .get_or_insert_with(ServiceProtocols::default)
332            .trust = protocols;
333        self
334    }
335
336    pub fn search_capabilities(mut self, capabilities: SearchCapabilities) -> Self {
337        self.document.search_capabilities = Some(capabilities);
338        self
339    }
340
341    pub fn status_url(mut self, url: impl Into<String>) -> Self {
342        self.document.status_url = url.into();
343        self
344    }
345
346    pub fn support_url(mut self, url: impl Into<String>) -> Self {
347        self.document.support_url = url.into();
348        self
349    }
350
351    pub fn website_url(mut self, url: impl Into<String>) -> Self {
352        self.document.website_url = url.into();
353        self
354    }
355
356    pub fn build(self, catalog: Arc<dyn Catalog>) -> Result<Service, ServiceError> {
357        Service::new(self.document, catalog)
358    }
359}
360
361pub struct Service {
362    catalog: Arc<dyn Catalog>,
363    document: ServiceDocument,
364    endpoint_base: String,
365}
366
367impl Service {
368    pub fn new(
369        mut document: ServiceDocument,
370        catalog: Arc<dyn Catalog>,
371    ) -> Result<Self, ServiceError> {
372        let operations = catalog.operations();
373        if !operations.contains(&Operation::ListOfferings)
374            || !operations.contains(&Operation::GetOffering)
375        {
376            return Err(ServiceError::InvalidConfiguration(
377                "Catalog must support list-offerings and get-offering".to_owned(),
378            ));
379        }
380        document.odp_version = VERSION.to_owned();
381        document.operations = operations
382            .into_iter()
383            .map(|name| OperationDescriptor {
384                authentication: document
385                    .operations
386                    .iter()
387                    .find(|descriptor| descriptor.name == name)
388                    .map(|descriptor| descriptor.authentication)
389                    .unwrap_or(AuthenticationRequirement::NotRequired),
390                name,
391            })
392            .collect();
393        let encoded = serde_json::to_vec(&document)
394            .map_err(|error| ServiceError::InvalidConfiguration(error.to_string()))?;
395        document = parse_service_document(&encoded)
396            .map_err(|error| ServiceError::InvalidConfiguration(error.to_string()))?;
397        // SVC-83 and SVC-84: a Service that cannot serve its own Service Document within the
398        // limit is misconfigured, and says so now rather than failing every request later.
399        if serde_json::to_vec(&document)
400            .map_err(|error| ServiceError::InvalidConfiguration(error.to_string()))?
401            .len()
402            > MAXIMUM_REQUEST_BYTES
403        {
404            return Err(ServiceError::InvalidConfiguration(
405                "Service Document exceeds 65536 bytes".to_owned(),
406            ));
407        }
408        let endpoint_base = document.http.endpoint_base.trim_end_matches('/').to_owned();
409        Ok(Self {
410            catalog,
411            document,
412            endpoint_base,
413        })
414    }
415
416    pub fn document(&self) -> ServiceDocument {
417        self.document.clone()
418    }
419
420    pub async fn handle(&self, request: Request) -> Response {
421        // A HEAD is the GET it shadows, answered without the body (RFC 9110). Deciding it here
422        // means every resource that answers GET answers HEAD, with the same headers.
423        let head = request.method.eq_ignore_ascii_case("HEAD");
424        let retrieval = head || request.method.eq_ignore_ascii_case("GET");
425        let conditional = request.headers.get("if-none-match").cloned();
426        let mut request = request;
427        if head {
428            request.method = "GET".to_owned();
429        }
430        let mut response = match self.handle_result(request).await {
431            Ok(response) => response,
432            Err(ServiceError::Request {
433                code,
434                message,
435                retry_after,
436                status,
437            }) => problem_with_retry(status, code, &message, retry_after),
438            Err(error) => problem(500, "INTERNAL_ERROR", &error.to_string()),
439        };
440        // PAG-31 and SVC-61: an entity tag distinguishes variants, and a validator that still
441        // matches means the Agent already holds this representation.
442        if response.status == 200 {
443            if let Some(etag) = response.headers.get("etag").cloned() {
444                if conditional.is_some_and(|value| matches_etag(&value, &etag)) {
445                    response.body.clear();
446                    response.status = if retrieval { 304 } else { 412 };
447                    response.headers.remove("content-type");
448                }
449            }
450        }
451        if head && response.status != 304 {
452            response
453                .headers
454                .insert("content-length".to_owned(), response.body.len().to_string());
455            response.body.clear();
456        }
457        response
458    }
459
460    async fn handle_result(&self, request: Request) -> Result<Response, ServiceError> {
461        if !accepts_odp(request.headers.get("accept").map(String::as_str)) {
462            return Ok(problem(
463                406,
464                "NOT_ACCEPTABLE",
465                "Accept must allow application/odp+json",
466            ));
467        }
468        // SVC-58 and SVC-59: Lookup against what the Service actually publishes, and fall back to
469        // the default representation rather than refusing the request.
470        let language = self.select_language(request.headers.get("accept-language"));
471        if request.path == "/.well-known/odp" {
472            if request.method != "GET" {
473                return Ok(method_not_allowed("GET, HEAD"));
474            }
475            return self.represent(200, &self.document, MAXIMUM_REQUEST_BYTES, &language);
476        }
477        let Some(path) = request.path.strip_prefix(&self.endpoint_base) else {
478            return Ok(problem(404, "NOT_FOUND", "ODP resource not found"));
479        };
480        if let Some(operation) = path_operation(request.method.as_str(), path) {
481            if !self
482                .document
483                .operations
484                .iter()
485                .any(|descriptor| descriptor.name == operation)
486            {
487                return Ok(problem(404, "NOT_FOUND", "ODP operation is not supported"));
488            }
489        }
490        let mut input = catalog_request(&request, language.clone())?;
491        if !url::form_urlencoded::parse(request.query.as_bytes())
492            .any(|(key, _)| key == "representation")
493            && matches!(
494                path_operation(request.method.as_str(), path),
495                Some(Operation::GetOffering | Operation::GetCollection)
496            )
497        {
498            input.representation = Representation::Full;
499        }
500        let limit = input.limit;
501        match (request.method.as_str(), path) {
502            ("GET", "/offerings") => {
503                let representation = input.representation;
504                let page = self.catalog.list_offerings(input).await?;
505                validate_offering_page(&page, false, representation, limit, &request)?;
506                self.represent(200, &page, MAXIMUM_RESOURCE_BYTES, &language)
507            }
508            ("POST", "/offerings/search") => {
509                let query = decode_offering_search(&request)?;
510                input.limit = query.limit;
511                let limit = input.limit;
512                let representation = input.representation;
513                let page = self.catalog.search_offerings(query, input).await?;
514                validate_offering_page(&page, true, representation, limit, &request)?;
515                self.represent(200, &page, MAXIMUM_RESOURCE_BYTES, &language)
516            }
517            ("GET", "/collections") => {
518                let representation = input.representation;
519                let page = self.catalog.list_collections(input).await?;
520                validate_collection_page(&page, representation, limit, &request)?;
521                self.represent(200, &page, MAXIMUM_RESOURCE_BYTES, &language)
522            }
523            ("POST", "/collections/search") => {
524                let query = decode_collection_search(&request)?;
525                input.limit = query.limit;
526                let limit = input.limit;
527                let representation = input.representation;
528                let page = self.catalog.search_collections(query, input).await?;
529                validate_collection_page(&page, representation, limit, &request)?;
530                self.represent(200, &page, MAXIMUM_RESOURCE_BYTES, &language)
531            }
532            ("GET", "/offerings/search") | ("GET", "/collections/search") => {
533                if input.cursor.as_ref().is_none_or(String::is_empty) {
534                    return Err(request_error(
535                        400,
536                        "INVALID_REQUEST",
537                        "Search continuation requires a cursor",
538                    ));
539                }
540                let representation = input.representation;
541                if path == "/offerings/search" {
542                    let page = self.catalog.continue_offering_search(input).await?;
543                    validate_offering_page(&page, true, representation, limit, &request)?;
544                    self.represent(200, &page, MAXIMUM_RESOURCE_BYTES, &language)
545                } else {
546                    let page = self.catalog.continue_collection_search(input).await?;
547                    validate_collection_page(&page, representation, limit, &request)?;
548                    self.represent(200, &page, MAXIMUM_RESOURCE_BYTES, &language)
549                }
550            }
551            (_, value) if RESERVED_PATHS.contains(&value) => {
552                Ok(method_not_allowed(allowed_methods(value)))
553            }
554            ("GET", _) => self.get_path(path, input, &request, &language).await,
555            (_, value) => Ok(method_not_allowed(allowed_methods(value))),
556        }
557    }
558
559    async fn get_path(
560        &self,
561        path: &str,
562        input: CatalogRequest,
563        request: &Request,
564        language: &str,
565    ) -> Result<Response, ServiceError> {
566        if let Some(id) = path.strip_prefix("/offerings/") {
567            if !is_local_resource_identifier(id) {
568                return Ok(problem(
569                    400,
570                    "INVALID_REQUEST",
571                    "Offering identifier is invalid",
572                ));
573            }
574            let representation = input.representation;
575            return match self.catalog.get_offering(id, input).await? {
576                Some(offering) if offering.id == id => {
577                    let encoded = serde_json::to_vec(&offering)
578                        .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
579                    parse_offering(&encoded)
580                        .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
581                    validate_offering_representation(&offering, representation)?;
582                    self.represent(200, &offering, MAXIMUM_RESOURCE_BYTES, language)
583                }
584                Some(_) => Err(ServiceError::InvalidResponse(
585                    "Offering identifier does not match request path".to_owned(),
586                )),
587                None => Ok(problem(404, "NOT_FOUND", "Offering not found")),
588            };
589        }
590        if let Some(value) = path.strip_prefix("/collections/") {
591            let limit = input.limit;
592            if let Some(id) = value.strip_suffix("/offerings") {
593                // IDN-08: a Collection identifier is checked the way an Offering identifier is,
594                // so a path that could never name a resource never reaches the catalog.
595                if !is_local_resource_identifier(id) {
596                    return Ok(problem(
597                        400,
598                        "INVALID_REQUEST",
599                        "Collection identifier is invalid",
600                    ));
601                }
602                let representation = input.representation;
603                let page = self.catalog.list_collection_offerings(id, input).await?;
604                validate_offering_page(&page, false, representation, limit, request)?;
605                return self.represent(200, &page, MAXIMUM_RESOURCE_BYTES, language);
606            }
607            if !is_local_resource_identifier(value) {
608                return Ok(problem(
609                    400,
610                    "INVALID_REQUEST",
611                    "Collection identifier is invalid",
612                ));
613            }
614            let representation = input.representation;
615            return match self.catalog.get_collection(value, input).await? {
616                Some(collection) if collection.id == value => {
617                    let encoded = serde_json::to_vec(&collection)
618                        .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
619                    parse_collection(&encoded)
620                        .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
621                    validate_collection_representation(&collection, representation)?;
622                    self.represent(200, &collection, MAXIMUM_RESOURCE_BYTES, language)
623                }
624                Some(_) => Err(ServiceError::InvalidResponse(
625                    "Collection identifier does not match request path".to_owned(),
626                )),
627                None => Ok(problem(404, "NOT_FOUND", "Collection not found")),
628            };
629        }
630        Ok(problem(404, "NOT_FOUND", "ODP resource not found"))
631    }
632
633    /// SVC-58: RFC 4647 Lookup against the localizations the Service Document advertises.
634    ///
635    /// Lookup walks a range down its own subtags and never sideways, so `de-CH-1901` finds
636    /// `de-CH` and then `de`, but never `de-DE`.
637    fn select_language(&self, accept_language: Option<&String>) -> String {
638        let default = self.document.language.clone();
639        let Some(header) = accept_language else {
640            return default;
641        };
642        for range in ranges_by_weight(header) {
643            if range == "*" {
644                return default;
645            }
646            let mut candidate = range.as_str();
647            loop {
648                if let Some(found) = self
649                    .document
650                    .localizations
651                    .iter()
652                    .find(|value| value.eq_ignore_ascii_case(candidate))
653                {
654                    return found.clone();
655                }
656                let Some(shorter) = candidate.rsplit_once('-') else {
657                    break;
658                };
659                candidate = shorter.0;
660                // RFC 4647: a single-character subtag introduces an extension rather than naming
661                // a language, so truncating to it would leave a range no tag can match.
662                if let Some((prefix, subtag)) = candidate.rsplit_once('-') {
663                    if subtag.len() == 1 {
664                        candidate = prefix;
665                    }
666                }
667            }
668        }
669        // SVC-59: nothing matched, so the default representation is returned, not a 406.
670        default
671    }
672
673    /// Serializes an ODP representation with the fields that describe the variant it is.
674    fn represent<T: serde::Serialize>(
675        &self,
676        status: u16,
677        value: &T,
678        maximum_bytes: usize,
679        language: &str,
680    ) -> Result<Response, ServiceError> {
681        let mut response = json_response(status, value, maximum_bytes)?;
682        if !language.is_empty() {
683            // SVC-60: say which variant this is, and that the choice depends on the request.
684            response
685                .headers
686                .insert("content-language".to_owned(), language.to_owned());
687            response
688                .headers
689                .insert("vary".to_owned(), "Accept-Language".to_owned());
690        }
691        // SVC-61: the tag covers the language too, so two variants never share one.
692        response
693            .headers
694            .insert("etag".to_owned(), entity_tag(&response.body, language));
695        Ok(response)
696    }
697}
698
699fn catalog_request(request: &Request, language: String) -> Result<CatalogRequest, ServiceError> {
700    let mut parameters: BTreeMap<String, Vec<String>> = BTreeMap::new();
701    for (name, value) in form_urlencoded::parse(request.query.as_bytes()).into_owned() {
702        parameters.entry(name).or_default().push(value);
703    }
704    // SVC-73: a repeated `representation` describes two requests, and the Service answers
705    // neither. The same reasoning applies to the other single-valued parameters.
706    for name in ["representation", "limit", "cursor"] {
707        if parameters.get(name).is_some_and(|values| values.len() > 1) {
708            return Err(request_error(
709                400,
710                "INVALID_REQUEST",
711                &format!("{name} must not be repeated"),
712            ));
713        }
714    }
715    let single = |name: &str| parameters.get(name).and_then(|values| values.first());
716    let representation = match single("representation").map(String::as_str) {
717        None | Some("terse") => Representation::Terse,
718        Some("full") => Representation::Full,
719        Some(_) => {
720            return Err(request_error(
721                400,
722                "INVALID_REQUEST",
723                "representation is invalid",
724            ));
725        }
726    };
727    let limit = single("limit")
728        .map(|value| value.parse::<usize>())
729        .transpose()
730        .map_err(|_| request_error(400, "INVALID_REQUEST", "limit is invalid"))?
731        .unwrap_or(0);
732    if limit > 100 || (limit == 0 && single("limit").is_some()) {
733        return Err(request_error(
734            400,
735            "INVALID_REQUEST",
736            "limit must be from 1 through 100",
737        ));
738    }
739    Ok(CatalogRequest {
740        accept_language: request.headers.get("accept-language").cloned(),
741        cursor: single("cursor").cloned(),
742        language,
743        limit,
744        path: request.path.clone(),
745        representation,
746    })
747}
748
749/// The language ranges of an `Accept-Language` field, most preferred first.
750///
751/// A range weighted zero is not acceptable at all, so it is dropped rather than ordered last.
752fn ranges_by_weight(header: &str) -> Vec<String> {
753    let mut ranges = header
754        .split(',')
755        .filter_map(|entry| {
756            let mut parts = entry.split(';');
757            let range = parts.next().unwrap_or_default().trim();
758            if range.is_empty() {
759                return None;
760            }
761            let weight = quality(parts);
762            (weight > 0.0).then(|| (range.to_owned(), weight))
763        })
764        .collect::<Vec<_>>();
765    // A stable sort keeps equally weighted ranges in the order the Agent wrote them.
766    ranges.sort_by(|left, right| right.1.total_cmp(&left.1));
767    ranges.into_iter().map(|(range, _)| range).collect()
768}
769
770/// The `q` parameter of one media range or language range, defaulting to 1.
771fn quality<'a>(parameters: impl Iterator<Item = &'a str>) -> f32 {
772    for parameter in parameters {
773        let Some((name, value)) = parameter.split_once('=') else {
774            continue;
775        };
776        if name.trim().eq_ignore_ascii_case("q") {
777            return value.trim().parse::<f32>().unwrap_or(0.0);
778        }
779    }
780    1.0
781}
782
783fn validate_search_request(request: &Request) -> Result<(), ServiceError> {
784    if request.body.len() > MAXIMUM_REQUEST_BYTES {
785        return Err(request_error(
786            413,
787            "REQUEST_TOO_LARGE",
788            "request body is too large",
789        ));
790    }
791    // MED-06: a media type is compared by its essence, which is case-insensitive and carries no
792    // surrounding whitespace (RFC 9110).
793    let essence = request
794        .headers
795        .get("content-type")
796        .map(|value| value.split(';').next().unwrap_or_default().trim())
797        .unwrap_or_default();
798    if !essence.eq_ignore_ascii_case(MEDIA_TYPE) {
799        return Err(request_error(
800            415,
801            "UNSUPPORTED_MEDIA_TYPE",
802            &format!("Content-Type must be {MEDIA_TYPE}"),
803        ));
804    }
805    Ok(())
806}
807
808fn decode_offering_search(request: &Request) -> Result<OfferingSearchRequest, ServiceError> {
809    validate_search_request(request)?;
810    parse_offering_search_request(&request.body)
811        .map_err(|error| request_error(400, "INVALID_REQUEST", &error.to_string()))
812}
813
814fn decode_collection_search(request: &Request) -> Result<CollectionSearchRequest, ServiceError> {
815    validate_search_request(request)?;
816    parse_collection_search_request(&request.body)
817        .map_err(|error| request_error(400, "INVALID_REQUEST", &error.to_string()))
818}
819
820fn request_error(status: u16, code: &'static str, message: &str) -> ServiceError {
821    ServiceError::request(status, code, message)
822}
823
824/// PAG-11 and PAG-14: what a page owes the request that produced it.
825fn validate_page_envelope(
826    next: &str,
827    items: usize,
828    limit: usize,
829    request: &Request,
830) -> Result<(), ServiceError> {
831    // PAG-14 lets a Service answer with fewer items than asked for, never with more.
832    if limit != 0 && items > limit {
833        return Err(ServiceError::InvalidResponse(
834            "Catalog returned more items than the request allows".to_owned(),
835        ));
836    }
837    if next.is_empty() {
838        return Ok(());
839    }
840    // PAG-11: a continuation that points at the request it answers never advances.
841    let current = if request.query.is_empty() {
842        request.path.clone()
843    } else {
844        format!("{}?{}", request.path, request.query)
845    };
846    if next == current {
847        return Err(ServiceError::InvalidResponse(
848            "Catalog returned the request URL as its own continuation".to_owned(),
849        ));
850    }
851    Ok(())
852}
853
854fn validate_offering_page(
855    page: &OfferingPage<Offering>,
856    search_response: bool,
857    representation: Representation,
858    limit: usize,
859    request: &Request,
860) -> Result<(), ServiceError> {
861    validate_page_envelope(&page.next, page.items.len(), limit, request)?;
862    let encoded = serde_json::to_vec(page)
863        .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
864    if search_response {
865        parse_offering_search_response(&encoded)
866            .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
867    } else {
868        parse_page::<serde_json::Value>(&encoded)
869            .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
870    }
871    for offering in &page.items {
872        let mut inherited = offering.clone();
873        if inherited.odp_version.is_empty() {
874            inherited.odp_version.clone_from(&page.odp_version);
875        }
876        let encoded = serde_json::to_vec(&inherited)
877            .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
878        parse_offering(&encoded)
879            .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
880        validate_offering_representation(offering, representation)?;
881    }
882    Ok(())
883}
884
885fn validate_collection_page(
886    page: &Page<Collection>,
887    representation: Representation,
888    limit: usize,
889    request: &Request,
890) -> Result<(), ServiceError> {
891    validate_page_envelope(&page.next, page.items.len(), limit, request)?;
892    let encoded = serde_json::to_vec(page)
893        .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
894    parse_page::<serde_json::Value>(&encoded)
895        .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
896    for collection in &page.items {
897        let mut inherited = collection.clone();
898        if inherited.odp_version.is_empty() {
899            inherited.odp_version.clone_from(&page.odp_version);
900        }
901        let encoded = serde_json::to_vec(&inherited)
902            .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
903        parse_collection(&encoded)
904            .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
905        validate_collection_representation(collection, representation)?;
906    }
907    Ok(())
908}
909
910fn validate_offering_representation(
911    offering: &Offering,
912    representation: Representation,
913) -> Result<(), ServiceError> {
914    if representation == Representation::Terse && !offering.actions.is_empty() {
915        return Err(ServiceError::InvalidResponse(
916            "Catalog returned Actions in a Terse Offering".to_owned(),
917        ));
918    }
919    if representation == Representation::Full && !offering.detail_fields.is_empty() {
920        return Err(ServiceError::InvalidResponse(
921            "Catalog returned detail_fields in a Full Offering".to_owned(),
922        ));
923    }
924    Ok(())
925}
926
927fn validate_collection_representation(
928    collection: &Collection,
929    representation: Representation,
930) -> Result<(), ServiceError> {
931    if representation == Representation::Full && !collection.detail_fields.is_empty() {
932        return Err(ServiceError::InvalidResponse(
933            "Catalog returned detail_fields in a Full Collection".to_owned(),
934        ));
935    }
936    Ok(())
937}
938
939/// The two paths that name an operation rather than a resource.
940///
941/// `/offerings/search` is the search endpoint, so it is never read as an Offering called
942/// `search`, however valid that identifier would otherwise be.
943const RESERVED_PATHS: &[&str] = &["/offerings/search", "/collections/search"];
944
945fn path_operation(method: &str, path: &str) -> Option<Operation> {
946    match (method, path) {
947        ("GET", "/offerings") => Some(Operation::ListOfferings),
948        ("POST" | "GET", "/offerings/search") => Some(Operation::SearchOfferings),
949        ("GET", "/collections") => Some(Operation::ListCollections),
950        ("POST" | "GET", "/collections/search") => Some(Operation::SearchCollections),
951        (_, value) if RESERVED_PATHS.contains(&value) => None,
952        ("GET", value) if value.starts_with("/offerings/") => Some(Operation::GetOffering),
953        ("GET", value) if value.starts_with("/collections/") && value.ends_with("/offerings") => {
954            Some(Operation::ListCollectionOfferings)
955        }
956        ("GET", value) if value.starts_with("/collections/") => Some(Operation::GetCollection),
957        _ => None,
958    }
959}
960
961fn json_response<T: serde::Serialize>(
962    status: u16,
963    value: &T,
964    maximum_bytes: usize,
965) -> Result<Response, ServiceError> {
966    let mut document = serde_json::to_value(value)
967        .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
968    odp_core::validate_json_depth(
969        &document,
970        if maximum_bytes == MAXIMUM_REQUEST_BYTES {
971            8
972        } else {
973            16
974        },
975    )
976    .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
977    if let Some(version) = document.get_mut("odp_version") {
978        *version = serde_json::Value::String(VERSION.to_owned());
979    }
980    if let Some(items) = document
981        .get_mut("items")
982        .and_then(serde_json::Value::as_array_mut)
983    {
984        for item in items {
985            if let Some(version) = item.get_mut("odp_version") {
986                *version = serde_json::Value::String(VERSION.to_owned());
987            }
988        }
989    }
990    let body = serde_json::to_vec(&document)
991        .map_err(|error| ServiceError::InvalidResponse(error.to_string()))?;
992    if body.len() > maximum_bytes {
993        return Err(ServiceError::InvalidResponse(
994            "response body is too large".to_owned(),
995        ));
996    }
997    Ok(Response {
998        body,
999        headers: BTreeMap::from([("content-type".to_owned(), MEDIA_TYPE.to_owned())]),
1000        status,
1001    })
1002}
1003
1004fn problem(status: u16, code: &str, detail: &str) -> Response {
1005    problem_with_retry(status, code, detail, None)
1006}
1007
1008fn problem_with_retry(status: u16, code: &str, detail: &str, retry_after: Option<u64>) -> Response {
1009    let value = ProblemDetails {
1010        additional: BTreeMap::new(),
1011        code: code.to_owned(),
1012        // ERR-04: a Problem Details object that breaks its own limits describes nothing.
1013        detail: bounded(detail, MAXIMUM_DETAIL_CHARACTERS),
1014        instance: String::new(),
1015        invalid_params: Vec::new(),
1016        problem_type: format!(
1017            "https://offeringprotocol.org/problems/{}",
1018            code.to_ascii_lowercase().replace('_', "-")
1019        ),
1020        status,
1021        title: bounded(detail, MAXIMUM_TITLE_CHARACTERS),
1022    };
1023    let mut headers = BTreeMap::from([("content-type".to_owned(), PROBLEM_MEDIA_TYPE.to_owned())]);
1024    // ERR-32 requires Retry-After on a 429 and ERR-33 asks for it on a 503, so a Service that
1025    // named no interval still tells the Agent to come back rather than leaving it to guess.
1026    if matches!(status, 429 | 503) {
1027        headers.insert(
1028            "retry-after".to_owned(),
1029            retry_after.unwrap_or(DEFAULT_RETRY_AFTER).to_string(),
1030        );
1031    } else if let Some(seconds) = retry_after {
1032        headers.insert("retry-after".to_owned(), seconds.to_string());
1033    }
1034    Response {
1035        body: serde_json::to_vec(&value)
1036            .unwrap_or_else(|_| json!({"status":500}).to_string().into_bytes()),
1037        headers,
1038        status,
1039    }
1040}
1041
1042/// Keeps a message within a code-point bound, marking where it was cut.
1043fn bounded(value: &str, maximum: usize) -> String {
1044    if value.chars().count() <= maximum {
1045        return value.to_owned();
1046    }
1047    let mut kept = value.chars().take(maximum - 1).collect::<String>();
1048    kept.push('…');
1049    kept
1050}
1051
1052/// A 405 states what the resource does allow (RFC 9110).
1053fn method_not_allowed(allow: &str) -> Response {
1054    let mut response = problem(
1055        405,
1056        "METHOD_NOT_ALLOWED",
1057        "ODP operation uses a fixed HTTP method",
1058    );
1059    response
1060        .headers
1061        .insert("allow".to_owned(), allow.to_owned());
1062    response
1063}
1064
1065fn allowed_methods(path: &str) -> &'static str {
1066    match path {
1067        "/offerings/search" | "/collections/search" => "POST, GET, HEAD",
1068        _ => "GET, HEAD",
1069    }
1070}
1071
1072/// MED-03 and MED-04: whether the request's `Accept` permits an ODP representation.
1073///
1074/// The most specific range that matches decides, and a range weighted zero rejects rather than
1075/// merely deprioritizes — so `application/odp+json;q=0` is a refusal, not a preference.
1076fn accepts_odp(value: Option<&str>) -> bool {
1077    let Some(value) = value else {
1078        return true;
1079    };
1080    if value.trim().is_empty() {
1081        return true;
1082    }
1083    let mut best: Option<(u8, f32)> = None;
1084    for entry in value.split(',') {
1085        let mut parts = entry.split(';');
1086        let media_range = parts.next().unwrap_or_default().trim();
1087        let specificity = if media_range.eq_ignore_ascii_case(MEDIA_TYPE) {
1088            2
1089        } else if media_range.eq_ignore_ascii_case("application/*") {
1090            1
1091        } else if media_range == "*/*" {
1092            0
1093        } else {
1094            continue;
1095        };
1096        let weight = quality(parts);
1097        if best.is_none_or(|(found, _)| specificity > found) {
1098            best = Some((specificity, weight));
1099        }
1100    }
1101    best.is_some_and(|(_, weight)| weight > 0.0)
1102}
1103
1104/// SVC-61: a strong validator over the bytes served and the variant they represent.
1105fn entity_tag(body: &[u8], language: &str) -> String {
1106    let mut digest = Sha256::new();
1107    digest.update(language.as_bytes());
1108    digest.update([0]);
1109    digest.update(body);
1110    let bytes = digest.finalize();
1111    let mut encoded = String::with_capacity(bytes.len() * 2 + 2);
1112    encoded.push('"');
1113    for byte in bytes {
1114        encoded.push(char::from_digit(u32::from(byte >> 4), 16).unwrap_or('0'));
1115        encoded.push(char::from_digit(u32::from(byte & 0x0f), 16).unwrap_or('0'));
1116    }
1117    encoded.push('"');
1118    encoded
1119}
1120
1121/// Whether an `If-None-Match` field lists this entity tag, weakly compared (RFC 9110).
1122fn matches_etag(header: &str, etag: &str) -> bool {
1123    let bare = |value: &str| {
1124        value
1125            .trim()
1126            .trim_start_matches("W/")
1127            .trim()
1128            .trim_matches('"')
1129            .to_owned()
1130    };
1131    let wanted = bare(etag);
1132    header
1133        .split(',')
1134        .any(|entry| entry.trim() == "*" || bare(entry) == wanted)
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139    use super::*;
1140    use odp_core::{
1141        Action, ActionRelation, AdditionalMembers, HttpActionTarget, HttpConfiguration,
1142        parse_collection, parse_service_document,
1143    };
1144
1145    struct TestCatalog;
1146
1147    #[async_trait]
1148    impl Catalog for TestCatalog {
1149        fn operations(&self) -> Vec<Operation> {
1150            vec![Operation::GetOffering, Operation::ListOfferings]
1151        }
1152
1153        async fn list_offerings(
1154            &self,
1155            _request: CatalogRequest,
1156        ) -> Result<OfferingPage<Offering>, ServiceError> {
1157            Ok(OfferingPage {
1158                additional: AdditionalMembers::new(),
1159                auth_expands: false,
1160                items: vec![offering()],
1161                next: String::new(),
1162                odp_version: VERSION.to_owned(),
1163                refinements: Vec::new(),
1164            })
1165        }
1166
1167        async fn get_offering(
1168            &self,
1169            id: &str,
1170            _request: CatalogRequest,
1171        ) -> Result<Option<Offering>, ServiceError> {
1172            Ok((id == "plant-1").then(offering))
1173        }
1174    }
1175
1176    fn offering() -> Offering {
1177        Offering {
1178            actions: Vec::new(),
1179            additional: AdditionalMembers::new(),
1180            attributes: BTreeMap::new(),
1181            auth_expands: false,
1182            collection_ids: Vec::new(),
1183            description: "A healthy plant".to_owned(),
1184            detail_fields: Vec::new(),
1185            id: "plant-1".to_owned(),
1186            images: Vec::new(),
1187            language: "en".to_owned(),
1188            localizations: vec!["en".to_owned()],
1189            name: "Plant".to_owned(),
1190            odp_version: VERSION.to_owned(),
1191            price: None,
1192            schema: None,
1193            web_url: String::new(),
1194        }
1195    }
1196
1197    fn document() -> ServiceDocument {
1198        parse_service_document(br#"{"description":"Plants","http":{"endpoint_base":"/odp"},"language":"en","localizations":["en"],"name":"Indica Flowers","odp_version":"1.0","operations":[{"authentication":"not-required","name":"get-offering"},{"authentication":"not-required","name":"list-offerings"}]}"#).unwrap()
1199    }
1200
1201    #[test]
1202    fn builder_derives_version_and_catalog_operations() {
1203        let service =
1204            ServiceBuilder::new("Indica Flowers", "An AI-enabled plant store.", "en", "/odp")
1205                .keywords(["plants", "flowers"])
1206                .operation_authentication(
1207                    Operation::GetOffering,
1208                    AuthenticationRequirement::Required,
1209                )
1210                .protocols(
1211                    vec![EnrollmentProtocol {
1212                        name: odp_core::Protocol::Aep,
1213                    }],
1214                    Vec::new(),
1215                )
1216                .trust(vec![TrustProtocol {
1217                    name: odp_core::Protocol::Tap,
1218                }])
1219                .build(Arc::new(TestCatalog))
1220                .unwrap();
1221        let document = service.document();
1222        assert_eq!(document.odp_version, VERSION);
1223        assert_eq!(document.localizations, ["en"]);
1224        assert_eq!(document.keywords, ["plants", "flowers"]);
1225        assert_eq!(document.operations.len(), 2);
1226        assert_eq!(
1227            document.protocols.as_ref().unwrap().trust,
1228            [TrustProtocol {
1229                name: odp_core::Protocol::Tap
1230            }]
1231        );
1232        assert_eq!(
1233            document
1234                .operations
1235                .iter()
1236                .find(|descriptor| descriptor.name == Operation::GetOffering)
1237                .unwrap()
1238                .authentication,
1239            AuthenticationRequirement::Required
1240        );
1241        assert_eq!(
1242            document
1243                .operations
1244                .iter()
1245                .find(|descriptor| descriptor.name == Operation::ListOfferings)
1246                .unwrap()
1247                .authentication,
1248            AuthenticationRequirement::NotRequired
1249        );
1250    }
1251
1252    #[tokio::test]
1253    async fn serves_a_framework_neutral_offering_request() {
1254        let service = Service::new(document(), Arc::new(TestCatalog)).unwrap();
1255        let response = service
1256            .handle(Request {
1257                headers: BTreeMap::from([("accept".to_owned(), MEDIA_TYPE.to_owned())]),
1258                method: "GET".to_owned(),
1259                path: "/odp/offerings/plant-1".to_owned(),
1260                query: "representation=full".to_owned(),
1261                ..Request::default()
1262            })
1263            .await;
1264        assert_eq!(response.status, 200);
1265        assert_eq!(parse_offering(&response.body).unwrap().id, "plant-1");
1266
1267        let listed = service
1268            .handle(Request {
1269                headers: BTreeMap::from([("accept".to_owned(), MEDIA_TYPE.to_owned())]),
1270                method: "GET".to_owned(),
1271                path: "/odp/offerings".to_owned(),
1272                ..Request::default()
1273            })
1274            .await;
1275        assert_eq!(listed.status, 200);
1276        assert_eq!(
1277            parse_page::<serde_json::Value>(&listed.body)
1278                .unwrap()
1279                .items
1280                .len(),
1281            1
1282        );
1283    }
1284
1285    #[tokio::test]
1286    async fn returns_problem_types_that_correspond_to_the_code() {
1287        let service = Service::new(document(), Arc::new(TestCatalog)).unwrap();
1288        let response = service
1289            .handle(Request {
1290                method: "GET".to_owned(),
1291                path: "/odp/missing".to_owned(),
1292                ..Request::default()
1293            })
1294            .await;
1295        let problem = odp_core::parse_problem_details(&response.body).unwrap();
1296
1297        assert_eq!(problem.code, "NOT_FOUND");
1298        assert_eq!(
1299            problem.problem_type,
1300            "https://offeringprotocol.org/problems/not-found"
1301        );
1302    }
1303
1304    #[test]
1305    fn model_http_configuration_remains_framework_neutral() {
1306        let configuration = HttpConfiguration {
1307            additional: AdditionalMembers::new(),
1308            endpoint_base: "/odp".to_owned(),
1309            openapi: None,
1310        };
1311        assert_eq!(configuration.endpoint_base, "/odp");
1312    }
1313
1314    #[test]
1315    fn rejects_search_bodies_above_the_normative_limit() {
1316        let error = validate_search_request(&Request {
1317            body: vec![b' '; MAXIMUM_REQUEST_BYTES + 1],
1318            headers: BTreeMap::from([("content-type".to_owned(), MEDIA_TYPE.to_owned())]),
1319            method: "POST".to_owned(),
1320            path: "/odp/offerings/search".to_owned(),
1321            query: String::new(),
1322        })
1323        .unwrap_err();
1324        assert!(matches!(error, ServiceError::Request { status: 413, .. }));
1325    }
1326
1327    #[test]
1328    fn rejects_invalid_page_envelopes() {
1329        let page = OfferingPage {
1330            additional: AdditionalMembers::new(),
1331            auth_expands: false,
1332            items: vec![offering()],
1333            next: String::new(),
1334            odp_version: String::new(),
1335            refinements: Vec::new(),
1336        };
1337
1338        assert!(
1339            validate_offering_page(&page, false, Representation::Terse, 0, &Request::default())
1340                .is_err()
1341        );
1342    }
1343
1344    #[test]
1345    fn rejects_representation_contract_violations() {
1346        let mut terse = offering();
1347        terse.actions.push(Action {
1348            authentication: AuthenticationRequirement::NotRequired,
1349            description: String::new(),
1350            http: Some(HttpActionTarget {
1351                href: "/purchase".to_owned(),
1352                method: "POST".to_owned(),
1353                request: None,
1354                response_content_types: Vec::new(),
1355            }),
1356            id: "purchase".to_owned(),
1357            openapi: None,
1358            rel: ActionRelation::Purchase,
1359        });
1360        assert!(validate_offering_representation(&terse, Representation::Terse).is_err());
1361
1362        let mut full = offering();
1363        full.detail_fields.push("/description".to_owned());
1364        assert!(validate_offering_representation(&full, Representation::Full).is_err());
1365
1366        let mut collection =
1367            parse_collection(br#"{"id":"plants","name":"Plants","odp_version":"1.0"}"#).unwrap();
1368        collection.detail_fields.push("/description".to_owned());
1369        assert!(validate_collection_representation(&collection, Representation::Full).is_err());
1370    }
1371}