Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 112 additions & 0 deletions pkgs/id/crates/id-pg/src/allowlist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,50 @@ impl CollectionAllowlist {
self.max_limit.unwrap_or(DEFAULT_MAX_LIMIT)
}

/// Check that every name this allowlist would hand to the
/// translator is safe to interpolate into a PostgREST request.
///
/// Rejected, with the reason named:
///
/// - a relation that is not a plain identifier — the relation is
/// interpolated raw into the request path (`/{relation}`);
/// - a declared column name that is not a usable field name (not
/// a plain identifier, or a reserved PostgREST parameter name
/// such as `or` or `select`) — declared names are joined raw
/// into the `select` value, and filter/order columns also
/// become query-parameter keys, so a name containing `,`, `(`,
/// `)`, `"`, or whitespace would change the shape of the
/// `select` list the source parses;
/// - a `unique_key` entry that is not one of the declared
/// columns — the key is appended to every ordering and rendered
/// into the `order` parameter and the keyset `or` group.
///
/// Registration (#13758) calls this when an allowlist is built,
/// so a bad configuration is refused at construction and never
/// reaches a request.
pub fn validate(&self) -> Result<(), String> {
if !is_plain_identifier(&self.relation) {
return Err(format!(
"relation {:?} is not a plain identifier",
self.relation
));
}
for column in &self.columns {
if !is_usable_field_name(&column.name) {
return Err(format!(
"declared column {:?} is not a usable field name",
column.name
));
}
}
for key in &self.unique_key {
if !self.is_declared(key) {
return Err(format!("unique_key entry {key:?} is not a declared column"));
}
}
Ok(())
}

/// Look up a declared column by name.
pub fn column(&self, name: &str) -> Option<&ColumnDecl> {
self.columns.iter().find(|c| c.name == name)
Expand All @@ -115,3 +159,71 @@ impl CollectionAllowlist {
self.columns.iter().map(|c| c.name.as_str()).collect()
}
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;

fn collection() -> CollectionAllowlist {
CollectionAllowlist {
schema: "public".to_string(),
relation: "items".to_string(),
columns: vec![
ColumnDecl {
name: "id".to_string(),
filterable: true,
orderable: true,
},
ColumnDecl {
name: "title".to_string(),
filterable: true,
orderable: true,
},
],
unique_key: vec!["id".to_string()],
max_limit: None,
}
}

fn with_column(name: &str) -> CollectionAllowlist {
let mut collection = collection();
collection.columns.push(ColumnDecl {
name: name.to_string(),
filterable: true,
orderable: true,
});
collection
}

#[test]
fn validate_accepts_plain_declared_columns() {
assert_eq!(collection().validate(), Ok(()));
}

#[test]
fn validate_refuses_column_with_comma() {
let collection = with_column("a,b");
assert!(collection.validate().unwrap_err().contains("a,b"));
}

#[test]
fn validate_refuses_reserved_column_name() {
let collection = with_column("or");
assert!(collection.validate().unwrap_err().contains("\"or\""));
}

#[test]
fn validate_refuses_non_identifier_relation() {
let mut collection = collection();
collection.relation = "items/x".to_string();
assert!(collection.validate().is_err());
}

#[test]
fn validate_refuses_undeclared_unique_key_entry() {
let mut collection = collection();
collection.unique_key = vec!["missing".to_string()];
assert!(collection.validate().unwrap_err().contains("missing"));
}
}
83 changes: 80 additions & 3 deletions pkgs/id/crates/id-pg/src/translate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,31 @@ impl Translator {
/// Build a translator over the owner's allowlist of collections.
/// The adapter exposes exactly these collections; a query naming
/// any other relation is `not_available`.
///
/// This constructor trusts that the collections were validated
/// when they were built (registration, #13758); `translate`
/// still refuses any declared name that is not a usable field
/// name before it can reach a request. Prefer
/// [`Translator::try_new`] when the allowlists come straight
/// from configuration.
pub fn new(collections: Vec<CollectionAllowlist>) -> Self {
Translator { collections }
}

/// Build a translator, refusing the whole set when any
/// collection's allowlist fails
/// [`CollectionAllowlist::validate`]: a relation that is not a
/// plain identifier, a declared column that is not a usable
/// field name, or a unique-key entry that is not declared. A bad
/// configuration is refused here, at construction, so it never
/// reaches a request.
pub fn try_new(collections: Vec<CollectionAllowlist>) -> Result<Self, String> {
for collection in &collections {
collection.validate()?;
}
Ok(Translator { collections })
}

/// Translate one query. Every §3.2 refusal is returned before any
/// request exists; a successful result is the whole request.
pub fn translate(&self, query: &Query) -> Result<PostgrestRequest, Refusal> {
Expand Down Expand Up @@ -109,6 +130,15 @@ impl Translator {
return Err(Refusal::shape(Feature::FieldUnsupported));
}
}
// The unique key is appended to every ordering by
// `effective_ordering`, unchecked by the loops above; a key
// column that is not a usable field name would be rendered
// raw into the `order` parameter and the keyset `or` group.
for key in &collection.unique_key {
if !is_usable_field_name(key) {
return Err(Refusal::shape(Feature::FieldUnsupported));
}
}
// 9. Operators: the text-pattern family is refused by name.
for leaf in &leaves {
if leaf.op.is_text_pattern() {
Expand Down Expand Up @@ -205,6 +235,21 @@ fn declared_columns(collection: &CollectionAllowlist) -> Vec<String> {
.collect()
}

/// Expand a star (or empty) projection to the declared columns,
/// refusing when any declared name is not a usable field name: the
/// names are joined raw into the `select` value, so a declared
/// column such as `a,b` or `x(y)` would change the shape of the
/// select list the source parses. Defense in depth behind
/// [`CollectionAllowlist::validate`], for allowlists that were
/// never validated at construction.
fn expand_declared(collection: &CollectionAllowlist) -> Result<Vec<String>, Refusal> {
let columns = declared_columns(collection);
if columns.iter().any(|name| !is_usable_field_name(name)) {
return Err(Refusal::shape(Feature::FieldUnsupported));
}
Ok(columns)
}

/// Resolve the projection to the declared column list to send.
///
/// An empty projection, or one containing `All`, expands to the
Expand All @@ -217,13 +262,13 @@ fn resolve_projection(
select: &[SelectItem],
) -> Result<Vec<String>, Refusal> {
if select.is_empty() || select.iter().any(|item| matches!(item, SelectItem::All)) {
return Ok(declared_columns(collection));
return expand_declared(collection);
}
let mut columns: Vec<String> = Vec::new();
for item in select {
match item {
SelectItem::Column(name) => {
if !collection.is_declared(name) {
if !collection.is_declared(name) || !is_usable_field_name(name) {
return Err(Refusal::shape(Feature::FieldUnsupported));
}
if !columns.contains(name) {
Expand All @@ -237,7 +282,7 @@ fn resolve_projection(
}
// Handled by the early return above; expand again rather
// than assume.
SelectItem::All => return Ok(declared_columns(collection)),
SelectItem::All => return expand_declared(collection),
}
}
Ok(columns)
Expand Down Expand Up @@ -488,6 +533,38 @@ mod tests {
assert_eq!(param(&request, "title"), Some("eq.1"));
}

#[test]
fn star_projection_refuses_unsafe_declared_column() {
let translator = collection_with_columns(&["id", "x(y)"]);
let refusal = translator.translate(&Query::read("items")).unwrap_err();
assert_eq!(refusal, Refusal::shape(Feature::FieldUnsupported));
}

#[test]
fn explicit_projection_refuses_unsafe_declared_column() {
let translator = collection_with_columns(&["id", "x(y)"]);
let mut query = Query::read("items");
query.select = vec![SelectItem::Column("x(y)".to_string())];
let refusal = translator.translate(&query).unwrap_err();
assert_eq!(refusal, Refusal::shape(Feature::FieldUnsupported));
}

#[test]
fn try_new_refuses_unvalidated_allowlist() {
let mut raw = collection();
raw.columns = vec![ColumnDecl {
name: "a,b".to_string(),
filterable: true,
orderable: true,
}];
assert!(Translator::try_new(vec![raw]).is_err());
}

#[test]
fn try_new_accepts_valid_allowlist() {
assert!(Translator::try_new(vec![collection()]).is_ok());
}

#[test]
fn is_null_renders_without_value() {
let mut query = Query::read("items");
Expand Down