Skip to main content

postrust_core/api_request/
mod.rs

1//! API request parsing module.
2//!
3//! This module handles parsing HTTP requests into the domain-specific
4//! `ApiRequest` type that can be used for query planning.
5
6pub mod payload;
7pub mod preferences;
8pub mod query_params;
9pub mod types;
10
11pub use preferences::parse_preferences;
12pub use query_params::{parse_query_params, parse_query_params_with, value_is_filter};
13pub use types::*;
14
15use crate::error::{Error, Result};
16use http::{Method, Request};
17use percent_encoding::percent_decode_str;
18use std::collections::{HashMap, HashSet};
19
20/// Parse an HTTP request into an ApiRequest.
21///
22/// `max_rows` is the server-configured ceiling on returned rows
23/// (`PGRST_MAX_ROWS`); pass `None` for no ceiling. It is applied when the read
24/// plan resolves its range, so it caps requests that specify no `limit`.
25pub fn parse_request<B>(
26    req: &Request<B>,
27    default_schema: &str,
28    schemas: &[String],
29    max_rows: Option<i64>,
30) -> Result<ApiRequest>
31where
32    B: AsRef<[u8]>,
33{
34    parse_request_with(req, default_schema, schemas, max_rows, false)
35}
36
37/// [`parse_request`], with `lenient_select` for compatibility mode: text left
38/// over after the last `select` item is dropped instead of refused.
39pub fn parse_request_with<B>(
40    req: &Request<B>,
41    default_schema: &str,
42    schemas: &[String],
43    max_rows: Option<i64>,
44    lenient_select: bool,
45) -> Result<ApiRequest>
46where
47    B: AsRef<[u8]>,
48{
49    let method = req.method();
50    let path = req.uri().path();
51    let query = req.uri().query().unwrap_or("");
52
53    // Parse resource from path
54    let resource = parse_resource(path)?;
55
56    // Determine schema from headers or use default
57    let (schema, negotiated_by_profile) = parse_schema(req, default_schema, schemas)?;
58
59    // Parse action from method and resource
60    let action = parse_action(method, &resource, &schema)?;
61
62    // Parse query parameters. On a function *called over GET* the
63    // unrecognized ones are arguments rather than malformed filters. Over
64    // POST the arguments are in the body, so the query string is filters and
65    // nothing else -- `POST /rpc/f?name=John` is a malformed filter, which is
66    // what PostgREST says about it.
67    let is_rpc = matches!(
68        action,
69        Action::Db(DbAction::Routine {
70            invoke_method: InvokeMethod::InvRead { .. },
71            ..
72        }) | Action::RoutineInfo { .. }
73    );
74    let query_params = parse_query_params_with(query, is_rpc, lenient_select)?;
75
76    // Parse preferences from Prefer header
77    let preferences = parse_preferences(req.headers())?;
78
79    // Parse Accept header for content negotiation
80    let accept_media_types = parse_accept(req.headers())?;
81
82    // Parse Content-Type header
83    let content_media_type = parse_content_type(req.headers())?;
84
85    // Parse Range header
86    // Only GET honours the header (PostgREST ApiRequest.hs getRanges,
87    // RFC 9110: ignore Range for every other method).
88    let top_level_range = if method == http::Method::GET {
89        parse_range(req.headers())?
90    } else {
91        Range::default()
92    };
93
94    // Extract headers and cookies for GUC passthrough
95    let headers = extract_headers(req.headers());
96    let cookies = extract_cookies(req.headers());
97
98    Ok(ApiRequest {
99        action,
100        schema,
101        payload: None, // Payload parsed separately
102        query_params,
103        accept_media_types,
104        content_media_type,
105        preferences,
106        columns: HashSet::new(),
107        top_level_range,
108        range_map: HashMap::new(),
109        max_rows,
110        negotiated_by_profile,
111        method: method.to_string(),
112        path: path.to_string(),
113        headers,
114        cookies,
115        // Set by the caller, which has the request's extensions; this sees
116        // a request rebuilt from the headers.
117        trace_id: None,
118    })
119}
120
121/// Parse the resource from the URL path.
122fn parse_resource(path: &str) -> Result<Resource> {
123    let path = path.trim_start_matches('/');
124
125    if path.is_empty() {
126        return Ok(Resource::Schema);
127    }
128
129    // A trailing slash names the same resource: `/items/` is `/items`.
130    let path = path.trim_end_matches('/');
131    if path.is_empty() {
132        return Ok(Resource::Schema);
133    }
134
135    // A name is the name the schema gave it, not the encoding a URL had to use
136    // to carry it: `/%D9%85%D9%88%D8%A7%D8%B1%D8%AF` addresses a table called
137    // `موارد`. Looking the encoded form up finds nothing, and says so using
138    // the escape sequence rather than the name.
139    let decoded = |segment: &str| -> String {
140        percent_decode_str(segment)
141            .decode_utf8()
142            .map(|name| name.into_owned())
143            .unwrap_or_else(|_| segment.to_string())
144    };
145
146    if let Some(func_name) = path.strip_prefix("rpc/") {
147        if func_name.is_empty() {
148            return Err(Error::InvalidPath("Empty function name".into()));
149        }
150        if func_name.contains('/') {
151            return Err(Error::InvalidResourcePath);
152        }
153        return Ok(Resource::Routine(decoded(func_name)));
154    }
155
156    // A table is named by one segment. More than one names nothing at all --
157    // there is no nesting in the API -- and reading only the first would
158    // answer a request for `/first/second/third` with the contents of
159    // `first`, which is not what was asked for.
160    if path.contains('/') {
161        return Err(Error::InvalidResourcePath);
162    }
163
164    Ok(Resource::Relation(decoded(path)))
165}
166
167/// Parse the schema from Accept-Profile or Content-Profile headers.
168fn parse_schema<B>(
169    req: &Request<B>,
170    default_schema: &str,
171    schemas: &[String],
172) -> Result<(String, bool)> {
173    // Check Accept-Profile header first (for reads)
174    if let Some(profile) = req.headers().get("accept-profile") {
175        let schema = profile
176            .to_str()
177            .map_err(|_| Error::InvalidHeader("Accept-Profile"))?;
178        if !schemas.contains(&schema.to_string()) {
179            return Err(Error::UnacceptableSchema {
180                requested: schema.into(),
181                exposed: schemas.to_vec(),
182            });
183        }
184        return Ok((schema.to_string(), true));
185    }
186
187    // Check Content-Profile header (for writes)
188    if let Some(profile) = req.headers().get("content-profile") {
189        let schema = profile
190            .to_str()
191            .map_err(|_| Error::InvalidHeader("Content-Profile"))?;
192        if !schemas.contains(&schema.to_string()) {
193            return Err(Error::UnacceptableSchema {
194                requested: schema.into(),
195                exposed: schemas.to_vec(),
196            });
197        }
198        return Ok((schema.to_string(), true));
199    }
200
201    Ok((default_schema.to_string(), false))
202}
203
204/// Parse the action from HTTP method and resource.
205fn parse_action(method: &Method, resource: &Resource, schema: &str) -> Result<Action> {
206    match (method, resource) {
207        // Schema endpoints
208        (&Method::GET, Resource::Schema) => Ok(Action::Db(DbAction::SchemaRead {
209            schema: schema.to_string(),
210            headers_only: false,
211        })),
212        (&Method::HEAD, Resource::Schema) => Ok(Action::Db(DbAction::SchemaRead {
213            schema: schema.to_string(),
214            headers_only: true,
215        })),
216        (&Method::OPTIONS, Resource::Schema) => Ok(Action::SchemaInfo),
217
218        // Table/view endpoints
219        (&Method::GET, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationRead {
220            qi: QualifiedIdentifier::new(schema, name),
221            headers_only: false,
222        })),
223        (&Method::HEAD, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationRead {
224            qi: QualifiedIdentifier::new(schema, name),
225            headers_only: true,
226        })),
227        (&Method::POST, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationMut {
228            qi: QualifiedIdentifier::new(schema, name),
229            mutation: Mutation::Create,
230        })),
231        (&Method::PATCH, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationMut {
232            qi: QualifiedIdentifier::new(schema, name),
233            mutation: Mutation::Update,
234        })),
235        (&Method::PUT, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationMut {
236            qi: QualifiedIdentifier::new(schema, name),
237            mutation: Mutation::SingleUpsert,
238        })),
239        (&Method::DELETE, Resource::Relation(name)) => Ok(Action::Db(DbAction::RelationMut {
240            qi: QualifiedIdentifier::new(schema, name),
241            mutation: Mutation::Delete,
242        })),
243        (&Method::OPTIONS, Resource::Relation(name)) => {
244            Ok(Action::RelationInfo(QualifiedIdentifier::new(schema, name)))
245        }
246
247        // RPC endpoints
248        (&Method::GET, Resource::Routine(name)) => Ok(Action::Db(DbAction::Routine {
249            qi: QualifiedIdentifier::new(schema, name),
250            invoke_method: InvokeMethod::InvRead {
251                headers_only: false,
252            },
253        })),
254        (&Method::HEAD, Resource::Routine(name)) => Ok(Action::Db(DbAction::Routine {
255            qi: QualifiedIdentifier::new(schema, name),
256            invoke_method: InvokeMethod::InvRead { headers_only: true },
257        })),
258        (&Method::POST, Resource::Routine(name)) => Ok(Action::Db(DbAction::Routine {
259            qi: QualifiedIdentifier::new(schema, name),
260            invoke_method: InvokeMethod::Inv,
261        })),
262        (&Method::OPTIONS, Resource::Routine(name)) => Ok(Action::RoutineInfo {
263            qi: QualifiedIdentifier::new(schema, name),
264            invoke_method: InvokeMethod::Inv,
265        }),
266
267        // Unsupported methods
268        (_, Resource::Routine(_)) => Err(Error::InvalidRpcMethod(method.to_string())),
269        _ => Err(Error::UnsupportedMethod(method.to_string())),
270    }
271}
272
273/// Parse Accept header for content negotiation.
274fn parse_accept(headers: &http::HeaderMap) -> Result<Vec<MediaType>> {
275    if let Some(accept) = headers.get(http::header::ACCEPT) {
276        let accept_str = accept
277            .to_str()
278            .map_err(|_| Error::InvalidHeader("Accept"))?;
279        // A quality factor orders the list and says nothing about the type,
280        // so it is dropped. The other parameters are not decoration: `;nulls=
281        // stripped` is part of what `application/vnd.pgrst.array+json` *is*,
282        // and cutting the entry at the semicolon threw it away along with the
283        // `q=`.
284        let types: Vec<MediaType> = accept_str
285            .split(',')
286            .map(str::trim)
287            .map(|entry| {
288                let kept: Vec<&str> = entry
289                    .split(';')
290                    .map(str::trim)
291                    .filter(|part| !part.starts_with("q="))
292                    .collect();
293                parse_media_type(&kept.join(";"))
294            })
295            .collect();
296        if types.is_empty() {
297            return Ok(vec![MediaType::ApplicationJson]);
298        }
299        return Ok(types);
300    }
301    Ok(vec![MediaType::ApplicationJson])
302}
303
304/// Parse a single media type, parameters included.
305///
306/// Only the vendored types read their parameters; for everything else the
307/// name alone is the type, so `application/json;charset=utf-8` is still JSON.
308fn parse_media_type(s: &str) -> MediaType {
309    let mut parts = s.split(';').map(str::trim);
310    let base = parts.next().unwrap_or(s);
311    // A parameter value may be quoted -- `for="application/json"` -- because
312    // it is itself a media type and carries a `/`. The quotes delimit it and
313    // are not part of it.
314    let parameters: Vec<(String, &str)> = parts
315        .filter_map(|part| part.split_once('='))
316        .map(|(key, value)| {
317            (
318                key.trim().to_ascii_lowercase(),
319                value.trim().trim_matches('"'),
320            )
321        })
322        .collect();
323    let param = |name: &str| {
324        parameters
325            .iter()
326            .find(|(key, _)| key == name)
327            .map(|(_, value)| *value)
328    };
329    let given = |parameter: &str| match parameter.split_once('=') {
330        Some((name, value)) => param(name) == Some(value),
331        None => false,
332    };
333
334    match base {
335        "application/json" => MediaType::ApplicationJson,
336        "application/geo+json" => MediaType::GeoJson,
337        "text/csv" => MediaType::TextCsv,
338        "text/plain" => MediaType::TextPlain,
339        "text/xml" => MediaType::TextXml,
340        "application/openapi+json" => MediaType::OpenApi,
341        "application/x-www-form-urlencoded" => MediaType::UrlEncoded,
342        "application/octet-stream" => MediaType::OctetStream,
343        "*/*" => MediaType::Any,
344        // A plan is a plan *for* something, and that something is a media
345        // type in its own right: read the same way, and named back the same
346        // way. `for="application/vnd.pgrst.object"` is how the client says
347        // "the plan for the query that would answer a singular request", and
348        // it comes back out as `application/vnd.pgrst.object+json` because
349        // that is the name that type has.
350        s if s.starts_with("application/vnd.pgrst.plan") => {
351            let format = match s.ends_with("+json") {
352                true => PlanFormat::Json,
353                false => PlanFormat::Text,
354            };
355            let requested = param("options").unwrap_or_default();
356            // Named in a fixed order rather than the order they were asked
357            // for, so that one set of options has one name.
358            let options = [
359                ("analyze", PlanOption::Analyze),
360                ("verbose", PlanOption::Verbose),
361                ("settings", PlanOption::Settings),
362                ("buffers", PlanOption::Buffers),
363                ("wal", PlanOption::Wal),
364            ]
365            .into_iter()
366            .filter(|(name, _)| requested.split('|').any(|asked| asked == *name))
367            .map(|(_, option)| option)
368            .collect();
369            MediaType::Plan {
370                base: Box::new(parse_media_type(param("for").unwrap_or("application/json"))),
371                format,
372                options,
373            }
374        }
375        s if s.starts_with("application/vnd.pgrst.object") => MediaType::SingularJson {
376            nullable: given("nulls=null"),
377            strip_nulls: given("nulls=stripped"),
378        },
379        s if s.starts_with("application/vnd.pgrst.array") => MediaType::ArrayJson {
380            strip_nulls: given("nulls=stripped"),
381        },
382        other => MediaType::Other(other.to_string()),
383    }
384}
385
386/// Parse Content-Type header.
387fn parse_content_type(headers: &http::HeaderMap) -> Result<MediaType> {
388    if let Some(ct) = headers.get(http::header::CONTENT_TYPE) {
389        let ct_str = ct
390            .to_str()
391            .map_err(|_| Error::InvalidHeader("Content-Type"))?;
392        return Ok(parse_media_type(ct_str.trim()));
393    }
394    Ok(MediaType::ApplicationJson)
395}
396
397/// Parse Range header for pagination.
398///
399/// `0-9`, `10-19` and `10-` are all ranges. Only the first of those was read
400/// before, by matching the literal prefix `0-`; every other range was dropped
401/// on the floor and the request answered with the whole relation. A client
402/// paging with `Range: 1000-1999` was handed all of it and a `Content-Range`
403/// saying so, which is the sort of disagreement a client discovers in
404/// production rather than in a test.
405///
406/// A range that is not a range at all is left alone, as before: hyper accepts
407/// header values this never has to make sense of, and the query parameters
408/// remain the way to page.
409fn parse_range(headers: &http::HeaderMap) -> Result<Range> {
410    let Some(range) = headers.get(http::header::RANGE) else {
411        return Ok(Range::default());
412    };
413    let range_str = range.to_str().map_err(|_| Error::InvalidHeader("Range"))?;
414
415    // PostgREST writes the unit in `Range-Unit` and the bounds bare, but a
416    // client following RFC 9110 puts the unit here. Both name the same rows.
417    let bounds = range_str
418        .split_once('=')
419        .map_or(range_str, |(_unit, bounds)| bounds)
420        .trim();
421
422    let Some((start, end)) = bounds.split_once('-') else {
423        return Ok(Range::default());
424    };
425    let Ok(start) = start.trim().parse::<i64>() else {
426        return Ok(Range::default());
427    };
428    if start < 0 {
429        return Ok(Range::default());
430    }
431
432    let end = end.trim();
433    if end.is_empty() {
434        // Open-ended: from here to the end of the relation.
435        return Ok(Range::new(start, None));
436    }
437    let Ok(end) = end.parse::<i64>() else {
438        return Ok(Range::default());
439    };
440    if end < start {
441        return Err(Error::InvalidRange(
442            "Requested range not satisfiable".into(),
443        ));
444    }
445
446    Ok(Range::from_bounds(start, Some(end)))
447}
448
449/// Extract headers for GUC passthrough.
450fn extract_headers(headers: &http::HeaderMap) -> indexmap::IndexMap<String, String> {
451    headers
452        .iter()
453        .filter_map(|(k, v)| v.to_str().ok().map(|v| (k.to_string(), v.to_string())))
454        .collect()
455}
456
457/// Extract cookies from Cookie header.
458fn extract_cookies(headers: &http::HeaderMap) -> indexmap::IndexMap<String, String> {
459    headers
460        .get(http::header::COOKIE)
461        .and_then(|v| v.to_str().ok())
462        .map(|s| {
463            s.split(';')
464                .filter_map(|cookie| {
465                    let (key, value) = cookie.trim().split_once('=')?;
466
467                    Some((key.to_string(), value.to_string()))
468                })
469                .collect()
470        })
471        .unwrap_or_default()
472}
473
474#[cfg(test)]
475mod tests {
476    use super::*;
477
478    fn range_of(value: &str) -> Result<Range> {
479        let mut headers = http::HeaderMap::new();
480        headers.insert(http::header::RANGE, value.parse().unwrap());
481        parse_range(&headers)
482    }
483
484    /// Every range, not only the ones that begin at the first row.
485    #[test]
486    fn a_range_header_names_the_rows_it_says() {
487        assert_eq!(range_of("0-9").unwrap(), Range::from_bounds(0, Some(9)));
488        assert_eq!(range_of("5-9").unwrap(), Range::from_bounds(5, Some(9)));
489        assert_eq!(range_of("10-19").unwrap(), Range::from_bounds(10, Some(19)));
490        // Open-ended: from there to the end of the relation.
491        assert_eq!(range_of("10-").unwrap(), Range::new(10, None));
492        assert_eq!(range_of("0-").unwrap(), Range::new(0, None));
493        // A unit, for a client that follows RFC 9110 rather than PostgREST.
494        assert_eq!(
495            range_of("items=5-9").unwrap(),
496            Range::from_bounds(5, Some(9))
497        );
498    }
499
500    /// The header is for GET alone (RFC 9110; PostgREST getRanges).
501    #[test]
502    fn the_range_header_is_ignored_off_get() {
503        for method in ["POST", "PUT", "PATCH", "DELETE"] {
504            let request = http::Request::builder()
505                .method(method)
506                .uri("/items")
507                .header("Range", "9-5")
508                .body(Vec::<u8>::new())
509                .unwrap();
510            let parsed = parse_request(&request, "public", &["public".to_string()], None).unwrap();
511            assert_eq!(parsed.top_level_range, Range::default(), "{method}");
512        }
513    }
514
515    /// A range whose end precedes its start names no rows at all.
516    #[test]
517    fn an_inverted_range_is_refused_rather_than_widened() {
518        assert!(matches!(range_of("9-5"), Err(Error::InvalidRange(_))));
519    }
520
521    /// Anything that is not a range leaves paging to the query parameters,
522    /// rather than being guessed at.
523    #[test]
524    fn a_header_that_is_not_a_range_is_left_alone() {
525        for value in ["", "nonsense", "-5", "a-b", "5"] {
526            assert_eq!(range_of(value).unwrap(), Range::default(), "{value:?}");
527        }
528    }
529
530    /// A plan is named back with everything that made it that plan.
531    ///
532    /// The cases are PostgREST's own doctests for `decodeMediaType`, read
533    /// back out through `toMime`.
534    #[test]
535    fn a_plan_media_type_is_named_back_in_full() {
536        let named = |s: &str| parse_media_type(s).to_mime();
537
538        assert_eq!(
539            named("application/vnd.pgrst.plan+json"),
540            "application/vnd.pgrst.plan+json; for=\"application/json\""
541        );
542        // The `for` type is read as a media type, so it is named by the name
543        // that type has rather than the one the client wrote.
544        assert_eq!(
545            named("application/vnd.pgrst.plan+json; for=\"application/vnd.pgrst.object\""),
546            "application/vnd.pgrst.plan+json; for=\"application/vnd.pgrst.object+json\""
547        );
548        assert_eq!(
549            named("application/vnd.pgrst.plan; for=\"text/csv\""),
550            "application/vnd.pgrst.plan+text; for=\"text/csv\""
551        );
552        // Options come back in a fixed order, not the order they were asked
553        // for, and anything unrecognised is not an option.
554        assert_eq!(
555            named("application/vnd.pgrst.plan+json; options=verbose|analyze|nonsense"),
556            "application/vnd.pgrst.plan+json; for=\"application/json\"; options=analyze|verbose"
557        );
558    }
559
560    #[test]
561    fn test_parse_resource() {
562        assert_eq!(parse_resource("/").unwrap(), Resource::Schema);
563        assert_eq!(
564            parse_resource("/users").unwrap(),
565            Resource::Relation("users".into())
566        );
567        assert_eq!(
568            parse_resource("/rpc/my_func").unwrap(),
569            Resource::Routine("my_func".into())
570        );
571    }
572
573    #[test]
574    fn test_parse_media_type() {
575        assert_eq!(
576            parse_media_type("application/json"),
577            MediaType::ApplicationJson
578        );
579        assert_eq!(parse_media_type("text/csv"), MediaType::TextCsv);
580        assert_eq!(parse_media_type("*/*"), MediaType::Any);
581    }
582}