Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(properties): vuln (#2301)

Sean Ayecafba8d078e9
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 03b66e10f5..c41b3804d3 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -65,6 +65,12 @@ pub enum ExpandErr {
/// unknown document sub type
#[error(transparent)]
DocumentSubTypeErr(#[from] strum::ParseError),
+ /// invalid property entity type
+ #[error(transparent)]
+ PropertyEntityType(#[from] properties::PropertyEntityTypeError),
+ /// invalid entity reference id
+ #[error(transparent)]
+ EntityRefId(#[from] properties::EntityRefIdError),
}
/// type alias for a maybe empty, cheaply cloneable ast literal tree
diff --git a/rust/cloud-storage/item_filters/src/ast/properties.rs b/rust/cloud-storage/item_filters/src/ast/properties.rs
index 1340f845f7..6510139145 100644
--- a/rust/cloud-storage/item_filters/src/ast/properties.rs
+++ b/rust/cloud-storage/item_filters/src/ast/properties.rs
@@ -1,3 +1,6 @@
+use std::fmt;
+use std::str::FromStr;
+
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -5,6 +8,115 @@ use crate::PropertyFilter;
use crate::ast::ExpandErr;
use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};
+/// The entity type for property lookups in the `entity_properties` table.
+///
+/// Using a closed enum prevents SQL injection through the `entity_type` field,
+/// which is interpolated into dynamic SQL queries.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum PropertyEntityType {
+ /// Channel entity
+ Channel,
+ /// Chat entity
+ Chat,
+ /// Company entity
+ Company,
+ /// Document entity
+ Document,
+ /// Project entity
+ Project,
+ /// Task entity
+ Task,
+ /// Thread entity
+ Thread,
+ /// User entity
+ User,
+}
+
+/// Error returned when parsing an invalid entity type string.
+#[derive(Debug, Clone, thiserror::Error)]
+#[error("invalid property entity type: {0}")]
+pub struct PropertyEntityTypeError(pub String);
+
+impl FromStr for PropertyEntityType {
+ type Err = PropertyEntityTypeError;
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s {
+ "CHANNEL" => Ok(Self::Channel),
+ "CHAT" => Ok(Self::Chat),
+ "COMPANY" => Ok(Self::Company),
+ "DOCUMENT" => Ok(Self::Document),
+ "PROJECT" => Ok(Self::Project),
+ "TASK" => Ok(Self::Task),
+ "THREAD" => Ok(Self::Thread),
+ "USER" => Ok(Self::User),
+ _ => Err(PropertyEntityTypeError(s.to_owned())),
+ }
+ }
+}
+
+impl fmt::Display for PropertyEntityType {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Channel => write!(f, "CHANNEL"),
+ Self::Chat => write!(f, "CHAT"),
+ Self::Company => write!(f, "COMPANY"),
+ Self::Document => write!(f, "DOCUMENT"),
+ Self::Project => write!(f, "PROJECT"),
+ Self::Task => write!(f, "TASK"),
+ Self::Thread => write!(f, "THREAD"),
+ Self::User => write!(f, "USER"),
+ }
+ }
+}
+
+/// A validated entity reference ID that is safe for SQL interpolation.
+///
+/// Rejects strings containing single quotes, backslashes, or null bytes,
+/// which could enable SQL injection when interpolated into dynamic queries.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct EntityRefId(String);
+
+/// Error returned when an entity reference ID contains unsafe characters.
+#[derive(Debug, Clone, thiserror::Error)]
+#[error("entity reference ID contains unsafe characters: {0}")]
+pub struct EntityRefIdError(pub String);
+
+impl EntityRefId {
+ /// Create a new validated entity reference ID.
+ pub fn new(s: String) -> Result<Self, EntityRefIdError> {
+ if s.contains('\'') || s.contains('\\') || s.contains('\0') {
+ return Err(EntityRefIdError(s));
+ }
+ Ok(Self(s))
+ }
+}
+
+impl fmt::Display for EntityRefId {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+impl Serialize for EntityRefId {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ self.0.serialize(serializer)
+ }
+}
+
+impl<'de> Deserialize<'de> for EntityRefId {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let s = String::deserialize(deserializer)?;
+ Self::new(s).map_err(serde::de::Error::custom)
+ }
+}
+
/// Describes how to match against a property value in the entity_properties table.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum PropertyMatchValue {
@@ -13,7 +125,7 @@ pub enum PropertyMatchValue {
SelectOption(Uuid),
/// Match an entity reference by entity_id. Uses the `@>` jsonb operator on `values->'value'`.
#[serde(rename = "er")]
- EntityRef(String),
+ EntityRef(EntityRefId),
}
/// A single property-based filter condition for the AST.
@@ -25,10 +137,10 @@ pub struct PropertiesLiteral {
/// The property definition UUID to filter on.
#[serde(rename = "pd")]
pub property_definition_id: Uuid,
- /// The entity type for the property lookup (e.g., "TASK", "DOCUMENT", "PROJECT").
+ /// The entity type for the property lookup (e.g., Task, Document, Project).
/// When None, matches across all entity types.
#[serde(default, rename = "et", skip_serializing_if = "Option::is_none")]
- pub entity_type: Option<String>,
+ pub entity_type: Option<PropertyEntityType>,
/// The value to match against.
#[serde(rename = "v")]
pub value: PropertyMatchValue,
@@ -43,6 +155,10 @@ impl ExpandFrame<PropertiesLiteral> for Vec<PropertyFilter> {
.into_iter()
.map(|pf| {
let prop_def_id = Uuid::parse_str(&pf.property_definition_id)?;
+ let entity_type = pf
+ .entity_type
+ .map(|et| et.parse::<PropertyEntityType>())
+ .transpose()?;
let option_nodes = pf
.option_ids
@@ -52,21 +168,27 @@ impl ExpandFrame<PropertiesLiteral> for Vec<PropertyFilter> {
|r| {
r.map(|uuid| PropertiesLiteral {
property_definition_id: prop_def_id,
- entity_type: pf.entity_type.clone(),
+ entity_type,
value: PropertyMatchValue::SelectOption(uuid),
})
},
Expr::or,
)?;
- let entity_ref_nodes = pf.entity_ids.iter().cloned().expand(
- |id| PropertiesLiteral {
- property_definition_id: prop_def_id,
- entity_type: pf.entity_type.clone(),
- value: PropertyMatchValue::EntityRef(id),
- },
- Expr::or,
- );
+ let entity_ref_nodes = pf
+ .entity_ids
+ .iter()
+ .map(|id| EntityRefId::new(id.clone()))
+ .try_expand(
+ |r| {
+ r.map(|id| PropertiesLiteral {
+ property_definition_id: prop_def_id,
+ entity_type,
+ value: PropertyMatchValue::EntityRef(id),
+ })
+ },
+ Expr::or,
+ )?;
Ok([option_nodes, entity_ref_nodes]
.into_iter()
diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rs
index d4a8dba8f7..a9a66e6f22 100644
--- a/rust/cloud-storage/item_filters/src/ast/tests.rs
+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs
@@ -7,6 +7,8 @@ use model_file_type::FileType;
use serde_json::json;
use uuid::Uuid;
+use super::properties;
+
#[test]
fn it_works_with_file_type() {
let res: Result<Vec<_>, _> = ["pdf", "md", "txt", "html"]
@@ -723,3 +725,76 @@ fn empty_sub_types_produce_no_ast() {
"empty sub_types should produce no AST"
);
}
+
+#[test]
+fn invalid_entity_type_returns_error() {
+ let prop_def_id = Uuid::new_v4();
+ let option_id = Uuid::new_v4();
+ let f = EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: prop_def_id.to_string(),
+ entity_type: Some("TASK'; DROP TABLE documents; --".to_string()),
+ option_ids: vec![option_id.to_string()],
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ assert!(
+ EntityFilterAst::new_from_filters(f).is_err(),
+ "SQL injection in entity_type should be rejected"
+ );
+}
+
+#[test]
+fn entity_ref_with_single_quote_returns_error() {
+ let prop_def_id = Uuid::new_v4();
+ let f = EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: prop_def_id.to_string(),
+ entity_type: Some("TASK".to_string()),
+ option_ids: vec![],
+ entity_ids: vec!["x'); DROP TABLE documents; --".to_string()],
+ }],
+ ..Default::default()
+ };
+
+ assert!(
+ EntityFilterAst::new_from_filters(f).is_err(),
+ "SQL injection in entity_ids should be rejected"
+ );
+}
+
+#[test]
+fn entity_ref_ast_deserialization_rejects_injection() {
+ let json = serde_json::json!({
+ "l": {
+ "pd": Uuid::new_v4(),
+ "et": "TASK",
+ "v": { "er": "x'); DROP TABLE documents; --" }
+ }
+ });
+
+ let result = serde_json::from_value::<filter_ast::Expr<properties::PropertiesLiteral>>(json);
+ assert!(
+ result.is_err(),
+ "direct AST deserialization should reject SQL injection in EntityRef"
+ );
+}
+
+#[test]
+fn entity_type_ast_deserialization_rejects_invalid() {
+ let json = serde_json::json!({
+ "l": {
+ "pd": Uuid::new_v4(),
+ "et": "INVALID_TYPE",
+ "v": { "so": Uuid::new_v4() }
+ }
+ });
+
+ let result = serde_json::from_value::<filter_ast::Expr<properties::PropertiesLiteral>>(json);
+ assert!(
+ result.is_err(),
+ "direct AST deserialization should reject invalid entity type"
+ );
+}