Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(pathlock): prevent path aliases from bypassing locks (#6687)

zhanglistar54d4c0fac91f
diff --git a/crates/ragfs/src/lock/cache_provder.rs b/crates/ragfs/src/lock/cache_provder.rs
index db69a3a4c..47fbd49de 100644
--- a/crates/ragfs/src/lock/cache_provder.rs
+++ b/crates/ragfs/src/lock/cache_provder.rs
@@ -12,6 +12,7 @@ use crate::cache_runtime::{
};
use super::codec::LockTokenCodec;
+use super::path::validate_normalized_logical_path;
use super::provider::{
AcquisitionChange, AtomicAcquisition, AtomicAcquisitionResult, PathLockHandleMode,
PathLockProvider,
@@ -79,6 +80,21 @@ local function decode_token(raw)
end
return { owner = token_owner, time_ns = time_ns, kind = kind }
end
+local function is_normalized_path(path)
+ if not path or string.sub(path, 1, 1) ~= "/"
+ or (path ~= "/" and string.sub(path, -1) == "/")
+ or string.find(path, "//", 1, true)
+ or string.find(path, string.char(0), 1, true) then
+ return false
+ end
+ for part in string.gmatch(path, "[^/]+") do
+ if part == "." or part == ".." then
+ return false
+ end
+ end
+ return true
+end
+
local function ancestors(path)
local result = {}
if path == "/" then
@@ -127,9 +143,7 @@ local includes_tree = false
for index = 5, #ARGV, 2 do
local path = ARGV[index]
local kind = ARGV[index + 1]
- if not path or string.sub(path, 1, 1) ~= "/"
- or (path ~= "/" and string.sub(path, -1) == "/")
- or (kind ~= "E" and kind ~= "T") then
+ if not is_normalized_path(path) or (kind ~= "E" and kind ~= "T") then
return { "invalid_request", "invalid path or lock kind" }
end
table.insert(requests, { path = path, kind = kind })
@@ -535,6 +549,7 @@ impl RedisPathLockProvider {
/// Return the Redis HASH key responsible for one logical path.
fn tokens_key_for_path(&self, path: &str) -> PathLockResult<String> {
+ validate_normalized_logical_path(path)?;
let suffix = if path == "/" || path == "/local" {
"global".to_string()
} else {
@@ -1188,6 +1203,7 @@ mod tests {
use crate::cache_runtime::{
CacheRuntime, RedisProviderConfig, ScriptDefinition, ScriptRequest, ScriptValue,
};
+ use crate::core::FileSystem;
use crate::plugins::memfs::MemFileSystem;
use super::super::manager::{PathLockConfig, PathLockManager};
@@ -1532,6 +1548,191 @@ return redis.call("HGET", KEYS[1], ARGV[2])
runtime.close().await.unwrap();
}
+ /// Real filesystem aliases must not bypass another manager's Redis Exact lock.
+ #[tokio::test]
+ async fn redis_path_aliases_cannot_write_a_locked_file() {
+ let Some((runtime, provider)) = test_provider("path-alias-write").await else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let fs = Arc::new(
+ crate::plugins::localfs::LocalFileSystem::new(dir.path().to_str().unwrap()).unwrap(),
+ );
+ let path = "/local/account-a/file";
+ std::fs::create_dir_all(dir.path().join("local/account-a")).unwrap();
+ fs.write(path, b"original", 0, crate::core::WriteFlag::Create)
+ .await
+ .unwrap();
+ let second_provider =
+ RedisPathLockProvider::new(runtime.clone(), &provider.service_name, 1.0).unwrap();
+ let config = PathLockConfig {
+ lock_expire_secs: 1.0,
+ ..PathLockConfig::default()
+ };
+ let first = PathLockManager::new(fs.clone(), Arc::new(provider), config.clone());
+ let second = Arc::new(PathLockManager::new(
+ fs.clone(),
+ Arc::new(second_provider),
+ config,
+ ));
+ let wrapped = crate::lock::PathLockWrappedFS::new(second, fs.clone());
+ let lease = first
+ .acquire_exact(path, Duration::ZERO, None)
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ wrapped
+ .write(path, b"modified", 0, crate::core::WriteFlag::Truncate)
+ .await,
+ Err(crate::core::Error::PathLock(PathLockError::Timeout { .. }))
+ ));
+ for alias in [
+ "/local/account-a/./file",
+ "/local/account-a//file",
+ "/local/./account-a/file",
+ ] {
+ assert_eq!(fs.read(alias, 0, 100).await.unwrap(), b"original");
+ assert!(
+ wrapped
+ .write(alias, b"modified", 0, crate::core::WriteFlag::Truncate)
+ .await
+ .is_err(),
+ "write through alias {alias} bypassed the lock"
+ );
+ assert_eq!(fs.read(path, 0, 100).await.unwrap(), b"original");
+ }
+ first.release(&lease).await.unwrap();
+ wrapped
+ .write(path, b"modified", 0, crate::core::WriteFlag::Truncate)
+ .await
+ .unwrap();
+ assert_eq!(fs.read(path, 0, 100).await.unwrap(), b"modified");
+ runtime.close().await.unwrap();
+ }
+
+ /// Lua validates the entire batch before writing any target or cleaning stale tokens.
+ #[tokio::test]
+ async fn redis_lua_rejects_path_aliases_before_mutation() {
+ let Some((runtime, provider)) = test_provider("path-alias-lua").await else {
+ return;
+ };
+ let valid = "/local/account-a/file";
+ let stale_path = "/local/account-a/stale";
+ let stale = token("old-owner", 1, PathLockKind::Exact);
+ provider.try_create_token(stale_path, &stale).await.unwrap();
+ for path in [
+ "",
+ "relative",
+ "//",
+ "/local/account-a/file/",
+ "/local/account-a//file",
+ "/local/account-a/./file",
+ "/local/account-a/../file",
+ "/local/account-a/file\0",
+ ] {
+ for kind in ["E", "T"] {
+ let values = provider
+ .execute_array(
+ ACQUIRE_BATCH_ID,
+ provider.tokens_key_for_path(valid).unwrap(),
+ ["owner", "200", "100", "2000", valid, "E", path, kind]
+ .iter()
+ .map(RedisPathLockProvider::bytes)
+ .collect(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ RedisPathLockProvider::result_status(&values, "test").unwrap(),
+ "invalid_request",
+ "Lua accepted {path:?}"
+ );
+ assert_eq!(provider.read_token(valid).await.unwrap(), None);
+ assert_eq!(
+ provider.read_token(stale_path).await.unwrap(),
+ Some(stale.clone())
+ );
+ }
+ }
+ runtime.close().await.unwrap();
+ }
+
+ /// Every Redis token entry point rejects noncanonical paths before executing scripts.
+ #[tokio::test]
+ async fn redis_provider_rejects_path_aliases_before_script_access() {
+ let mock = crate::cache_runtime::MemoryMockProvider::new()
+ .with_script_handler(|_| panic!("invalid path must not execute a Redis script"));
+ let runtime = CacheRuntime::memory_with_provider(Arc::new(mock));
+ let provider = RedisPathLockProvider::new(runtime.clone(), "path-validation", 1.0).unwrap();
+ let original = token("owner", 100, PathLockKind::Exact);
+ for path in [
+ "",
+ "relative",
+ "//",
+ "/local/account-a/file/",
+ "/local/account-a/file//",
+ "/local/account-a//file",
+ "/local/account-a/./file",
+ "/local/account-a/../file",
+ "/local/account-a/file\0",
+ ] {
+ for kind in [PathLockKind::Exact, PathLockKind::Tree] {
+ assert!(matches!(
+ provider
+ .try_acquire_batch_atomic(
+ &[
+ request("/local/account-a/valid", PathLockKind::Exact),
+ request(path, kind)
+ ],
+ "owner",
+ 200,
+ 100,
+ )
+ .await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ }
+ assert!(matches!(
+ provider.try_create_token(path, &original).await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ assert!(matches!(
+ provider
+ .compare_and_write_token(path, &original, &original)
+ .await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ assert!(matches!(
+ provider.read_token(path).await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ assert!(matches!(
+ provider.refresh_token(path, "owner", 200).await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ assert!(matches!(
+ &provider
+ .refresh_tokens(&[path.to_string()], "owner", 200)
+ .await[0],
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ assert!(matches!(
+ provider.remove_token(path, "owner", false).await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ assert!(matches!(
+ provider.scan_descendant_locks(path).await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ assert!(matches!(
+ provider.is_path_locked_atomic(path, 200, 100, true).await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ }
+ runtime.close().await.unwrap();
+ }
+
/// Reject global Tree requests before accessing Redis, including token upgrades.
#[tokio::test]
async fn provider_rejects_cross_scope_tree_before_redis_access() {
diff --git a/crates/ragfs/src/lock/manager.rs b/crates/ragfs/src/lock/manager.rs
index 22b7ed044..3372e2539 100644
--- a/crates/ragfs/src/lock/manager.rs
+++ b/crates/ragfs/src/lock/manager.rs
@@ -17,6 +17,7 @@ use crate::core::internal_names::{EXACT_LOCK_FILE_PREFIX, PATH_LOCK_FILE};
use crate::core::{FileSystem, FsContextView};
use super::metrics::LockMetrics;
+use super::path::normalize_logical_path;
use super::provider::{AcquisitionChange, AtomicAcquisition, PathLockHandleMode, PathLockProvider};
use super::resolver::{LockPathResolver, ResolvedExactPaths};
use super::types::{
@@ -669,10 +670,10 @@ impl PathLockManager {
}
/// Normalize, deduplicate, and sort requests with Tree taking precedence over Exact.
- fn normalize_requests(requests: &[PathLockRequest]) -> Vec<PathLockRequest> {
+ fn normalize_requests(requests: &[PathLockRequest]) -> PathLockResult<Vec<PathLockRequest>> {
let mut by_path: HashMap<String, PathLockKind> = HashMap::new();
for request in requests {
- let path = Self::normalize_path(&request.path);
+ let path = normalize_logical_path(&request.path)?.to_string();
by_path
.entry(path)
.and_modify(|kind| {
@@ -693,17 +694,7 @@ impl PathLockManager {
.cmp(&b.path.len())
.then_with(|| a.path.cmp(&b.path))
});
- normalized
- }
-
- /// Normalize one logical path using the existing PathLock trailing-slash rule.
- fn normalize_path(path: &str) -> String {
- let trimmed = path.trim_end_matches('/');
- if trimmed.is_empty() {
- "/".to_string()
- } else {
- trimmed.to_string()
- }
+ Ok(normalized)
}
/// Return the configured lock expiry in nanoseconds.
@@ -851,7 +842,7 @@ impl PathLockManager {
"lock request batch must not be empty".to_string(),
));
}
- let sorted = Self::normalize_requests(requests);
+ let sorted = Self::normalize_requests(requests)?;
let owner = self.resolve_owner_state(owner_capability)?;
let owner_id = owner.owner_id.clone();
@@ -1751,6 +1742,9 @@ impl PathLockManager {
"handoff owner_id and lock_paths must not be empty".to_string(),
));
}
+ for request in &handoff.covered_paths {
+ normalize_logical_path(&request.path)?;
+ }
// Local fast path: a handoff carrying lease_ref MUST be adopted from this
// process's registry — it is never legacy. Adopt in-place (migrate to a fresh
@@ -1834,8 +1828,8 @@ impl PathLockManager {
let expected_kind = match handle_mode {
PathLockHandleMode::LogicalPath => {
let request = &handoff.covered_paths[index];
- let expected_path = Self::normalize_path(&request.path);
- if lp != &expected_path {
+ let expected_path = normalize_logical_path(&request.path)?;
+ if lp != expected_path {
return Err(PathLockError::InvalidRequest(format!(
"handoff coverage '{}' does not match logical lock path '{lp}'",
request.path
@@ -1976,11 +1970,11 @@ impl PathLockManager {
/// Check if a path is locked (for observability).
pub async fn is_locked(&self, path: &str, ignore_stale: bool) -> PathLockResult<bool> {
let now_ns = Self::now_ns();
- let normalized_path = Self::normalize_path(path);
+ let normalized_path = normalize_logical_path(path)?;
if let Some(locked) = self
.provider
.is_path_locked_atomic(
- &normalized_path,
+ normalized_path,
now_ns,
now_ns.saturating_sub(self.lock_expire_ns()),
ignore_stale,
@@ -1993,7 +1987,7 @@ impl PathLockManager {
// Check the current sidecar and the legacy in-directory token.
let exact_paths = self
.resolver
- .resolve_exact_conflict_paths(&normalized_path)
+ .resolve_exact_conflict_paths(normalized_path)
.await?;
for lp in &exact_paths {
if let Ok(Some(token)) = self.provider.read_token(lp).await {
@@ -2004,7 +1998,7 @@ impl PathLockManager {
}
// Check ancestor tree locks.
- for parent in LockPathResolver::ancestor_paths(&normalized_path) {
+ for parent in LockPathResolver::ancestor_paths(normalized_path) {
for ancestor_lock in self.resolver.resolve_tree_conflict_paths(&parent).await? {
if let Ok(Some(token)) = self.provider.read_token(&ancestor_lock).await {
// Only Tree locks propagate to descendants.
@@ -2081,6 +2075,9 @@ impl PathLockManager {
lease_ref: &str,
requests: &[PathLockRequest],
) -> PathLockResult<()> {
+ for request in requests {
+ normalize_logical_path(&request.path)?;
+ }
let owner = self.lease_registry.resolve(lease_ref).ok_or_else(|| {
PathLockError::InvalidRequest(format!("unknown pathlock lease ref '{lease_ref}'"))
})?;
@@ -2110,6 +2107,9 @@ impl PathLockManager {
debug!(requests = ?requests, "pathlock auto action resolved to disabled");
return Ok(AutoPathLockAction::Disabled);
}
+ for request in requests {
+ normalize_logical_path(&request.path)?;
+ }
let Some(lease_ref) = view.pathlock_lease_ref() else {
debug!(requests = ?requests, "pathlock auto action resolved to acquire");
return Ok(AutoPathLockAction::Acquire);
diff --git a/crates/ragfs/src/lock/mod.rs b/crates/ragfs/src/lock/mod.rs
index adb7abe1e..e9096e083 100644
--- a/crates/ragfs/src/lock/mod.rs
+++ b/crates/ragfs/src/lock/mod.rs
@@ -17,6 +17,7 @@ pub mod codec;
mod cache_provder;
pub mod manager;
pub mod metrics;
+mod path;
pub mod provider;
pub mod resolver;
pub mod sqlite_provider;
diff --git a/crates/ragfs/src/lock/path.rs b/crates/ragfs/src/lock/path.rs
new file mode 100644
index 000000000..ebec8bb19
--- /dev/null
+++ b/crates/ragfs/src/lock/path.rs
@@ -0,0 +1,198 @@
+//! Shared lexical path rules for lock identity and lease coverage.
+
+use super::types::{PathLockError, PathLockResult};
+
+/// Validate a logical path and preserve compatibility with a single trailing slash.
+///
+/// Reject aliases instead of rewriting them: the filesystem still receives the
+/// original path, and resolving `..` could change the operation's scope.
+pub(super) fn normalize_logical_path(path: &str) -> PathLockResult<&str> {
+ if !path.starts_with('/')
+ || path.contains("//")
+ || path.contains('\0')
+ || path.split('/').any(|part| matches!(part, "." | ".."))
+ {
+ return Err(PathLockError::InvalidRequest(format!(
+ "PathLock requires an absolute logical path without repeated '/', \
+ '.' or '..' components, or NUL: {path:?}"
+ )));
+ }
+ Ok(if path == "/" {
+ path
+ } else {
+ path.strip_suffix('/').unwrap_or(path)
+ })
+}
+
+/// Provider token paths must already be normalized by the Manager.
+pub(super) fn validate_normalized_logical_path(path: &str) -> PathLockResult<()> {
+ if normalize_logical_path(path)? != path {
+ return Err(PathLockError::InvalidRequest(format!(
+ "PathLock requires a normalized absolute logical path: {path:?}"
+ )));
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::core::{FileSystem, FsContextInner, PathLockContext, FS_CTX};
+ use crate::lock::types::PathLockKind;
+ use crate::lock::{MemoryPathLockProvider, PathLockConfig, PathLockManager, PathLockRequest};
+ use crate::plugins::memfs::MemFileSystem;
+ use std::sync::Arc;
+ use std::time::Duration;
+
+ #[test]
+ fn logical_paths_reject_aliases_and_preserve_valid_names() {
+ for path in [
+ "", "relative", "//", "/a//b", "/a//", "/a/./b", "/./a", "/a/../b", "/a/.", "/a/..",
+ "/a\0b",
+ ] {
+ assert!(normalize_logical_path(path).is_err(), "{path:?}");
+ assert!(validate_normalized_logical_path(path).is_err(), "{path:?}");
+ }
+ for path in [
+ "/",
+ "/a",
+ "/a/.hidden",
+ "/a/file..txt",
+ "/中文/文件",
+ "/a/file name",
+ ] {
+ assert_eq!(normalize_logical_path(path).unwrap(), path);
+ validate_normalized_logical_path(path).unwrap();
+ }
+ assert_eq!(normalize_logical_path("/a/").unwrap(), "/a");
+ assert!(validate_normalized_logical_path("/a/").is_err());
+ }
+
+ /// Invalid aliases cannot acquire locks, query locks, or borrow Tree coverage.
+ #[tokio::test]
+ async fn path_aliases_are_rejected_before_acquisition_and_coverage() {
+ let fs = Arc::new(MemFileSystem::new());
+ fs.mkdir("/data", 0o755).await.unwrap();
+ let mgr = PathLockManager::new(
+ fs.clone(),
+ Arc::new(MemoryPathLockProvider::new()),
+ PathLockConfig::default(),
+ );
+ let tree = mgr
+ .acquire_tree("/data", Duration::ZERO, None)
+ .await
+ .unwrap();
+ let context = Arc::new(FsContextInner::with_pathlock(
+ "account",
+ PathLockContext {
+ lease_ref: Some(tree.lease.lease_ref.clone()),
+ disable_auto_pathlock: false,
+ },
+ ));
+ for path in [
+ "",
+ "relative",
+ "//",
+ "/data//file",
+ "/data/./file",
+ "/data/../other/file",
+ "/data/file//",
+ "/data/file\0",
+ ] {
+ let request = PathLockRequest {
+ path: path.to_string(),
+ kind: PathLockKind::Exact,
+ };
+ for kind in [PathLockKind::Exact, PathLockKind::Tree] {
+ assert!(
+ matches!(
+ mgr.acquire_batch(
+ &[
+ PathLockRequest {
+ path: "/unrelated/file".into(),
+ kind: PathLockKind::Exact
+ },
+ PathLockRequest {
+ path: path.into(),
+ kind
+ },
+ ],
+ Duration::ZERO,
+ None
+ )
+ .await,
+ Err(PathLockError::InvalidRequest(_))
+ ),
+ "Manager accepted {path:?}"
+ );
+ }
+ assert!(
+ matches!(
+ mgr.is_locked(path, true).await,
+ Err(PathLockError::InvalidRequest(_))
+ ),
+ "is_locked accepted {path:?}"
+ );
+ assert!(
+ !tree.lease.covers(&request),
+ "Tree lease covered alias {path:?}"
+ );
+ assert!(matches!(
+ mgr.require_covered_lease_ref(&tree.lease.lease_ref, &[request.clone()])
+ .await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ assert!(matches!(
+ mgr.resolve_auto_pathlock_action(&[request.clone()]).await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ assert!(matches!(
+ FS_CTX
+ .scope(context.clone(), async {
+ mgr.resolve_auto_pathlock_action(&[request.clone()]).await
+ })
+ .await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ let mut handoff = mgr.to_handoff(&tree);
+ handoff.covered_paths = vec![request];
+ assert!(matches!(
+ mgr.adopt(&handoff).await,
+ Err(PathLockError::InvalidRequest(_))
+ ));
+ }
+ assert!(matches!(
+ fs.stat("/unrelated").await,
+ Err(crate::core::Error::NotFound(_))
+ ));
+ assert_eq!(mgr.metrics_snapshot().await.active_lock_count, 1);
+ mgr.release(&tree).await.unwrap();
+ }
+
+ /// A single trailing slash retains the existing canonical lease identity.
+ #[tokio::test]
+ async fn trailing_slash_uses_the_same_lock_path() {
+ let fs = Arc::new(MemFileSystem::new());
+ fs.mkdir("/data", 0o755).await.unwrap();
+ let mgr = PathLockManager::new(
+ fs,
+ Arc::new(MemoryPathLockProvider::new()),
+ PathLockConfig::default(),
+ );
+ let lease = mgr
+ .acquire_exact("/data/file/", Duration::ZERO, None)
+ .await
+ .unwrap();
+ assert_eq!(lease.lease.covered_paths[0].path, "/data/file");
+ assert!(mgr.is_locked("/data/file/", true).await.unwrap());
+ assert!(lease.lease.covers(&PathLockRequest {
+ path: "/data/file/".into(),
+ kind: PathLockKind::Exact,
+ }));
+ assert!(matches!(
+ mgr.acquire_exact("/data/file", Duration::ZERO, None).await,
+ Err(PathLockError::Timeout { .. })
+ ));
+ mgr.release(&lease).await.unwrap();
+ }
+}
diff --git a/crates/ragfs/src/lock/sqlite_provider.rs b/crates/ragfs/src/lock/sqlite_provider.rs
index 0dfa9af81..115e64521 100644
--- a/crates/ragfs/src/lock/sqlite_provider.rs
+++ b/crates/ragfs/src/lock/sqlite_provider.rs
@@ -7,6 +7,7 @@ use std::time::Duration;
use async_trait::async_trait;
use rusqlite::{params, Connection, OptionalExtension, TransactionBehavior};
+use super::path::validate_normalized_logical_path as validate_path;
use super::provider::{
AcquisitionChange, AtomicAcquisition, AtomicAcquisitionResult, PathLockHandleMode,
PathLockProvider,
@@ -50,20 +51,6 @@ fn timestamp(time_ns: u128) -> String {
format!("{time_ns:039}")
}
-fn validate_path(path: &str) -> PathLockResult<()> {
- if !path.starts_with('/')
- || (path != "/" && path.ends_with('/'))
- || path.contains("//")
- || path.contains('\0')
- || path.split('/').any(|part| matches!(part, "." | ".."))
- {
- return Err(PathLockError::InvalidRequest(format!(
- "SQLite PathLock requires a normalized absolute logical path: {path}"
- )));
- }
- Ok(())
-}
-
fn validate_owner(owner: &str) -> PathLockResult<()> {
if owner.is_empty() || owner.contains(':') {
return Err(PathLockError::InvalidRequest(
diff --git a/crates/ragfs/src/lock/types.rs b/crates/ragfs/src/lock/types.rs
index 8cdbba3a7..faacbe594 100644
--- a/crates/ragfs/src/lock/types.rs
+++ b/crates/ragfs/src/lock/types.rs
@@ -2,6 +2,8 @@
use serde::{Deserialize, Serialize};
+use super::path::normalize_logical_path;
+
/// Lock kind: exact (single path) or tree (path + descendants).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PathLockKind {
@@ -106,31 +108,25 @@ impl PathLockLease {
/// Return true when a held request covers another requested operation.
fn request_is_covered_by(held: &PathLockRequest, request: &PathLockRequest) -> bool {
+ let (Ok(held_path), Ok(request_path)) = (
+ normalize_logical_path(&held.path),
+ normalize_logical_path(&request.path),
+ ) else {
+ return false;
+ };
match (held.kind, request.kind) {
- (PathLockKind::Exact, PathLockKind::Exact) => normalize_path(&held.path) == normalize_path(&request.path),
- (PathLockKind::Tree, _) => path_is_self_or_descendant(&request.path, &held.path),
+ (PathLockKind::Exact, PathLockKind::Exact) => held_path == request_path,
+ (PathLockKind::Tree, _) => path_is_self_or_descendant(request_path, held_path),
(PathLockKind::Exact, PathLockKind::Tree) => false,
}
}
-/// Normalize a path for simple lock coverage checks.
-fn normalize_path(path: &str) -> String {
- let trimmed = path.trim_end_matches('/');
- if trimmed.is_empty() {
- "/".to_string()
- } else {
- trimmed.to_string()
- }
-}
-
-/// Return true when `path` is equal to or under `ancestor`.
+/// Return true when a normalized `path` is equal to or under `ancestor`.
fn path_is_self_or_descendant(path: &str, ancestor: &str) -> bool {
- let path = normalize_path(path);
- let ancestor = normalize_path(ancestor);
path == ancestor
|| ancestor == "/"
|| path
- .strip_prefix(&ancestor)
+ .strip_prefix(ancestor)
.is_some_and(|suffix| suffix.starts_with('/'))
}
diff --git a/docs/en/concepts/09-transaction.md b/docs/en/concepts/09-transaction.md
index c0501cfa4..77504802b 100644
--- a/docs/en/concepts/09-transaction.md
+++ b/docs/en/concepts/09-transaction.md
@@ -224,6 +224,14 @@ The lock mechanism uses two lock types to handle different conflict patterns:
Exact and Tree describe an operation's scope; file, directory, and missing describe the target's current state. These are independent. Locks protect path names, including names that do not currently exist.
+Lock paths must be absolute. The Manager rejects empty or relative paths, repeated
+`/`, `.` or `..` components, and NUL with `InvalidRequest` before acquiring locks
+or checking lease coverage. A single trailing `/` is stripped, except at `/`.
+Redis and SQLite token operations require this normalized form; Redis Lua batch
+acquisition also validates every request before mutating tokens. Use
+`/local/account-a/file`, rather than aliases such as `/local/account-a/./file`
+or `/local/account-a//file`.
+
The following conflicts apply to different owners within the same provider scope:
| Held lock | New request | Conflict |
diff --git a/docs/zh/concepts/09-transaction.md b/docs/zh/concepts/09-transaction.md
index c4156ed9e..ed5771919 100644
--- a/docs/zh/concepts/09-transaction.md
+++ b/docs/zh/concepts/09-transaction.md
@@ -221,6 +221,13 @@ async with LockContext(lock_manager, [src], lock_mode="mv", mv_dst_path=dst):
Exact 和 Tree 表达操作范围,文件、目录或缺失路径表达目标的当前状态,两者独立。锁保护路径名字,目标不存在也可以申请锁。
+锁路径必须是绝对路径。Manager 在获取锁或检查租约覆盖范围前,对空路径、
+相对路径、重复 `/`、`.` 或 `..` 路径段及 NUL 返回 `InvalidRequest`。
+非根路径末尾的单个 `/` 会被移除。Redis 和 SQLite 的 token 操作要求路径
+已完成这一规范化;Redis Lua 批量获取也会在修改 token 前校验全部请求。
+应使用 `/local/account-a/file`,避免 `/local/account-a/./file`、
+`/local/account-a//file` 等别名。
+
以下冲突关系限定为不同 owner、同一 Provider scope 内的请求:
| 已持有 | 新请求 | 冲突 |