Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(indexeddb): validate native schema key paths before mutation

ldm07e93cca6318f
diff --git a/Cargo.lock b/Cargo.lock
index 870108aef..a48833cdc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2781,6 +2781,7 @@ dependencies = [
"serde",
"serde_json",
"strum",
+ "unicode-id-start",
]
[[package]]
diff --git a/moli-indexeddb/Cargo.toml b/moli-indexeddb/Cargo.toml
index 4bf40c49b..5a7297387 100644
--- a/moli-indexeddb/Cargo.toml
+++ b/moli-indexeddb/Cargo.toml
@@ -9,6 +9,7 @@ moli-crypto = { path = "../moli-crypto" }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145"
strum = { version = "0.28.0", features = ["derive"] }
+unicode-id-start = "1.4.0"
[lints]
workspace = true
diff --git a/moli-indexeddb/src/error.rs b/moli-indexeddb/src/error.rs
index ed2430ce9..f8500125c 100644
--- a/moli-indexeddb/src/error.rs
+++ b/moli-indexeddb/src/error.rs
@@ -3,6 +3,7 @@ use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IndexedDbError {
Constraint(String),
+ InvalidAccess(String),
InvalidState(String),
NotFound(String),
QuotaExceeded { quota: u64, requested: u64 },
@@ -12,12 +13,14 @@ pub enum IndexedDbError {
Io(String),
Corruption(String),
Serialization(String),
+ Syntax(String),
}
impl fmt::Display for IndexedDbError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Constraint(message)
+ | Self::InvalidAccess(message)
| Self::InvalidState(message)
| Self::NotFound(message)
| Self::ReadOnly(message)
@@ -25,7 +28,8 @@ impl fmt::Display for IndexedDbError {
| Self::Version(message)
| Self::Io(message)
| Self::Corruption(message)
- | Self::Serialization(message) => f.write_str(message),
+ | Self::Serialization(message)
+ | Self::Syntax(message) => f.write_str(message),
Self::QuotaExceeded { quota, requested } => write!(
f,
"IndexedDB write would exceed storage quota: requested {requested} bytes, quota {quota} bytes"
diff --git a/moli-indexeddb/src/key.rs b/moli-indexeddb/src/key.rs
index 38a0255f6..350525e3b 100644
--- a/moli-indexeddb/src/key.rs
+++ b/moli-indexeddb/src/key.rs
@@ -56,6 +56,17 @@ pub enum KeyPath {
}
impl KeyPath {
+ /// Key paths contain identifiers separated by dots, or a non-empty list
+ /// of such strings. An empty string selects the entire stored value.
+ pub fn is_valid(&self) -> bool {
+ match self {
+ Self::String(path) => string_key_path_is_valid(path),
+ Self::Sequence(paths) => {
+ !paths.is_empty() && paths.iter().all(|path| string_key_path_is_valid(path))
+ }
+ }
+ }
+
pub fn is_sequence(&self) -> bool {
matches!(self, Self::Sequence(_))
}
@@ -65,6 +76,20 @@ impl KeyPath {
}
}
+fn string_key_path_is_valid(path: &str) -> bool {
+ path.is_empty()
+ || path.split('.').all(|identifier| {
+ let mut chars = identifier.chars();
+ chars
+ .next()
+ .is_some_and(|ch| matches!(ch, '$' | '_') || unicode_id_start::is_id_start(ch))
+ && chars.all(|ch| {
+ matches!(ch, '$' | '_' | '\u{200c}' | '\u{200d}')
+ || unicode_id_start::is_id_continue(ch)
+ })
+ })
+}
+
impl From<String> for KeyPath {
fn from(value: String) -> Self {
Self::String(value)
@@ -76,3 +101,63 @@ impl From<&str> for KeyPath {
Self::String(value.to_owned())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::KeyPath;
+
+ #[test]
+ fn key_paths_accept_unicode_identifiers_without_normalizing_them() {
+ for path in [
+ "",
+ "id",
+ "true.$",
+ "delete._",
+ "a0.b9",
+ "my.køi",
+ "名字.值",
+ "a\u{0301}",
+ "a\u{200c}\u{200d}",
+ "\u{2118}",
+ "\u{309b}",
+ "\u{10400}.id",
+ ] {
+ assert!(KeyPath::from(path).is_valid(), "{path:?}");
+ assert!(KeyPath::Sequence(vec![path.into()]).is_valid(), "{path:?}");
+ }
+ assert!(KeyPath::Sequence(vec!["id".into(), "meta.name".into()]).is_valid());
+ }
+
+ #[test]
+ fn key_paths_reject_empty_sequences_and_invalid_identifier_segments() {
+ for path in [
+ ".",
+ ".id",
+ "id.",
+ "id..name",
+ "0id",
+ "id.1",
+ "with space",
+ "id-name",
+ "id[0]",
+ "a,b",
+ "\u{0301}a",
+ "\u{200c}a",
+ "\u{200d}a",
+ "\u{fffd}",
+ "a\0b",
+ "a\nb",
+ "a\u{feff}",
+ "😀",
+ "\\u0061",
+ "a.\\u0062",
+ ] {
+ assert!(!KeyPath::from(path).is_valid(), "{path:?}");
+ assert!(
+ !KeyPath::Sequence(vec!["id".into(), path.into()]).is_valid(),
+ "{path:?}"
+ );
+ }
+ assert!(!KeyPath::Sequence(vec![]).is_valid());
+ }
+}
diff --git a/moli-indexeddb/src/manager.rs b/moli-indexeddb/src/manager.rs
index 5ab49795b..02a98c174 100644
--- a/moli-indexeddb/src/manager.rs
+++ b/moli-indexeddb/src/manager.rs
@@ -16,6 +16,7 @@ use crate::{
},
transaction::{ensure_writeable, resolve_key, transaction_store, transaction_store_mut},
usage::{database_usage_bytes, origin_usage_bytes, sum_usage},
+ validate_index_options, validate_object_store_options,
};
impl IndexedDbManager {
@@ -400,11 +401,29 @@ impl IndexedDbManager {
"create_object_store requires a versionchange transaction".to_owned(),
));
}
+ // Object-store creation checks syntax before duplicate names; index
+ // creation below deliberately uses the opposite order.
+ if options
+ .key_path
+ .as_ref()
+ .is_some_and(|path| !path.is_valid())
+ {
+ return Err(IndexedDbError::Syntax(
+ "The key path is not valid.".to_owned(),
+ ));
+ }
if tx.working_copy.stores.contains_key(name) {
return Err(IndexedDbError::Constraint(format!(
"object store `{name}` already exists"
)));
}
+ validate_object_store_options(options.key_path.as_ref(), options.auto_increment).map_err(
+ |_| {
+ IndexedDbError::InvalidAccess(
+ "autoIncrement cannot be used with an empty or sequence key path.".to_owned(),
+ )
+ },
+ )?;
tx.working_copy.stores.insert(
name.to_owned(),
ObjectStoreData {
@@ -458,11 +477,16 @@ impl IndexedDbManager {
"index `{index_name}` already exists"
)));
}
- if options.multi_entry && options.key_path.is_sequence() {
- return Err(IndexedDbError::InvalidState(
- "multiEntry indexes cannot use a sequence key_path".to_owned(),
+ if !options.key_path.is_valid() {
+ return Err(IndexedDbError::Syntax(
+ "The key path is not valid.".to_owned(),
));
}
+ validate_index_options(&options.key_path, options.multi_entry).map_err(|_| {
+ IndexedDbError::InvalidAccess(
+ "multiEntry indexes cannot use a sequence key path.".to_owned(),
+ )
+ })?;
let info = IndexInfo {
name: index_name.to_owned(),
key_path: options.key_path.clone(),
diff --git a/moli-indexeddb/src/tests.rs b/moli-indexeddb/src/tests.rs
index d8bda54a6..13f70f9be 100644
--- a/moli-indexeddb/src/tests.rs
+++ b/moli-indexeddb/src/tests.rs
@@ -12,6 +12,8 @@ use crate::{
*,
};
+mod schema_validation;
+
struct TestDir {
path: PathBuf,
}
diff --git a/moli-indexeddb/src/tests/schema_validation.rs b/moli-indexeddb/src/tests/schema_validation.rs
new file mode 100644
index 000000000..aa9ea7275
--- /dev/null
+++ b/moli-indexeddb/src/tests/schema_validation.rs
@@ -0,0 +1,96 @@
+use super::*;
+
+#[test]
+fn schema_validation_preserves_exception_order_and_does_not_create_invalid_metadata() {
+ let mut manager = IndexedDbManager::new_in_memory();
+ let open = manager
+ .open(OpenOptions {
+ origin: "origin".into(),
+ name: "schema".into(),
+ version: Some(1),
+ })
+ .unwrap();
+ let upgrade = open.upgrade_transaction.unwrap();
+ manager
+ .create_object_store(upgrade, "existing", ObjectStoreOptions::default())
+ .unwrap();
+ let invalid = ObjectStoreOptions {
+ key_path: Some(KeyPath::from("invalid path")),
+ auto_increment: true,
+ };
+ for name in ["existing", "invalid"] {
+ assert!(matches!(
+ manager.create_object_store(upgrade, name, invalid.clone()),
+ Err(IndexedDbError::Syntax(_))
+ ));
+ }
+ let empty = ObjectStoreOptions {
+ key_path: Some(KeyPath::from("")),
+ auto_increment: true,
+ };
+ assert!(matches!(
+ manager.create_object_store(upgrade, "existing", empty.clone()),
+ Err(IndexedDbError::Constraint(_))
+ ));
+ assert!(matches!(
+ manager.create_object_store(upgrade, "invalid", empty),
+ Err(IndexedDbError::InvalidAccess(_))
+ ));
+ assert!(matches!(
+ manager.create_object_store(
+ upgrade,
+ "invalid",
+ ObjectStoreOptions {
+ key_path: Some(KeyPath::Sequence(vec![])),
+ auto_increment: true,
+ }
+ ),
+ Err(IndexedDbError::Syntax(_))
+ ));
+ let valid = IndexOptions {
+ key_path: KeyPath::from("id"),
+ unique: false,
+ multi_entry: false,
+ };
+ manager
+ .create_index(upgrade, "existing", "index", valid)
+ .unwrap();
+ let invalid = IndexOptions {
+ key_path: KeyPath::Sequence(vec!["invalid path".into()]),
+ unique: false,
+ multi_entry: true,
+ };
+ assert!(matches!(
+ manager.create_index(upgrade, "existing", "index", invalid.clone()),
+ Err(IndexedDbError::Constraint(_))
+ ));
+ assert!(matches!(
+ manager.create_index(upgrade, "existing", "invalid", invalid),
+ Err(IndexedDbError::Syntax(_))
+ ));
+ assert!(matches!(
+ manager.create_index(
+ upgrade,
+ "existing",
+ "invalid",
+ IndexOptions {
+ key_path: KeyPath::Sequence(vec!["id".into()]),
+ unique: false,
+ multi_entry: true,
+ }
+ ),
+ Err(IndexedDbError::InvalidAccess(_))
+ ));
+ manager.commit_transaction(upgrade).unwrap();
+ assert_eq!(
+ manager
+ .object_store_info(open.database, "existing")
+ .unwrap()
+ .index_names,
+ ["index"]
+ );
+ assert!(matches!(
+ manager.object_store_info(open.database, "invalid"),
+ Err(IndexedDbError::NotFound(_))
+ ));
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/env/errors.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/env/errors.rs
index 93f0e895a..e9966d26f 100644
--- a/moli-renderer-v8/src/context_bootstrap/indexed_db/core/env/errors.rs
+++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/core/env/errors.rs
@@ -3,6 +3,7 @@ use super::*;
fn backend_error_name(error: &IndexedDbError) -> &'static str {
match error {
IndexedDbError::Constraint(_) => "ConstraintError",
+ IndexedDbError::InvalidAccess(_) => "InvalidAccessError",
IndexedDbError::InvalidState(message)
if message == "StorageBucket IndexedDB bucket is no longer current" =>
{
@@ -12,6 +13,7 @@ fn backend_error_name(error: &IndexedDbError) -> &'static str {
IndexedDbError::NotFound(_) => "NotFoundError",
IndexedDbError::QuotaExceeded { .. } => "QuotaExceededError",
IndexedDbError::ReadOnly(_) => "ReadOnlyError",
+ IndexedDbError::Syntax(_) => "SyntaxError",
IndexedDbError::TransactionInactive(_) => "TransactionInactiveError",
IndexedDbError::Version(_) => "VersionError",
IndexedDbError::Io(_)