Skip to content

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

feat(privacy): support automatic privacy extraction and restore for sessions (#6278)

Wenxi Zhu0d546854b4be
diff --git a/crates/ragfs-python/src/lib.rs b/crates/ragfs-python/src/lib.rs
index a31efe5b2..129524107 100644
--- a/crates/ragfs-python/src/lib.rs
+++ b/crates/ragfs-python/src/lib.rs
@@ -920,6 +920,7 @@ fn cache_policy_from_config(config: &RagfsCacheConfig) -> CachePolicy {
mod git;
mod privacy;
+mod privacy_extractor;
fn py_detach_blocking<T, F>(py: Python<'_>, f: F) -> T
where
@@ -3091,6 +3092,7 @@ impl RAGFSBindingClient {
fn ragfs_python(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<RAGFSBindingClient>()?;
m.add_class::<privacy::PyPrivacyMatcher>()?;
+ m.add_class::<privacy_extractor::PyPrivacyExtractor>()?;
m.add_function(wrap_pyfunction!(reopen_tracing_file, m)?)?;
// Import the Python business exception so native code raises the same type
diff --git a/crates/ragfs-python/src/privacy.rs b/crates/ragfs-python/src/privacy.rs
index b86e1606a..4acbba1de 100644
--- a/crates/ragfs-python/src/privacy.rs
+++ b/crates/ragfs-python/src/privacy.rs
@@ -1,7 +1,8 @@
//! Thin PyO3 wrapper around RAGFS's compiled Privacy matcher.
-use pyo3::exceptions::PyValueError;
+use pyo3::exceptions::{PyOverflowError, PyValueError};
use pyo3::prelude::*;
+use pyo3::types::PyString;
use ragfs::privacy_matcher::PrivacyMatcher;
use std::collections::HashMap;
use std::sync::Arc;
@@ -74,4 +75,32 @@ impl PyPrivacyMatcher {
limit_exceeded,
)
}
+
+ /// Return bounded match metadata without copying or rewriting the input.
+ ///
+ /// Borrow Python's UTF-8 representation for both the byte-size check and
+ /// matching. The immutable Python string stays alive while the GIL is
+ /// released. Oversized input raises OverflowError before matching begins.
+ fn find_limited(
+ &self,
+ py: Python<'_>,
+ content: &Bound<'_, PyString>,
+ max_replacements: usize,
+ max_content_bytes: usize,
+ ) -> PyResult<(Vec<(usize, usize, String)>, Vec<Vec<String>>, bool)> {
+ let content = content.to_str()?;
+ if content.len() > max_content_bytes {
+ return Err(PyOverflowError::new_err(
+ "Content exceeds the Privacy sanitizer size limit",
+ ));
+ }
+ let matcher = self.inner.clone();
+ let (result, exceeded) = py.detach(move || matcher.find_limited(content, max_replacements));
+ let replacements = result
+ .replacements
+ .into_iter()
+ .map(|replacement| (replacement.start, replacement.end, replacement.reference))
+ .collect();
+ Ok((replacements, result.ambiguous_references, exceeded))
+ }
}
diff --git a/crates/ragfs-python/src/privacy_extractor.rs b/crates/ragfs-python/src/privacy_extractor.rs
new file mode 100644
index 000000000..ae46d5c71
--- /dev/null
+++ b/crates/ragfs-python/src/privacy_extractor.rs
@@ -0,0 +1,37 @@
+//! PyO3 access to fixed-rule credential discovery, separate from file scanning.
+
+use pyo3::exceptions::PyValueError;
+use pyo3::prelude::*;
+use ragfs::privacy_extractor::PrivacyExtractor;
+use std::sync::Arc;
+
+#[pyclass(name = "PrivacyExtractor", module = "ragfs_python")]
+pub(crate) struct PyPrivacyExtractor {
+ inner: Arc<PrivacyExtractor>,
+}
+
+#[pymethods]
+impl PyPrivacyExtractor {
+ #[new]
+ fn new() -> PyResult<Self> {
+ Ok(Self {
+ inner: Arc::new(PrivacyExtractor::new().map_err(PyValueError::new_err)?),
+ })
+ }
+
+ #[pyo3(signature = (content, field_name=None))]
+ fn extract(
+ &self,
+ py: Python<'_>,
+ content: String,
+ field_name: Option<String>,
+ ) -> PyResult<Vec<(usize, usize, String)>> {
+ let inner = self.inner.clone();
+ py.detach(move || inner.extract(&content, field_name.as_deref()))
+ .map_err(PyValueError::new_err)
+ }
+
+ fn is_sensitive_key(&self, key: &str) -> bool {
+ self.inner.is_sensitive_key(key)
+ }
+}
diff --git a/crates/ragfs/src/lib.rs b/crates/ragfs/src/lib.rs
index 54ff3f528..dbc85477c 100644
--- a/crates/ragfs/src/lib.rs
+++ b/crates/ragfs/src/lib.rs
@@ -40,6 +40,7 @@ pub mod lock;
pub mod metrics;
pub mod multibackend;
pub mod plugins;
+pub mod privacy_extractor;
pub mod privacy_matcher;
pub mod shape;
diff --git a/crates/ragfs/src/privacy_extractor.rs b/crates/ragfs/src/privacy_extractor.rs
new file mode 100644
index 000000000..de51e161e
--- /dev/null
+++ b/crates/ragfs/src/privacy_extractor.rs
@@ -0,0 +1,727 @@
+//! Fixed-rule discovery of credentials in text and named fields.
+//! Positions are Unicode character offsets, suitable for Python string slicing.
+
+use regex::Regex;
+use serde::Deserialize;
+use std::collections::{HashMap, HashSet};
+
+#[derive(Deserialize)]
+struct Config {
+ normalized_names: HashSet<String>,
+ suffixes: Vec<String>,
+ token_hints: Vec<String>,
+ token_pattern: String,
+ assignment_pattern: String,
+ cli_pattern: String,
+ auth_pattern: String,
+ scheme_pattern: String,
+ bracket_pattern: String,
+ reference_pattern: String,
+}
+
+/// Compiled, immutable fixed rules used for Session credential discovery.
+pub struct PrivacyExtractor {
+ cfg: Config,
+ token: Regex,
+ assignment: Regex,
+ cli: Regex,
+ auth: Regex,
+ scheme: Regex,
+ bracket: Regex,
+ reference: Regex,
+ bold: Regex,
+ code_delimiter: Regex,
+ unicode_alphanumeric: Regex,
+}
+
+#[derive(Clone, Debug)]
+struct Hit {
+ start: usize,
+ end: usize,
+ field: String,
+}
+
+impl PrivacyExtractor {
+ /// Compile the built-in credential rules once for reuse across messages.
+ pub fn new() -> Result<Self, String> {
+ let cfg: Config = serde_json::from_str(include_str!("privacy_extractor_rules.json"))
+ .map_err(|error| error.to_string())?;
+ Ok(Self {
+ token: Regex::new(&cfg.token_pattern).map_err(|error| error.to_string())?,
+ assignment: Regex::new(&format!("(?i){}", cfg.assignment_pattern))
+ .map_err(|error| error.to_string())?,
+ cli: Regex::new(&cfg.cli_pattern).map_err(|error| error.to_string())?,
+ auth: Regex::new(&cfg.auth_pattern).map_err(|error| error.to_string())?,
+ scheme: Regex::new(&cfg.scheme_pattern).map_err(|error| error.to_string())?,
+ bracket: Regex::new(&cfg.bracket_pattern).map_err(|error| error.to_string())?,
+ reference: Regex::new(&cfg.reference_pattern).map_err(|error| error.to_string())?,
+ bold: Regex::new(r"(?:^|[\s(>=:])\*\*(?P<text>[^\s*](?:[^\r\n]*?[^\s*])?)\*\*")
+ .map_err(|error| error.to_string())?,
+ code_delimiter: Regex::new(r"`+|~{3,}").map_err(|error| error.to_string())?,
+ unicode_alphanumeric: Regex::new(r"^[\p{L}\p{N}]$")
+ .map_err(|error| error.to_string())?,
+ cfg,
+ })
+ }
+
+ fn word(&self, c: char) -> bool {
+ if c.is_ascii() {
+ return c.is_ascii_alphanumeric() || c == '_';
+ }
+ // General categories Letter and Number match Python's alphanumeric
+ // definition. Rust's Alphabetic property also includes combining marks.
+ self.unicode_alphanumeric
+ .is_match(c.encode_utf8(&mut [0; 4]))
+ }
+
+ fn boundary(&self, s: &str, pos: usize) -> bool {
+ s[..pos]
+ .chars()
+ .next_back()
+ .map_or(true, |c| c != '-' && !self.word(c))
+ }
+
+ /// Whether a structured input key denotes a complete sensitive value.
+ pub fn is_sensitive_key(&self, key: &str) -> bool {
+ let lower = key.to_lowercase().replace('-', "_");
+ self.cfg
+ .suffixes
+ .iter()
+ .any(|suffix| lower.ends_with(suffix))
+ || self.cfg.normalized_names.contains(&normalize_key(&lower))
+ }
+
+ fn env_end(&self, s: &str, p: usize) -> Option<usize> {
+ let tail = &s[p..];
+ if tail.starts_with("${") {
+ let mut n = 0;
+ for (i, c) in tail[2..].char_indices() {
+ if c == '}' {
+ return (n > 0).then_some(p + 2 + i + 1);
+ }
+ if c == '{' || space(c) {
+ return None;
+ }
+ n += 1;
+ }
+ } else if tail.starts_with('$') {
+ let mut chars = tail[1..].char_indices();
+ let (_, first) = chars.next()?;
+ if !first.is_ascii_alphabetic() && first != '_' {
+ return None;
+ }
+ let mut end = p + 1 + first.len_utf8();
+ for (i, c) in chars {
+ if !self.word(c) {
+ break;
+ }
+ end = p + 1 + i + c.len_utf8();
+ }
+ return Some(end);
+ } else if tail.starts_with('<') {
+ for (i, c) in tail[1..].char_indices() {
+ if c == '<' {
+ return None;
+ }
+ if c == '>' {
+ return (i > 0).then_some(p + 1 + i + 1);
+ }
+ }
+ }
+ None
+ }
+
+ fn full_reference(&self, s: &str) -> bool {
+ self.reference
+ .find(s)
+ .is_some_and(|m| m.start() == 0 && m.end() == s.len())
+ }
+
+ fn add(
+ &self,
+ hits: &mut Vec<Hit>,
+ s: &str,
+ start: usize,
+ end: usize,
+ key: &str,
+ structured: bool,
+ ) -> Result<(), String> {
+ let value = &s[start..end];
+ if value.is_empty()
+ || (!structured && (value == "|" || value == ">"))
+ || self.full_reference(value)
+ || self.env_end(value, 0) == Some(value.len())
+ {
+ return Ok(());
+ }
+ if hits.len() >= 100_000 {
+ return Err("Privacy extraction match limit exceeded".into());
+ }
+ let mut field = String::new();
+ let mut previous = None;
+ for c in key.chars() {
+ if previous.is_some_and(|v: char| v.is_ascii_lowercase() || v.is_ascii_digit())
+ && c.is_ascii_uppercase()
+ {
+ field.push('_');
+ }
+ if c == '-' || c == ' ' {
+ field.push('_');
+ } else {
+ field.extend(c.to_lowercase());
+ }
+ previous = Some(c);
+ }
+ hits.push(Hit { start, end, field });
+ Ok(())
+ }
+
+ fn mask_markdown_markers(&self, s: &str) -> Option<String> {
+ let delimiters: Vec<_> = self.code_delimiter.find_iter(s).collect();
+ // Index equal-length runs once so unmatched inline delimiters stay linear-time.
+ let mut next = vec![None; delimiters.len()];
+ let mut following = HashMap::new();
+ for (i, delimiter) in delimiters.iter().enumerate().rev() {
+ let key = (delimiter.as_str().as_bytes()[0], delimiter.len());
+ next[i] = following.insert(key, i);
+ }
+ let mut masked = None;
+ let mut cursor = 0;
+ let mut i = 0;
+ while i < delimiters.len() {
+ let open = delimiters[i];
+ let marker = open.as_str().as_bytes()[0];
+ let fenced = open.len() >= 3
+ && fence_line_start(s, open.start())
+ && (marker != b'`' || !s[open.end()..].split('\n').next().unwrap().contains('`'));
+ let close = if fenced {
+ (i + 1..delimiters.len()).find(|&j| {
+ let m = delimiters[j];
+ m.as_str().as_bytes()[0] == marker
+ && m.len() >= open.len()
+ && fence_line_start(s, m.start())
+ && s[m.end()..].split('\n').next().unwrap().trim().is_empty()
+ })
+ } else if marker == b'`' {
+ next[i]
+ } else {
+ None
+ };
+ if close.is_none() && !fenced {
+ i += 1;
+ continue;
+ }
+ self.mask_bold_markers(s, cursor, open.start(), &mut masked);
+ let bytes = masked.get_or_insert_with(|| s.as_bytes().to_vec());
+ bytes[open.start()..open.end()].fill(b' ');
+ cursor = if let Some(j) = close {
+ let end = delimiters[j];
+ bytes[end.start()..end.end()].fill(b' ');
+ i = j + 1;
+ end.end()
+ } else {
+ i = delimiters.len();
+ s.len()
+ };
+ }
+ self.mask_bold_markers(s, cursor, s.len(), &mut masked);
+ masked.map(|bytes| String::from_utf8(bytes).expect("ASCII replacement preserves UTF-8"))
+ }
+
+ fn mask_bold_markers(&self, s: &str, start: usize, end: usize, masked: &mut Option<Vec<u8>>) {
+ // Emphasis inside code is literal; only scan the gaps between code regions.
+ for cap in self.bold.captures_iter(&s[start..end]) {
+ let text = cap.name("text").unwrap();
+ let bytes = masked.get_or_insert_with(|| s.as_bytes().to_vec());
+ bytes[start + text.start() - 2..start + text.start()].fill(b' ');
+ bytes[start + text.end()..start + text.end() + 2].fill(b' ');
+ }
+ }
+
+ fn value_span(&self, s: &str, mut start: usize) -> (usize, usize) {
+ if s[start..].starts_with("${") {
+ if let Some(end) = self.env_end(s, start) {
+ return (start, end);
+ }
+ }
+ let mut end = start;
+ if let Some(quote @ ('\'' | '"')) = char_at(s, start) {
+ start += 1;
+ end = start;
+ while let Some(c) = char_at(s, end) {
+ if c == '\\' {
+ end = advance(s, end, 2);
+ } else if c == quote {
+ break;
+ } else {
+ end += c.len_utf8();
+ }
+ }
+ } else {
+ while let Some(c) = char_at(s, end) {
+ if space(c) || ",;,;\"'<>}{]".contains(c) {
+ break;
+ }
+ if c == '[' {
+ match self.bracket.find_at(s, end) {
+ Some(m) if m.start() == end => end = m.end(),
+ _ => break,
+ }
+ } else {
+ end += c.len_utf8();
+ }
+ }
+ }
+ (start, end)
+ }
+
+ fn shell_span(&self, s: &str, start: usize) -> (usize, usize) {
+ let encoded = s[start..].starts_with("\\\"");
+ let mut quote = if encoded { Some('"') } else { None };
+ let width = if encoded { 2 } else { 1 };
+ let mut end = start + if encoded { 2 } else { 0 };
+ let mut first_quote_end = None;
+ while let Some(c) = char_at(s, end) {
+ if encoded && c == '\\' && quote != Some('\'') {
+ let mut run = end + 1;
+ while char_at(s, run) == Some('\\') {
+ run += 1;
+ }
+ if run == end + 1 && char_at(s, run) == Some('"') {
+ if quote.is_some() {
+ quote = None;
+ if first_quote_end.is_none() {
+ first_quote_end = Some(end);
+ }
+ } else {
+ quote = Some('"');
+ }
+ end = run + 1;
+ } else {
+ end = advance(s, run, 1);
+ }
+ } else if c == '\\' && quote != Some('\'') {
+ end = advance(s, end, 2);
+ } else if let Some(q) = quote {
+ if c == q && (!encoded || q == '\'') {
+ quote = None;
+ if first_quote_end.is_none() {
+ first_quote_end = Some(end);
+ }
+ }
+ end += c.len_utf8();
+ } else if c == '\'' || c == '"' {
+ if encoded && c == '"' {
+ break;
+ }
+ quote = Some(c);
+ end += 1;
+ } else if space(c) || ";&|()<>".contains(c) {
+ break;
+ } else {
+ end += c.len_utf8();
+ }
+ }
+ if start < end
+ && (encoded || matches!(char_at(s, start), Some('\'' | '"')))
+ && first_quote_end == end.checked_sub(width)
+ {
+ (start + width, end - width)
+ } else {
+ (start, end)
+ }
+ }
+
+ fn scheme_end(&self, s: &str, pos: usize, end: usize) -> Option<usize> {
+ if pos > 0 && self.word(s[..pos].chars().next_back()?) {
+ return None;
+ }
+ self.scheme
+ .find_at(&s[..end], pos)
+ .filter(|m| m.start() == pos)
+ .map(|m| m.end())
+ }
+
+ /// Return disjoint credential spans in Unicode character coordinates.
+ pub fn extract(
+ &self,
+ s: &str,
+ field_name: Option<&str>,
+ ) -> Result<Vec<(usize, usize, String)>, String> {
+ if s.len() > 4 * 1024 * 1024 && s.chars().count() > 4 * 1024 * 1024 {
+ return Err("Privacy extraction text limit exceeded".into());
+ }
+ let mut hits = Vec::new();
+ if let Some(field) = field_name.filter(|v| self.is_sensitive_key(v)) {
+ let mut start = 0;
+ if matches!(
+ normalize_key(&field.to_lowercase()).as_str(),
+ "authorization" | "proxyauthorization"
+ ) {
+ start = self.scheme_end(s, 0, s.len()).unwrap_or(0);
+ }
+ self.add(&mut hits, s, start, s.len(), field, true)?;
+ return Ok(to_char_offsets(s, hits));
+ }
+ // Replace Markdown delimiters with whitespace, retaining original offsets and values.
+ let source = s;
+ let scan_text = self.mask_markdown_markers(s);
+ let s = scan_text.as_deref().unwrap_or(s);
+ if s.contains(['=', ':', ':']) {
+ let mut cursor = 0;
+ let mut covered = 0;
+ while cursor < s.len() {
+ let Some(cap) = self.assignment.captures_at(s, cursor) else {
+ break;
+ };
+ let m = cap.get(0).unwrap();
+ if !self.boundary(s, m.start()) {
+ cursor = advance(s, m.start(), 1);
+ continue;
+ }
+ cursor = m.end();
+ let key = cap.name("key").unwrap().as_str();
+ if m.start() < covered || !self.is_sensitive_key(key) {
+ continue;
+ }
+ let start = m.end();
+ let auth_start = start + usize::from(matches!(char_at(s, start), Some('\'' | '"')));
+ let start = if matches!(
+ normalize_key(&key.to_lowercase()).as_str(),
+ "authorization" | "proxyauthorization"
+ ) {
+ self.scheme_end(s, auth_start, s.len()).unwrap_or(start)
+ } else {
+ start
+ };
+ let (start, end) = self.value_span(s, start);
+ self.add(&mut hits, source, start, end, key, false)?;
+ covered = end;
+ }
+ }
+ if s.contains("--") || s.contains("-u") || s.contains("-U") {
+ let mut cursor = 0;
+ let mut covered = 0;
+ while cursor < s.len() {
+ let Some(cap) = self.cli.captures_at(s, cursor) else {
+ break;
+ };
+ let m = cap.get(0).unwrap();
+ if !self.boundary(s, m.start()) {
+ cursor = advance(s, m.start(), 1);
+ continue;
+ }
+ cursor = m.end();
+ if cap.name("short").is_some() && m.end() == m.start() + 2 {
+ if char_at(s, m.end()).map_or(true, |c| space(c) || c == '=') {
+ continue;
+ }
+ }
+ if m.start() < covered {
+ continue;
+ }
+ let mut key = cap.name("key").map_or("user", |v| v.as_str());
+ let normalized = normalize_key(&key.to_lowercase());
+ let combined = normalized == "user" || normalized == "proxyuser";
+ if normalized == "oauth2bearer" {
+ key = "access_token";
+ }
+ if !combined && !self.is_sensitive_key(key) {
+ continue;
+ }
+ let mut start = m.end();
+ loop {
+ let count = if s[start..].starts_with("\\\r\n") {
+ 3
+ } else if s[start..].starts_with("\\\n") {
+ 2
+ } else {
+ break;
+ };
+ start += count;
+ while matches!(char_at(s, start), Some(' ' | '\t')) {
+ start += 1;
+ }
+ }
+ if s[start..].starts_with("--") {
+ continue;
+ }
+ let (mut start, end) = self.shell_span(s, start);
+ if end > start && (!combined || s[start..end].contains(':')) {
+ covered = end;
+ if normalized == "authorization" || normalized == "proxyauthorization" {
+ start = self.scheme_end(s, start, end).unwrap_or(start);
+ }
+ self.add(
+ &mut hits,
+ source,
+ start,
+ end,
+ if combined { "credential" } else { key },
+ false,
+ )?;
+ }
+ }
+ }
+ if self.cfg.token_hints.iter().any(|h| s.contains(h)) {
+ let mut cursor = 0;
+ while cursor < s.len() {
+ let Some(m) = self.token.find_at(s, cursor) else {
+ break;
+ };
+ if !self.boundary(s, m.start()) {
+ cursor = advance(s, m.start(), 1);
+ continue;
+ }
+ cursor = m.end();
+ if (m.as_str().starts_with("AKIA") || m.as_str().starts_with("ASIA"))
+ && char_at(s, m.end()).is_some_and(token_char)
+ {
+ continue;
+ }
+ self.add(&mut hits, source, m.start(), m.end(), "credential", false)?;
+ }
+ }
+ if s.contains(['b', 'B']) {
+ let mut cursor = 0;
+ while cursor < s.len() {
+ let Some(cap) = self.auth.captures_at(s, cursor) else {
+ break;
+ };
+ let m = cap.get(0).unwrap();
+ if m.start() > 0 && self.word(s[..m.start()].chars().next_back().unwrap()) {
+ cursor = advance(s, m.start(), 1);
+ continue;
+ }
+ cursor = m.end();
+ let value = cap.name("value").unwrap();
+ self.add(
+ &mut hits,
+ source,
+ value.start(),
+ value.end(),
+ "authorization",
+ false,
+ )?;
+ }
+ }
+ let refs: Vec<_> = self
+ .reference
+ .find_iter(s)
+ .map(|m| (m.start(), m.end()))
+ .collect();
+ let mut r = 0;
+ let mut merged: Vec<Hit> = Vec::new();
+ hits.sort_by_key(|h| h.start);
+ for h in hits {
+ while r < refs.len() && refs[r].1 <= h.start {
+ r += 1;
+ }
+ if r < refs.len() && refs[r].0 <= h.start && h.end <= refs[r].1 {
+ continue;
+ }
+ if let Some(last) = merged.last_mut() {
+ if h.start < last.end {
+ last.end = last.end.max(h.end);
+ continue;
+ }
+ }
+ merged.push(h);
+ }
+ Ok(to_char_offsets(source, merged))
+ }
+}
+
+fn fence_line_start(s: &str, pos: usize) -> bool {
+ let mut prefix = s[..pos].bytes().rev();
+ for _ in 0..3 {
+ match prefix.next() {
+ None | Some(b'\n') => return true,
+ Some(b' ') => (),
+ _ => return false,
+ }
+ }
+ matches!(prefix.next(), None | Some(b'\n'))
+}
+
+fn normalize_key(s: &str) -> String {
+ s.chars()
+ .filter(|c| !matches!(c, '-' | '_' | ' '))
+ .collect()
+}
+fn space(c: char) -> bool {
+ c.is_whitespace() || matches!(c, '\u{1c}'..='\u{1f}')
+}
+fn token_char(c: char) -> bool {
+ c.is_ascii_alphanumeric() || "_./+=~-".contains(c)
+}
+fn char_at(s: &str, p: usize) -> Option<char> {
+ s.get(p..)?.chars().next()
+}
+fn advance(s: &str, mut p: usize, n: usize) -> usize {
+ for _ in 0..n {
+ if let Some(c) = char_at(s, p) {
+ p += c.len_utf8();
+ }
+ }
+ p
+}
+fn to_char_offsets(s: &str, hits: Vec<Hit>) -> Vec<(usize, usize, String)> {
+ if s.is_ascii() {
+ return hits
+ .into_iter()
+ .map(|h| (h.start, h.end, h.field))
+ .collect();
+ }
+ let mut byte = 0;
+ let mut count = 0;
+ let mut out = Vec::with_capacity(hits.len());
+ for h in hits {
+ count += s[byte..h.start].chars().count();
+ let start = count;
+ count += s[h.start..h.end].chars().count();
+ byte = h.end;
+ out.push((start, count, h.field));
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn basic_requires_authentication_context() {
+ let extractor = PrivacyExtractor::new().unwrap();
+ let text = "Basic usage; Authorization: Basic demo-secret";
+ let chars: Vec<_> = text.chars().collect();
+ let values: Vec<String> = extractor
+ .extract(text, None)
+ .unwrap()
+ .iter()
+ .map(|(start, end, _)| chars[*start..*end].iter().collect())
+ .collect();
+ assert_eq!(values, ["demo-secret"]);
+ assert_eq!(
+ extractor
+ .extract("Basic demo-secret", Some("Authorization"))
+ .unwrap(),
+ vec![(6, 17, "authorization".to_owned())]
+ );
+ }
+
+ #[test]
+ fn unicode_offsets_and_overlaps_cover_complete_credentials() {
+ let extractor = PrivacyExtractor::new().unwrap();
+ let text = "前缀 password='中文密码' Authorization: Bearer sk-abcdefghijklmnopqrstuv";
+ let hits = extractor.extract(text, None).unwrap();
+ let chars: Vec<_> = text.chars().collect();
+ let values: Vec<String> = hits
+ .iter()
+ .map(|(s, e, _)| chars[*s..*e].iter().collect())
+ .collect();
+ assert_eq!(values, ["中文密码", "sk-abcdefghijklmnopqrstuv"]);
+ }
+
+ #[test]
+ fn references_and_environment_placeholders_are_not_new_credentials() {
+ let extractor = PrivacyExtractor::new().unwrap();
+ let text = "password=${PASSWORD} {{ov_privacy:alice:viking://~/privacy/session/sk-abcdefghijklmnopqrstuv#/values/pat}}";
+ assert!(extractor.extract(text, None).unwrap().is_empty());
+ for value in ["${PASSWORD}", "$PASSWORD中", "$PASSWORD²", "$PASSWORD¼"] {
+ assert!(extractor
+ .extract(value, Some("password"))
+ .unwrap()
+ .is_empty());
+ }
+ // A combining mark ends the environment name and leaves a literal value.
+ assert_eq!(
+ extractor
+ .extract("$PASSWORD\u{0345}", Some("password"))
+ .unwrap(),
+ vec![(0, 10, "password".to_owned())]
+ );
+ }
+
+ #[test]
+ fn markdown_delimiters_preserve_value_boundaries_and_literal_symbols() {
+ let extractor = PrivacyExtractor::new().unwrap();
+ for (text, expected) in [
+ ("**API_KEY=secret-value**", "secret-value"),
+ ("1. **API_KEY=secret-value**.", "secret-value"),
+ ("password=**secret-value**", "secret-value"),
+ ("**Authorization: Bearer secret-value**", "secret-value"),
+ ("**sk-abcdefghijklmnopqrstuv**", "sk-abcdefghijklmnopqrstuv"),
+ ("password=secret**", "secret**"),
+ ("password=ab**cd", "ab**cd"),
+ ("password=***", "***"),
+ ("**password='secret**'**", "secret**"),
+ ("password='**secret**'", "**secret**"),
+ ("`API_KEY=secret-value`", "secret-value"),
+ ("password=`secret-value`", "secret-value"),
+ ("``API_KEY=secret-value``", "secret-value"),
+ ("**`API_KEY=secret-value`**", "secret-value"),
+ ("**API_KEY=`secret-value`**", "secret-value"),
+ ("`password=**secret**`", "**secret**"),
+ ("``password=has`tick``", "has`tick"),
+ ("````password=has```ticks````", "has```ticks"),
+ ("`Authorization: Bearer secret-value`", "secret-value"),
+ ("`--api-key secret-value`", "secret-value"),
+ ("``--password='secret`**'``", "secret`**"),
+ ("password='literal`tick`**'", "literal`tick`**"),
+ ("password=unpaired`", "unpaired`"),
+ ("`unclosed password=secret-value", "secret-value"),
+ ("`password='**secret**'`", "**secret**"),
+ ("```\npassword=**secret**\n```", "**secret**"),
+ ("```sh\npassword=**secret**\n````", "**secret**"),
+ ("~~~sh\npassword=**secret**\n~~~~", "**secret**"),
+ ("```sh\npassword=**secret**", "**secret**"),
+ ("~~~sh\npassword=**secret**", "**secret**"),
+ ("**heading** password=secret**", "secret**"),
+ ("中文 **password=密码**", "密码"),
+ ("中文 `password=密码`。", "密码"),
+ ] {
+ let chars: Vec<_> = text.chars().collect();
+ let values: Vec<String> = extractor
+ .extract(text, None)
+ .unwrap()
+ .iter()
+ .map(|(s, e, _)| chars[*s..*e].iter().collect())
+ .collect();
+ assert_eq!(values, [expected], "{text}");
+ }
+ assert_eq!(
+ extractor.extract("**secret**", Some("password")).unwrap(),
+ vec![(0, 10, "password".to_owned())]
+ );
+ let text = "`password=one` **password=two** ``password=three`tick`` password='four`**'";
+ let chars: Vec<_> = text.chars().collect();
+ let values: Vec<String> = extractor
+ .extract(text, None)
+ .unwrap()
+ .iter()
+ .map(|(s, e, _)| chars[*s..*e].iter().collect())
+ .collect();
+ assert_eq!(values, ["one", "two", "three`tick", "four`**"]);
+ }
+
+ #[test]
+ fn unicode_categories_preserve_credential_boundaries() {
+ let extractor = PrivacyExtractor::new().unwrap();
+ // Letters, numbers and underscores continue identifiers.
+ for prefix in ['A', '9', '_', '中', '²', '¼'] {
+ for suffix in ["sk-abcdefghijklmnopqrstuv", "Bearer secret-value"] {
+ let text = format!("{prefix}{suffix}");
+ assert!(extractor.extract(&text, None).unwrap().is_empty(), "{text}");
+ }
+ }
+ // Combining marks, other connectors and format characters form boundaries.
+ for prefix in ['\u{0345}', '\u{0363}', '\u{203f}', '\u{200c}', '🙂'] {
+ let text = format!("{prefix}password=secret-value");
+ assert_eq!(
+ extractor.extract(&text, None).unwrap(),
+ vec![(10, 22, "password".to_owned())]
+ );
+ }
+ }
+}
diff --git a/crates/ragfs/src/privacy_extractor_rules.json b/crates/ragfs/src/privacy_extractor_rules.json
new file mode 100644
index 000000000..f4367f74d
--- /dev/null
+++ b/crates/ragfs/src/privacy_extractor_rules.json
@@ -0,0 +1,12 @@
+{
+ "normalized_names": ["accesskey", "accesskeyid", "accesskeysecret", "accesstoken", "ak", "anthropicaccesskey", "anthropicaccesskeyid", "anthropicaccesskeysecret", "anthropicaccesstoken", "anthropicak", "anthropicapikey", "anthropicappsecret", "anthropicauthorization", "anthropicauthtoken", "anthropicbottoken", "anthropicclientsecret", "anthropiccredential", "anthropiccredentials", "anthropicpasswd", "anthropicpassword", "anthropicprivatekey", "anthropicproxyauthorization", "anthropicpwd", "anthropicrefreshtoken", "anthropicsecret", "anthropicsecretaccesskey", "anthropicsecretkey", "anthropicsecuritytoken", "anthropicsessiontoken", "anthropicsigningkey", "anthropicsigningsecret", "anthropicsk", "anthropictoken", "anthropicwebhooksecret", "anthropicxapikey", "apikey", "appsecret", "authorization", "authtoken", "awsaccesskey", "awsaccesskeyid", "awsaccesskeysecret", "awsaccesstoken", "awsak", "awsapikey", "awsappsecret", "awsauthorization", "awsauthtoken", "awsbottoken", "awsclientsecret", "awscredential", "awscredentials", "awspasswd", "awspassword", "awsprivatekey", "awsproxyauthorization", "awspwd", "awsrefreshtoken", "awssecret", "awssecretaccesskey", "awssecretkey", "awssecuritytoken", "awssessiontoken", "awssigningkey", "awssigningsecret", "awssk", "awstoken", "awswebhooksecret", "awsxapikey", "bottoken", "clientsecret", "credential", "credentials", "openaiaccesskey", "openaiaccesskeyid", "openaiaccesskeysecret", "openaiaccesstoken", "openaiak", "openaiapikey", "openaiappsecret", "openaiauthorization", "openaiauthtoken", "openaibottoken", "openaiclientsecret", "openaicredential", "openaicredentials", "openaipasswd", "openaipassword", "openaiprivatekey", "openaiproxyauthorization", "openaipwd", "openairefreshtoken", "openaisecret", "openaisecretaccesskey", "openaisecretkey", "openaisecuritytoken", "openaisessiontoken", "openaisigningkey", "openaisigningsecret", "openaisk", "openaitoken", "openaiwebhooksecret", "openaixapikey", "openvikingaccesskey", "openvikingaccesskeyid", "openvikingaccesskeysecret", "openvikingaccesstoken", "openvikingak", "openvikingapikey", "openvikingappsecret", "openvikingauthorization", "openvikingauthtoken", "openvikingbottoken", "openvikingclientsecret", "openvikingcredential", "openvikingcredentials", "openvikingpasswd", "openvikingpassword", "openvikingprivatekey", "openvikingproxyauthorization", "openvikingpwd", "openvikingrefreshtoken", "openvikingsecret", "openvikingsecretaccesskey", "openvikingsecretkey", "openvikingsecuritytoken", "openvikingsessiontoken", "openvikingsigningkey", "openvikingsigningsecret", "openvikingsk", "openvikingtoken", "openvikingwebhooksecret", "openvikingxapikey", "passwd", "password", "privatekey", "proxyauthorization", "pwd", "refreshtoken", "rootaccesskey", "rootaccesskeyid", "rootaccesskeysecret", "rootaccesstoken", "rootak", "rootapikey", "rootappsecret", "rootauthorization", "rootauthtoken", "rootbottoken", "rootclientsecret", "rootcredential", "rootcredentials", "rootpasswd", "rootpassword", "rootprivatekey", "rootproxyauthorization", "rootpwd", "rootrefreshtoken", "rootsecret", "rootsecretaccesskey", "rootsecretkey", "rootsecuritytoken", "rootsessiontoken", "rootsigningkey", "rootsigningsecret", "rootsk", "roottoken", "rootwebhooksecret", "rootxapikey", "secret", "secretaccesskey", "secretkey", "securitytoken", "sessiontoken", "signingkey", "signingsecret", "sk", "token", "volcaccesskey", "volcaccesskeyid", "volcaccesskeysecret", "volcaccesstoken", "volcak", "volcapikey", "volcappsecret", "volcauthorization", "volcauthtoken", "volcbottoken", "volcclientsecret", "volccredential", "volccredentials", "volcengineaccesskey", "volcengineaccesskeyid", "volcengineaccesskeysecret", "volcengineaccesstoken", "volcengineak", "volcengineapikey", "volcengineappsecret", "volcengineauthorization", "volcengineauthtoken", "volcenginebottoken", "volcengineclientsecret", "volcenginecredential", "volcenginecredentials", "volcenginepasswd", "volcenginepassword", "volcengineprivatekey", "volcengineproxyauthorization", "volcenginepwd", "volcenginerefreshtoken", "volcenginesecret", "volcenginesecretaccesskey", "volcenginesecretkey", "volcenginesecuritytoken", "volcenginesessiontoken", "volcenginesigningkey", "volcenginesigningsecret", "volcenginesk", "volcenginetoken", "volcenginewebhooksecret", "volcenginexapikey", "volcpasswd", "volcpassword", "volcprivatekey", "volcproxyauthorization", "volcpwd", "volcrefreshtoken", "volcsecret", "volcsecretaccesskey", "volcsecretkey", "volcsecuritytoken", "volcsessiontoken", "volcsigningkey", "volcsigningsecret", "volcsk", "volctoken", "volcwebhooksecret", "volcxapikey", "webhooksecret", "xapikey"],
+ "suffixes": ["_access_key", "_access_key_id", "_access_key_secret", "_access_token", "_api_key", "_app_secret", "_auth_token", "_bot_token", "_client_secret", "_passwd", "_password", "_private_key", "_pwd", "_refresh_token", "_secret_access_key", "_secret_key", "_security_token", "_session_token", "_signing_key", "_signing_secret", "_webhook_secret", "_x_api_key"],
+ "token_hints": ["sk-", "ak-", "ark-", "ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_", "AKLT", "AKTP", "AKIA", "ASIA"],
+ "token_pattern": "(?:sk-(?:proj-|svcacct-|ant-(?:api\\d+-)?)?[A-Za-z0-9_./+=~\\-*]{16,}|(?:ak|ark)-[A-Za-z0-9_./+=~\\-*]{16,}|(?:gh[pousr]_|github_pat_)[A-Za-z0-9_./+=~\\-*]{16,}|(?:AKLT|AKTP)[A-Za-z0-9_./+=~\\-*]{12,}|(?:AKIA|ASIA)[A-Z0-9]{16})",
+ "assignment_pattern": "(?P<key>api[ ]key|secret[ ]key|[A-Za-z_][A-Za-z0-9_-]{0,127})[\\\"']?\\]?[ \\t]*[:=:][ \\t]*",
+ "cli_pattern": "(?:--(?P<key>[A-Za-z_][A-Za-z0-9_-]{0,127})(?:[ \\t]*=[ \\t]*|[ \\t]+)|-(?P<short>[uU])[ \\t]*)",
+ "auth_pattern": "(?i)Bearer[ \\t]+(?P<value>(?:\\[[^\\[\\]\\s\\\"',;]+\\]|[A-Za-z0-9_./+=~\\-*])+)",
+ "scheme_pattern": "(?i)(?:Bearer|Basic)[ \\t]+",
+ "bracket_pattern": "\\[[^\\[\\]\\s\\\"',;]+\\]",
+ "reference_pattern": "\\{\\{ov_privacy:[^{}\\r\\n]+\\}\\}"
+}
diff --git a/crates/ragfs/src/privacy_matcher.rs b/crates/ragfs/src/privacy_matcher.rs
index 42654326c..e00dfb201 100644
--- a/crates/ragfs/src/privacy_matcher.rs
+++ b/crates/ragfs/src/privacy_matcher.rs
@@ -5,7 +5,13 @@
//! references; RAGFS owns only automaton construction and text rewriting.
use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind};
+use regex::Regex;
use std::collections::HashSet;
+use std::sync::LazyLock;
+
+static PRIVACY_REFERENCE: LazyLock<Regex> = LazyLock::new(|| {
+ Regex::new(r"\{\{[ \t]*ov_privacy:[^{}\r\n]+\}\}").expect("fixed reference regex")
+});
/// Replacement emitted for one non-overlapping leftmost-longest match.
#[derive(Clone, PartialEq, Eq)]
@@ -29,6 +35,15 @@ pub struct PrivacySanitizeResult {
pub ambiguous_references: Vec<Vec<String>>,
}
+/// Match metadata without a rewritten copy of the input.
+#[derive(Default)]
+pub struct PrivacyMatchResult {
+ /// Non-overlapping replacements in source order, using character offsets.
+ pub replacements: Vec<PrivacyReplacement>,
+ /// Reference candidates for ambiguous values that occurred in the input.
+ pub ambiguous_references: Vec<Vec<String>>,
+}
+
#[derive(Clone)]
enum PatternTarget {
Reference(String),
@@ -109,37 +124,73 @@ impl PrivacyMatcher {
content: &str,
max_replacements: usize,
) -> (PrivacySanitizeResult, bool) {
+ let mut rewritten = String::with_capacity(content.len());
+ let mut cursor = 0;
+ let (result, exceeded) =
+ self.visit_matches_limited(content, max_replacements, |start, end, reference| {
+ rewritten.push_str(&content[cursor..start]);
+ rewritten.push_str(reference);
+ cursor = end;
+ });
+ if exceeded {
+ rewritten = content.to_string();
+ } else {
+ rewritten.push_str(&content[cursor..]);
+ }
+ (
+ PrivacySanitizeResult {
+ content: rewritten,
+ replacements: result.replacements,
+ ambiguous_references: result.ambiguous_references,
+ },
+ exceeded,
+ )
+ }
+
+ /// Find matches without constructing rewritten text.
+ ///
+ /// Exceeding the replacement limit discards all partial metadata, just as
+ /// `sanitize_limited` does.
+ pub fn find_limited(
+ &self,
+ content: &str,
+ max_replacements: usize,
+ ) -> (PrivacyMatchResult, bool) {
+ self.visit_matches_limited(content, max_replacements, |_, _, _| {})
+ }
+
+ fn visit_matches_limited(
+ &self,
+ content: &str,
+ max_replacements: usize,
+ mut on_match: impl FnMut(usize, usize, &str),
+ ) -> (PrivacyMatchResult, bool) {
+ let mut result = PrivacyMatchResult::default();
let Some(matcher) = &self.matcher else {
- return (
- PrivacySanitizeResult {
- content: content.to_string(),
- replacements: Vec::new(),
- ambiguous_references: Vec::new(),
- },
- false,
- );
+ return (result, false);
};
-
- let mut rewritten = String::with_capacity(content.len());
- let mut replacements = Vec::new();
- let mut ambiguous_references = Vec::new();
let mut source_byte_cursor = 0;
let mut source_char_cursor = 0;
+ let mut references = PRIVACY_REFERENCE.find_iter(content).peekable();
for matched in matcher.find_iter(content) {
- if replacements.len() >= max_replacements {
- return (
- PrivacySanitizeResult {
- content: content.to_string(),
- replacements: Vec::new(),
- ambiguous_references: Vec::new(),
- },
- true,
- );
+ while references
+ .peek()
+ .is_some_and(|item| item.end() <= matched.start())
+ {
+ references.next();
+ }
+ if references
+ .peek()
+ .is_some_and(|item| item.start() < matched.end())
+ {
+ continue;
+ }
+ if result.replacements.len() >= max_replacements {
+ return (PrivacyMatchResult::default(), true);
}
let start = matched.start();
let end = matched.end();
- rewritten.push_str(&content[source_byte_cursor..start]);
source_char_cursor += content[source_byte_cursor..start].chars().count();
let char_start = source_char_cursor;
source_char_cursor += content[start..end].chars().count();
@@ -149,32 +200,19 @@ impl PrivacyMatcher {
let reference = match target {
PatternTarget::Reference(reference) => reference.clone(),
PatternTarget::Ambiguous(candidates) => {
- ambiguous_references.push(candidates.clone());
+ result.ambiguous_references.push(candidates.clone());
self.ambiguous_placeholder.clone()
}
};
- rewritten.push_str(&reference);
- replacements.push(PrivacyReplacement {
+ on_match(start, end, &reference);
+ result.replacements.push(PrivacyReplacement {
start: char_start,
end: char_end,
reference,
});
source_byte_cursor = end;
}
- if replacements.is_empty() {
- rewritten.push_str(content);
- } else {
- rewritten.push_str(&content[source_byte_cursor..]);
- }
-
- (
- PrivacySanitizeResult {
- content: rewritten,
- replacements,
- ambiguous_references,
- },
- false,
- )
+ (result, false)
}
}
@@ -199,52 +237,59 @@ mod tests {
}
#[test]
- fn uses_leftmost_longest_and_unicode_character_offsets() {
+ fn registered_values_preserve_references_and_report_unicode_spans() {
+ let reference = "{{ov_privacy:default:viking://~/privacy/session/demo#/values/key}}";
let matcher = matcher(vec![
("秘密", vec!["short"]),
("秘密值", vec!["long"]),
- ("token", vec!["token-ref"]),
+ ("session", vec!["ref-b", "ref-a", "ref-a"]),
+ ("default", vec!["owner-ref"]),
]);
- let result = matcher.sanitize("前缀秘密值 token");
- assert_eq!(result.content, "前缀long token-ref");
- assert_eq!(result.replacements.len(), 2);
+ let input = format!("🙂秘密值 {reference} session default");
+ let (found, exceeded) = matcher.find_limited(&input, 3);
+ assert!(!exceeded);
+ let spans: Vec<_> = found
+ .replacements
+ .iter()
+ .map(|hit| (hit.start, hit.end, hit.reference.as_str()))
+ .collect();
+ let end = input.chars().count();
assert_eq!(
- (result.replacements[0].start, result.replacements[0].end),
- (2, 5)
+ spans,
+ vec![
+ (1, 4, "long"),
+ (end - 15, end - 8, "{{ov_privacy:ambiguous}}"),
+ (end - 7, end, "owner-ref"),
+ ]
);
+ assert_eq!(found.ambiguous_references, vec![vec!["ref-a", "ref-b"]]);
assert_eq!(
- (result.replacements[1].start, result.replacements[1].end),
- (6, 11)
+ matcher.sanitize(&input).content,
+ format!("🙂long {reference} {{{{ov_privacy:ambiguous}}}} owner-ref")
);
}
#[test]
- fn reports_ambiguity_without_exposing_pattern() {
- let matcher = matcher(vec![("secret", vec!["ref-b", "ref-a", "ref-a"])]);
- let result = matcher.sanitize("x secret y");
- assert_eq!(result.content, "x {{ov_privacy:ambiguous}} y");
- assert_eq!(result.ambiguous_references, vec![vec!["ref-a", "ref-b"]]);
- }
-
- #[test]
- fn empty_catalog_is_a_noop() {
- let matcher = PrivacyMatcher::new(Vec::new(), "ambiguous").unwrap();
- let result = matcher.sanitize("unchanged");
- assert_eq!(result.content, "unchanged");
- assert!(result.replacements.is_empty());
- }
-
- #[test]
- fn limited_scan_stops_without_returning_partial_rewrites() {
- let matcher = matcher(vec![("secret", vec!["ref"])]);
- let (result, limit_exceeded) = matcher.sanitize_limited("secret secret secret", 2);
- assert!(limit_exceeded);
- assert_eq!(result.content, "secret secret secret");
- assert!(result.replacements.is_empty());
-
- let (result, limit_exceeded) = matcher.sanitize_limited("secret secret", 2);
- assert!(!limit_exceeded);
- assert_eq!(result.content, "ref ref");
- assert_eq!(result.replacements.len(), 2);
+ fn match_limits_discard_partial_rewrites_and_metadata() {
+ let matcher = matcher(vec![
+ ("secret", vec!["ref"]),
+ ("shared", vec!["ref-a", "ref-b"]),
+ ]);
+ for (input, expected, exceeded) in [
+ ("shared secret", "{{ov_privacy:ambiguous}} ref", false),
+ ("shared secret secret", "shared secret secret", true),
+ ] {
+ let (rewritten, rewrite_exceeded) = matcher.sanitize_limited(input, 2);
+ let (found, find_exceeded) = matcher.find_limited(input, 2);
+ assert_eq!(rewrite_exceeded, exceeded);
+ assert_eq!(find_exceeded, exceeded);
+ assert_eq!(rewritten.content, expected);
+ assert_eq!(found.replacements.len(), if exceeded { 0 } else { 2 });
+ if exceeded {
+ assert!(rewritten.replacements.is_empty());
+ assert!(rewritten.ambiguous_references.is_empty());
+ assert!(found.ambiguous_references.is_empty());
+ }
+ }
}
}
diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.md
index 1fe91fd97..3fcd6c8f9 100644
--- a/docs/en/api/05-sessions.md
+++ b/docs/en/api/05-sessions.md
@@ -589,7 +589,7 @@ curl --get http://localhost:1933/api/v1/sessions/session-id/tool-results \
### read_tool_result()
-Read one externalized tool result by Unicode character range.
+Read one externalized tool result by Unicode character range. The returned content may contain placeholders for sensitive values. To restore them, read the corresponding file through the [Content API](12-content.md).
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
@@ -927,7 +927,7 @@ If the archive does not exist, is incomplete, or does not belong to the session,
#### 1. API Implementation Introduction
-Delete the session directory, including messages, archives, and session audit records. Long-term memories already extracted into user or Peer memory directories remain; locate and delete those URIs separately when needed. This endpoint has no automatic undo.
+Delete the session directory, including messages, archives, and session audit records. Long-term memories already extracted into user or Peer memory directories remain; locate and delete those URIs separately when needed. This endpoint has no automatic undo. The corresponding Privacy config (`category=session`, `target_key=session_id`) is retained.
**Code Entries:**
- `openviking/server/routers/sessions.py:delete_session()` - HTTP route
diff --git a/docs/en/api/10-privacy.md b/docs/en/api/10-privacy.md
index 02a6215f3..0730648f8 100644
--- a/docs/en/api/10-privacy.md
+++ b/docs/en/api/10-privacy.md
@@ -1,8 +1,6 @@
# Privacy Configs
-Privacy configs manage sensitive values by `category + target_key` (for example, a skill's `api_key` and `base_url`).
-
-Changed values create a version snapshot. You can query history and switch the active version. Submitting the same values as the current version does not create a new version.
+Privacy configs manage sensitive values in Skills and Sessions (such as `api_key` and `token`) by `category + target_key` in the current user's space. Changed values create a version snapshot. You can query history and switch the active version. Submitting the same values as the current version does not create a new version.
These examples use the current user’s API key. In trusted mode, supply the identity headers required by your deployment. Value-reading endpoints and CLI commands return stored values; tree and field-metadata endpoints omit them. `***` below is an example placeholder, not automatic redaction.
@@ -33,10 +31,10 @@ Activating a version changes only the values stored in OpenViking. It does not r
## Common Use Cases
-- Store sensitive settings for a skill
+- Store sensitive settings for a Skill or Session
- Rotate keys by writing a new version
- Roll back to an old version
-- Restore placeholders in skill content at read time
+- Restore values from placeholders when reading Skill or Session content
---
@@ -104,7 +102,8 @@ The server applies the same validation to HTTP, CLI, Embedded, and internal writ
| Item | Limit |
|------|------|
| `category` / `target_key` | Non-empty, at most 255 ASCII characters; only letters, digits, `_`, `-`, `.`, and `@`; `.` and `..` are forbidden and at most one `@` is allowed |
-| Top-level values fields | At most 128 |
+| Session `target_key` | Use the Session ID when it meets the limits above; otherwise use `_` followed by the first 24 hexadecimal characters of its SHA-256 hash (the original Session ID is automatically recorded in `labels.session_id`) |
+| Top-level values fields | At most 1024 for `category=session`; at most 128 for other categories |
| Field name | Non-empty, at most 255 UTF-8 bytes, no control characters |
| Individual string | At most 64 KiB UTF-8 |
| Serialized values | At most 1 MiB |
@@ -138,10 +137,12 @@ curl -X GET http://localhost:1933/api/v1/privacy-configs \
```json
{
"status": "ok",
- "result": ["skill"]
+ "result": ["session", "skill"]
}
```
+Only categories with stored configs are returned; a Session with no extracted values does not create a privacy config.
+
---
### list_privacy_tree()
@@ -571,6 +572,7 @@ curl -X POST "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-se
# Categories and targets
ov privacy categories
ov privacy list skill
+ov privacy list session
# Tree of current targets and fields, without values
ov privacy tree
@@ -626,5 +628,7 @@ ov privacy scan --uri viking://~/resources/project-a --fix --node-limit 500
## Related Documentation
- [Skills](04-skills.md) - Skill write/read APIs
+- [Sessions](05-sessions.md) - Session creation and privacy config
+- [Privacy Configs](../concepts/13-privacy.md) - Sensitive value extraction and restore
- [File System](03-filesystem.md) - `read`/`write`/`ls`
- [System](07-system.md) - System status and observability
diff --git a/docs/en/api/12-content.md b/docs/en/api/12-content.md
index a50eb3220..790558f90 100644
--- a/docs/en/api/12-content.md
+++ b/docs/en/api/12-content.md
@@ -144,14 +144,14 @@ Read the complete text of an L0, L1, or L2 file.
| uri | str | Yes | - | Viking URI (e.g. `viking://resources/docs/api.md`) or a 32-character hex vector record `id` (returned by `stat()`) |
| offset | int | No | 0 | Starting line number (0-indexed) |
| limit | int | No | -1 | Number of lines to read, `-1` means read to end |
-| raw | bool | No | false | Return raw stored content without memory-field cleanup. In Python, use `client.read_raw(uri)` to read this form. |
+| raw | bool | No | false | Skip default sanitization and MEMORY_FIELDS cleanup, and attempt placeholder restoration. In Python, use `client.read_raw(uri)`. |
**Notes**
- `read()` accepts file URIs only. Passing an existing directory URI returns `INVALID_ARGUMENT` (`400`), not `NOT_FOUND`. This error carries a structured `details` payload — `details.expected` is `"file"`, `details.actual` is `"directory"`, and `details.resource` is the offending URI (present on the HTTP path) — so clients can detect a file-vs-directory mismatch programmatically (for example, fall back to `list`) instead of string-matching the message.
- Instead of a Viking URI, you may pass the 32-character hex `id` returned by `stat()` for a file. The server looks up the URI via the vector index and applies the same permission checks. Because indexing is asynchronous, a newly returned ID might not be resolvable immediately; lookup also fails if the corresponding vector record has been deleted. In both cases, the server returns `NOT_FOUND` and indicates that the data may not have been indexed yet or may have been deleted.
- Public URI parameters accept `resources`, `user`, and `agent` scopes. For session files, use `viking://user/{user_id}/sessions/{session_id}/messages.jsonl` or the backward-compatible `viking://session/{session_id}/messages.jsonl` alias. Internal scopes such as `temp` and `queue` return `INVALID_URI`.
-
+- Sensitive information handling: default reads (`raw=false`) preserve existing placeholders and sanitize remaining registered plaintext values; `raw=true` skips default sanitization and returns the restored content. Restoration affects only the response, not stored files; see [Privacy Configs](../concepts/13-privacy.md).
**Python SDK**
diff --git a/docs/en/concepts/00-overview.md b/docs/en/concepts/00-overview.md
index 2f3c19217..07b101955 100644
--- a/docs/en/concepts/00-overview.md
+++ b/docs/en/concepts/00-overview.md
@@ -28,7 +28,7 @@ When you are ready to build, choose an [application workflow](../workflows/01-ov
| When is processing complete, and how does recovery work? | [Queue State and Completion Semantics](16-queue-lifecycle.md) → [Path Locks and Crash Recovery](09-transaction.md) |
| How do primary and backup writes, reads and observation work? | [Multi-Write Storage](14-multi-write-storage.md) → [Metrics](12-metrics.md) |
| Who can see which content, and how are permissions inherited? | [Multi-Tenant](11-multi-tenant.md) → [Resource Access Control (ACL)](15-acl.md) |
-| How are data encrypted and skill privacy handled? | [Data Encryption](10-encryption.md) → [Privacy Configs and Skill Privacy Extraction/Restore](13-privacy.md) |
+| How does OpenViking encrypt data and protect privacy in Skills and Sessions? | [Data Encryption](10-encryption.md) → [Privacy Configs and Automatic Management](13-privacy.md) |
Configuration and deployment steps live in [Deploy & Operate](../guides/00-overview.md). Concept pages explain behavior and constraints; task guides explain how to configure and verify them, with links between the two.
diff --git a/docs/en/concepts/01-architecture.md b/docs/en/concepts/01-architecture.md
index 29082b396..f35446fdc 100644
--- a/docs/en/concepts/01-architecture.md
+++ b/docs/en/concepts/01-architecture.md
@@ -154,4 +154,4 @@ curl http://localhost:1933/api/v1/search/find \
- [Data Encryption](./10-encryption.md) - At-rest encryption and key architecture
- [Multi-Tenant](./11-multi-tenant.md) - Account, user, and peer isolation model
- [Metrics](./12-metrics.md) - `/metrics` usage and key metric explanations
-- [Privacy Configs and Skill Privacy Extraction/Restore](./13-privacy.md) - Versioning, placeholder extraction, and read-time restore
+- [Privacy Configs and Automatic Management](./13-privacy.md) - Versioning, placeholder extraction, and read-time restore
diff --git a/docs/en/concepts/13-privacy.md b/docs/en/concepts/13-privacy.md
index 7c0cec6f9..967879161 100644
--- a/docs/en/concepts/13-privacy.md
+++ b/docs/en/concepts/13-privacy.md
@@ -1,25 +1,28 @@
-# Privacy Configs and Skill Privacy Extraction/Restore
+# Privacy Configs and Automatic Management
-This page explains OpenViking privacy configs and how they work with skill write-time extraction and read-time restore.
+This page explains OpenViking privacy configs and how they work with skill and session write-time extraction and read-time restore.
## Goal
-Privacy configs separate sensitive values (such as `api_key`, `token`, `base_url`) from skill body content to reduce plaintext storage of recognized values in `SKILL.md`, with version lookup and switching. Extraction relies on a model and replaces only recognized, matched spans; it does not guarantee discovery of every sensitive value.
+Privacy configs separate sensitive values (such as `api_key` and `token`) from content (such as skills and sessions). Automatically detected values are saved in the OpenViking user's privacy configs with version history. Content stores placeholders that can be restored from the active config at read time.
Core goals:
- Auto-extract sensitive values at write time and replace with placeholders
-- Auto-restore values from the active config at read time
+- Auto-restore values at read time according to the content type
- Provide version query, switching, and auditability
---
## Core Objects and Storage Layout
-Privacy configs are keyed by `category + target_key`.
+Privacy configs are keyed by `category + target_key` within the current user's space.
-- `category`: config category (currently skill uses `skill`)
-- `target_key`: target identifier (usually the skill name)
+| Content | `category` | `target_key` |
+|---|---|---|
+| Skill | `skill` | Skill name |
+| Session | `session` | Session ID |
+| Personal credentials | `credential` | For example, `github` or `database` |
Storage layout in user space:
@@ -33,7 +36,7 @@ viking://user/{user_id}/privacy/{category}/{target_key}/
└── ...
```
-`current.json` and `history/version_x.json` are full `values` snapshots.
+`current.json` and `history/version_x.json` contain full privacy value maps (`values`). Session and skill bodies store references to these values (placeholders).
---
@@ -55,20 +58,23 @@ viking://user/{user_id}/privacy/{category}/{target_key}/
---
-## Skill Privacy Extraction (Write Path)
+## Skill Privacy Extraction and Restore
-When adding a skill via `add_skill`, OpenViking runs extraction + placeholderization.
+### Automatic Extraction (Write Path)
+
+When adding a Skill via `add_skill`, sensitive values are extracted and replaced with placeholders.
```
add_skill
-> SkillProcessor._sanitize_skill_privacy
+ -> PrivacySanitizer (protect registered personal credentials)
-> extract_skill_privacy_values (LLM extracts values)
-> placeholderize_skill_content_with_blocks (replace plaintext with placeholders)
-> privacy.upsert(category="skill", target_key=skill_name, values=...)
-> write placeholderized SKILL.md
```
-### Key Points
+#### Key Points
1. **Extraction source**: model returns JSON; `values` is used as privacy key-value pairs.
2. **Content replacement**: matched plaintext is replaced by placeholders:
@@ -80,25 +86,26 @@ add_skill
---
-## Skill Restore on Read (Load Path)
+### Restore on Read (Load Path)
-When reading `SKILL.md`, `FSService.read` attempts placeholder restoration automatically.
+Reads of `SKILL.md` preserve placeholders by default. With explicit `raw=true`, `FSService.read` attempts to restore them.
```
fs.read(uri)
-> get_skill_name_from_uri(uri)
- -> privacy.get_current(category="skill", target_key=skill_name)
- -> restore_skill_content(content, skill_name, current.values)
+ -> restore_skill_content
+ -> privacy.get_current(category, target_key)
+ -> restore references in the content
```
-### URI Matching
+#### URI Matching
Current matching is suffix-based: `/skills/{name}/SKILL.md`, so it supports user-scoped skill paths such as:
- `viking://~/skills/{name}/SKILL.md`
- `viking://user/{user_id}/skills/{name}/SKILL.md`
-### restore Rules
+#### restore Rules
`restore_skill_content` behavior:
@@ -116,17 +123,86 @@ Current matching is suffix-based: `/skills/{name}/SKILL.md`, so it supports user
- `Missing config: ...` (if any)
- `Configured but not referenced in content: ...` (if any)
-> Current implementation only runs restore when a `current` privacy config exists for that skill. If no current config exists, no notice is appended.
+Placeholders that reference the current user's Privacy fields are also restored. References to other users or missing fields remain unchanged.
+
+> Config notices for a skill are appended only when that skill has a `current` config.
---
`read` returns restored values, and extra-config notices also include values. Privacy APIs and historical snapshots can return full values as well. This feature does not redact responses or encrypt storage; see [Storage Encryption](./10-encryption.md) for encryption.
+## Session Privacy Extraction and Restore
+
+### Automatic Extraction (Write Path)
+
+When writing messages to a Session, common credential rules extract sensitive values and replace them with placeholders before tool output externalization and message persistence.
+
+```
+Session.add_messages_async
+ -> extract_and_store_session_privacy
+ -> PrivacySanitizer (protect registered personal credentials)
+ -> PrivacyExtractor (extract new values using rules and replace them with placeholders)
+ -> privacy.insert_values(category="session", target_key=session_id, updates=...)
+ -> externalize tool output
+ -> write placeholderized messages
+```
+
+#### Key Points
+
+1. **Extraction source**: fixed rules identify sensitive values without model calls; the results are used as privacy key-value pairs.
+2. **Coverage**: TextPart text, ContextPart abstracts, and ToolPart input and output. Values under sensitive tool input keys are stored and masked as a whole.
+3. **Content replacement**: sensitive spans in the original content are replaced with placeholders:
+ - Sensitive values belonging to the current Session use the same placeholder format, with the Session ID or its hash value: <code>&#123;&#123;ov_privacy:session:&#123;session_id&#125;:&#123;field_name&#125;&#125;&#125;</code>.
+ - If a sensitive span matches registered personal credentials (`credential`), prefer the uniquely matching field's placeholder, for example <code>&#123;&#123;ov_privacy:alice:viking://~/privacy/credential/github#/values/pat&#125;&#125;</code>.
+4. **Persisted content**: matched spans are saved as placeholders; unmatched content remains unchanged. Newly extracted privacy values are saved in the current Session's config.
+
+---
+
+### Restore on Read (Load Path)
+
+Reads of Session messages or externalized tool output preserve placeholders by default. With explicit `raw=true`, `FSService.read` attempts to restore them.
+
+```
+fs.read(uri)
+ -> get_session_id_from_uri(uri, session_root)
+ -> restore_session_content
+ -> privacy.get_current(category, target_key)
+ -> restore references in the content
+```
+
+#### URI Matching
+
+Restoration is supported for these files under the current user's Session directory:
+
+- `sessions/{session_id}/messages.jsonl`
+- `sessions/{session_id}/history/archive_*/messages.jsonl`
+- `sessions/{session_id}/tool-results/{id}/output.txt`
+
+#### restore Rules
+
+`restore_session_content` behavior:
+
+1. **Placeholder exists in content and privacy value exists and is non-empty**
+
+ -> Replace directly with the corresponding value. Whole-value placeholders in tool input restore the original JSON type.
+
+2. **Placeholder exists in content but privacy value is missing or empty**
+
+ -> Keep the placeholder unchanged.
+
+3. **Placeholder in content refers to another user, or uses <code>&#123;&#123;ov_privacy:session:...&#125;&#125;</code> for another Session**
+
+ -> Keep the placeholder unchanged.
+
+> Restoration affects only the read result, without modifying stored files. References follow the active config: rotating a field or activating another version also changes the value used on the next read of historical messages.
+
+---
+
## Relationship with CLI/API
- Management plane: Privacy API/CLI for versions (query, write, rollback)
-- Content plane: `read` automatically restores placeholders
-- Separation of concerns: content files hold placeholders; privacy service holds sensitive values and versions
+- Content plane: automatically restore placeholders through `read`
+- Separation of concerns: content files hold placeholders; the privacy service holds sensitive values and versions
PrivacySanitizer does not infer sensitivity from field names. String values in the active Privacy catalog participate in automatic content scanning and reference replacement only when they contain at least 6 Unicode characters. Shorter values can still be stored, referenced, and explicitly resolved, but are excluded from global substring replacement to reduce false positives in ordinary text. Python owns catalog loading, reference generation, and cache policy; matcher construction, leftmost-longest matching, and text rewriting run in RAGFS's Rust Aho-Corasick implementation through a reusable PyO3 matcher that releases the GIL while scanning. The matcher catalog is cached per user and process-local revision; local changes invalidate it immediately, and a 3600-second TTL bounds staleness after changes made by another worker or node.
@@ -163,14 +239,15 @@ ov privacy scan --uri viking://~/resources/project-a
- Reduces plaintext sensitive data exposure in skill content
- Version history supports configuration changes after external credential rotation
-- Transparent to callers: `read` returns restored executable skill text
-- Notice block improves troubleshooting when config is incomplete or over-provisioned
+- Transparent to callers: `read` returns restored, executable skill content
+- Notice blocks improve troubleshooting when config is incomplete or over-provisioned
---
## Related Documentation
- [Skills](../api/04-skills.md) - Skill write/read API
+- [Sessions](../api/05-sessions.md) - Session creation and message writes
- [Privacy API](../api/10-privacy.md) - Privacy config endpoints
- [Context Extraction](./06-extraction.md) - Main extraction pipeline
- [Architecture Overview](./01-architecture.md) - Layering and module relationships
diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.md
index 74a1cef2a..1f1cc4a6a 100644
--- a/docs/zh/api/05-sessions.md
+++ b/docs/zh/api/05-sessions.md
@@ -587,7 +587,7 @@ curl --get http://localhost:1933/api/v1/sessions/session-id/tool-results \
### read_tool_result()
-按 Unicode 字符范围读取一个外置工具结果。
+按 Unicode 字符范围读取一个外置工具结果。 此 API 返回的内容中可能含有敏感信息的占位符,若需还原,使用[内容 API](12-content.md) 读取对应文件。
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
@@ -927,7 +927,7 @@ ov session get-session-archive a1b2c3d4 archive_002
#### 1. API 实现介绍
-删除该会话目录,包括消息、归档历史和会话内的审计记录。已经抽取到用户或 Peer 记忆目录的长期记忆不会随之删除;需要删除这些记忆时,单独定位并删除对应 URI。此接口不提供自动撤销。
+删除该会话目录,包括消息、归档历史和会话内的审计记录。已经抽取到用户或 Peer 记忆目录的长期记忆不会随之删除;需要删除这些记忆时,单独定位并删除对应 URI。此接口不提供自动撤销。对应的 Privacy 配置(`category=session`、`target_key=session_id`)会保留。
**代码入口**:
- `openviking/server/routers/sessions.py:delete_session()` - HTTP 路由
diff --git a/docs/zh/api/10-privacy.md b/docs/zh/api/10-privacy.md
index 47b55c07e..91dc2b88d 100644
--- a/docs/zh/api/10-privacy.md
+++ b/docs/zh/api/10-privacy.md
@@ -1,8 +1,6 @@
# 隐私配置
-隐私配置用于按 `category + target_key` 管理敏感字段版本(如 skill 的 `api_key`、`base_url`)。
-
-配置值变化时会生成版本快照,可查询历史版本并切换生效版本。提交与当前版本相同的值不会创建新版本。
+隐私配置在当前用户空间内,按 `category + target_key` 管理技能、会话中的敏感信息(如密钥、凭据等)。配置值变化时会生成版本快照,可查询历史版本并切换生效版本。提交与当前版本相同的值不会创建新版本。
以下示例使用当前用户的 API Key。trusted 模式需补充部署要求的身份头。读取值的接口和 CLI 命令会返回实际值;树总览和字段元数据接口不返回值。下文的 `***` 仅为示例占位符,不表示接口自动脱敏。
@@ -10,10 +8,10 @@
## 典型场景
-- 为某个 skill 保存密钥等敏感配置
+- 为某个 skill 或 session 保存密钥等敏感配置
- 轮换密钥(新版本)
- 回滚到历史版本
-- 在读取 skill 内容时按占位符自动恢复配置值
+- 在读取 skill 或 session 内容时按占位符恢复配置值
---
@@ -84,7 +82,8 @@
| 项目 | 限制 |
|------|------|
| `category` / `target_key` | 非空、最多 255 个 ASCII 字符;仅允许字母、数字、`_`、`-`、`.`、`@`;禁止 `.`、`..`,`@` 最多一个 |
-| values 顶层字段 | 最多 128 个 |
+| Session 的 `target_key` | 当 Session ID 符合上行的限制时,使用 Session ID 作为 `target_key`;否则为 `_` 加 SHA-256 前 24 位十六进制(原始 Session ID 会自动记录在 `labels.session_id`) |
+| values 顶层字段 | `category=session` 最多 1024 个;其他类别最多 128 个 |
| 字段名 | 非空、最多 255 UTF-8 字节、禁止控制字符 |
| 单个字符串值 | 最多 64 KiB UTF-8 |
| values 序列化总量 | 最多 1 MiB |
@@ -138,10 +137,12 @@ curl -X GET http://localhost:1933/api/v1/privacy-configs \
```json
{
"status": "ok",
- "result": ["skill"]
+ "result": ["session", "skill"]
}
```
+只返回已有配置的分类;Session 未提取到原值时,不会创建对应的 Privacy 配置。
+
---
### list_privacy_tree()
@@ -572,6 +573,7 @@ curl -X POST "http://localhost:1933/api/v1/privacy-configs/skill/byted-viking-se
# 分类/目标
ov privacy categories
ov privacy list skill
+ov privacy list session
# 树形盘点当前目标和字段,不显示值
ov privacy tree
@@ -626,5 +628,7 @@ ov privacy scan --uri viking://~/resources/project-a --fix --node-limit 500
## 相关文档
- [技能](04-skills.md) - 技能写入与读取
+- [会话](05-sessions.md) - 会话创建与隐私配置
+- [隐私配置](../concepts/13-privacy.md) - 隐私敏感值的提取与还原机制
- [文件系统](03-filesystem.md) - `read`/`write`/`ls` 等
- [系统](07-system.md) - 服务状态与可观测性
diff --git a/docs/zh/api/12-content.md b/docs/zh/api/12-content.md
index 829fc4879..2bc14bdd6 100644
--- a/docs/zh/api/12-content.md
+++ b/docs/zh/api/12-content.md
@@ -144,14 +144,14 @@ ov overview viking://resources/docs/
| uri | str | 是 | - | Viking URI(如 `viking://resources/docs/api.md`)或 32 字符十六进制向量记录 `id`(由 `stat()` 返回) |
| offset | int | 否 | 0 | 起始行号(0 开始) |
| limit | int | 否 | -1 | 读取的行数,`-1` 表示读到结尾 |
-| raw | bool | 否 | false | 返回未过滤 MEMORY_FIELDS 的原始存储内容;Python 中使用 `client.read_raw(uri)` 读取此格式。 |
+| raw | bool | 否 | false | 跳过默认脱敏和 MEMORY_FIELDS 过滤,并尝试还原占位符;Python 中使用 `client.read_raw(uri)`。 |
**说明**
- `read()` 只接受文件 URI。传入已存在的目录时返回 `INVALID_ARGUMENT`(HTTP `400`)。HTTP 响应的 `details` 包含 `expected: "file"`、`actual: "directory"` 和目标 `resource` URI,客户端可据此改用目录列表接口,无需解析错误消息。
- 除 Viking URI 外,还可以传入 `stat()` 返回的 32 字符十六进制文件 `id`。服务端通过向量索引查找对应 URI 并执行相同的权限校验。由于索引是异步生成的,新返回的 ID 可能暂时无法解析;对应向量记录被删除后,按 ID 查询也会失败。这两种情况下,服务端都会返回 `NOT_FOUND`,并提示数据可能尚未索引或已经删除。
- 公开 URI 参数接受 `resources`、`user` 和 `agent` 作用域。访问 session 文件时,使用 `viking://user/{user_id}/sessions/{session_id}/messages.jsonl`,也可以使用向后兼容的 `viking://session/{session_id}/messages.jsonl` 别名。`temp`、`queue` 等内部作用域会返回 `INVALID_URI`。
-
+- 敏感信息的处理:默认读取(`raw=false`)保留已有占位符,并对残留的已登记明文脱敏;`raw=true` 跳过默认脱敏,返回加载还原后的内容,该还原只影响返回内容,不修改存储文件,详见[隐私配置](../concepts/13-privacy.md)。
**Python SDK**
diff --git a/docs/zh/concepts/00-overview.md b/docs/zh/concepts/00-overview.md
index 533b53ac3..1a9417145 100644
--- a/docs/zh/concepts/00-overview.md
+++ b/docs/zh/concepts/00-overview.md
@@ -28,7 +28,7 @@
| 处理何时结束,失败后如何恢复? | [任务状态](16-queue-lifecycle.md) → [路径锁与崩溃恢复](09-transaction.md) |
| 主备写入、读取和观测有什么语义? | [主备存储](14-multi-write-storage.md) → [指标与 Metrics](12-metrics.md) |
| 谁能看到什么,权限如何继承? | [多租户](11-multi-tenant.md) → [资源访问控制(ACL)](15-acl.md) |
-| 数据如何加密,Skill 隐私如何处理? | [数据加密](10-encryption.md) → [隐私配置与 Skill 隐私提取/加载](13-privacy.md) |
+| 数据如何加密,Skill 和 Session 隐私如何处理? | [数据加密](10-encryption.md) → [隐私配置与自动管理](13-privacy.md) |
配置和部署步骤集中在[部署运维](../guides/00-overview.md)。原理页说明行为与约束,操作指南说明如何设置和验证,两者通过链接连接。
diff --git a/docs/zh/concepts/01-architecture.md b/docs/zh/concepts/01-architecture.md
index cc684c795..ef5c7e84b 100644
--- a/docs/zh/concepts/01-architecture.md
+++ b/docs/zh/concepts/01-architecture.md
@@ -154,4 +154,4 @@ curl http://localhost:1933/api/v1/search/find \
- [数据加密](./10-encryption.md) - 静态数据加密与密钥架构
- [多租户](./11-multi-tenant.md) - account / user / peer 隔离模型
- [指标](./12-metrics.md) - `/metrics` 使用方式与关键指标说明
-- [用户隐私配置](./13-privacy.md) - 隐私版本管理、自动提取Skill隐私配置
+- [用户隐私配置](./13-privacy.md) - 隐私版本管理、自动提取Skill/Session隐私配置
diff --git a/docs/zh/concepts/13-privacy.md b/docs/zh/concepts/13-privacy.md
index 0b680ba28..b5dca8e7d 100644
--- a/docs/zh/concepts/13-privacy.md
+++ b/docs/zh/concepts/13-privacy.md
@@ -1,25 +1,28 @@
-# 隐私配置与 Skill 隐私提取/加载
+# 隐私配置与自动管理
-本文介绍 OpenViking 的隐私配置能力,以及它与 Skill 写入(提取)和读取(加载还原)的协作机制。
+本文介绍 OpenViking 的隐私配置能力,以及它与技能/会话写入(提取)和读取(加载还原)的协作机制。
## 目标
-隐私配置用于把敏感值(如 `api_key`、`token`、`base_url`)从技能正文中分离出来,减少已识别敏感值在 `SKILL.md` 中的明文存储,并支持版本查询和切换。抽取依赖模型,只替换识别并匹配成功的片段,不能保证发现所有敏感信息。
+隐私配置用于把敏感值(如 `api_key`、`token`)从内容(如技能、会话)中分离出来。被自动扫描的敏感信息,保存在 OpenViking 用户空间的隐私配置中并保留版本记录,内容则保存占位符,读取时可根据当前生效配置还原。
核心目标:
-- 写入时自动抽取敏感值并占位符化
-- 读取时按当前生效配置自动还原
+- 写入时自动提取敏感值并占位符化
+- 读取时按内容类型还原
- 支持版本查询、切换与审计
---
## 核心对象与存储结构
-隐私配置按二级键组织:`category + target_key`。
+隐私配置在当前用户空间内按二级键组织:`category + target_key`。
-- `category`:配置类别(当前 Skill 使用 `skill`)
-- `target_key`:目标标识(通常是 skill 名)
+| 内容 | `category` | `target_key` |
+|---|---|---|
+| Skill | `skill` | Skill 名称 |
+| Session | `session` | Session ID |
+| 个人密钥 | `credential` | 如 `github`、`database` |
用户空间下的存储路径:
@@ -33,7 +36,7 @@ viking://user/{user_id}/privacy/{category}/{target_key}/
└── ...
```
-`current.json` 与 `history/version_x.json` 都是完整快照(`values` 整包)。
+`current.json` 与 `history/version_x.json` 都是完整的隐私值字典(`values` 整包)。而 Session 或 Skill 中的正文只会保存这些隐私值的引用(即占位符)。
---
@@ -55,20 +58,23 @@ viking://user/{user_id}/privacy/{category}/{target_key}/
---
-## Skill 隐私提取(写入链路)
+## 技能的隐私提取与读取还原
+
+### 自动提取(写入链路)
当通过 `add_skill` 写入 Skill 时,会走隐私提取与占位符化流程。
```
add_skill
-> SkillProcessor._sanitize_skill_privacy
+ -> PrivacySanitizer(保护已登记的个人密钥)
-> extract_skill_privacy_values (LLM 抽取 values)
-> placeholderize_skill_content_with_blocks (明文替换为占位符)
-> privacy.upsert(category="skill", target_key=skill_name, values=...)
-> 写入占位符化后的 SKILL.md
```
-### 关键点
+#### 关键点
1. **抽取结果来源**:模型返回 JSON,读取 `values` 字段作为隐私键值。
2. **内容替换**:原文中命中的敏感片段会替换为占位符:
@@ -80,25 +86,26 @@ add_skill
---
-## Skill 加载还原(读取链路)
+### 加载还原(读取链路)
-读取 `SKILL.md` 时,`FSService.read` 会尝试自动还原占位符。
+读取 `SKILL.md` 时,默认保留占位符;显式指定 `raw=true` 时,`FSService.read` 会尝试还原占位符。
```
fs.read(uri)
-> get_skill_name_from_uri(uri)
- -> privacy.get_current(category="skill", target_key=skill_name)
- -> restore_skill_content(content, skill_name, current.values)
+ -> restore_skill_content
+ -> privacy.get_current(category, target_key)
+ -> 还原正文中的引用
```
-### URI 匹配
+#### URI 匹配
当前支持通过后缀识别 Skill:`/skills/{name}/SKILL.md`,可兼容 user-scoped skill 路径,例如:
- `viking://~/skills/{name}/SKILL.md`
- `viking://user/{user_id}/skills/{name}/SKILL.md`
-### restore 规则
+#### restore 规则
`restore_skill_content` 的行为如下:
@@ -116,12 +123,81 @@ fs.read(uri)
- `Missing config: ...`(如有)
- `Configured but not referenced in content: ...`(如有)
-> 仅当该 skill 已有 `current` 配置时才会进入 restore。若没有当前配置,不会追加 notice。
+指向当前用户 Privacy 字段的占位符也会按其引用还原;指向其他用户或缺失字段时,保留占位符。
+
+> 仅当该 skill 已有 `current` 配置时,才会追加该技能的配置提示。
---
`read` 返回的是还原后的值;“额外配置”提示也会包含配置值。Privacy API 和历史快照同样可以返回完整值,该功能不等于响应脱敏或存储加密。需要加密存储时,另见[存储加密](./10-encryption.md)。
+## 会话的隐私提取与读取还原
+
+### 自动提取(写入链路)
+
+向 Session 写入消息时,会在工具输出外置和消息落盘前,通过常见的规则,提取敏感值并替换为占位符。
+
+```
+Session.add_messages_async
+ -> extract_and_store_session_privacy
+ -> PrivacySanitizer(保护已登记的个人密钥)
+ -> PrivacyExtractor(规则提取新值并占位符化)
+ -> privacy.insert_values(category="session", target_key=session_id, updates=...)
+ -> 工具输出外置
+ -> 写入占位符化后的消息
+```
+
+#### 关键点
+
+1. **抽取结果来源**:通过固定的常见规则(不调用模型)识别敏感值,将结果作为隐私键值。
+2. **覆盖范围**:处理 TextPart 文本、ContextPart 摘要和 ToolPart 输入、输出。工具输入中,敏感字段对应的值整体保存和遮罩。
+3. **内容替换**:原文中的敏感片段会替换为占位符:
+ - 当前 Session 的敏感值统一使用以下占位符,以 Session ID 或其哈希映射值标识会话:<code>&#123;&#123;ov_privacy:session:&#123;session_id&#125;:&#123;field_name&#125;&#125;&#125;</code>。
+ - 若敏感片段与已登记的个人密钥(credential)匹配,则优先使用唯一匹配字段的占位符,例如 <code>&#123;&#123;ov_privacy:alice:viking://~/privacy/credential/github#/values/pat&#125;&#125;</code>。
+4. **写盘结果**:匹配成功的片段以占位符保存,未匹配内容保持原样。新提取的隐私值保存在当前 Session 的配置中。
+
+---
+
+### 加载还原(读取链路)
+
+读取 Session 消息或外置工具输出时,默认保留占位符;显式指定 `raw=true` 时,`FSService.read` 会尝试还原占位符。
+
+```
+fs.read(uri)
+ -> get_session_id_from_uri(uri, session_root)
+ -> restore_session_content
+ -> privacy.get_current(category, target_key)
+ -> 还原正文中的引用
+```
+
+#### URI 匹配
+
+当前支持还原当前用户 Session 目录下的以下文件:
+
+- `sessions/{session_id}/messages.jsonl`
+- `sessions/{session_id}/history/archive_*/messages.jsonl`
+- `sessions/{session_id}/tool-results/{id}/output.txt`
+
+#### restore 规则
+
+`restore_session_content` 的行为如下:
+
+1. **content 中有占位符,且 privacy value 存在且非空**
+
+ -> 直接替换为对应值;工具输入中的整值占位符按原始 JSON 类型还原。
+
+2. **content 中有占位符,但 privacy value 缺失或为空**
+
+ -> 保留占位符不替换。
+
+3. **content 中的占位符指向其他用户,或使用不属于当前会话的 <code>&#123;&#123;ov_privacy:session:...&#125;&#125;</code>**
+
+ -> 保留占位符不替换。
+
+> 还原只影响读取结果,不修改存储文件。引用跟随当前生效配置,轮换字段值或激活其他版本后,历史消息下次读取时也使用新的当前值。
+
+---
+
## 与 CLI/API 的关系
- 管理面:通过 Privacy API/CLI 管理版本(查询、写入、回滚)
@@ -171,6 +247,7 @@ ov privacy scan --uri viking://~/resources/project-a
## 相关文档
- [技能](../api/04-skills.md) - Skill 写入与读取 API
+- [会话](../api/05-sessions.md) - Session 创建、消息写入
- [隐私配置 API](../api/10-privacy.md) - 隐私配置端点说明
- [上下文提取](./06-extraction.md) - 内容提取主流程
- [架构概述](./01-architecture.md) - 系统分层与模块关系
diff --git a/openviking/privacy/restore.py b/openviking/privacy/restore.py
new file mode 100644
index 000000000..9680855dd
--- /dev/null
+++ b/openviking/privacy/restore.py
@@ -0,0 +1,100 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Resolve Privacy references to the current user's active values."""
+
+import re
+from typing import Any, Literal
+
+from openviking.privacy.models import UserPrivacyConfigVersion
+from openviking.privacy.reference import PrivacyFieldReference, parse_privacy_field_reference
+from openviking.privacy.service import UserPrivacyConfigService
+from openviking.server.identity import RequestContext
+from openviking_cli.exceptions import InvalidArgumentError, NotFoundError, ResourceExhaustedError
+
+_REFERENCE = re.compile(r"\{\{[ \t]*ov_privacy:[^{}\r\n]+\}\}")
+MAX_RESTORE_TARGETS = 1024
+
+
+class PrivacyRestorer:
+ """Collect placeholders once and restore them using their original positions."""
+
+ def __init__(
+ self,
+ privacy: UserPrivacyConfigService,
+ ctx: RequestContext,
+ *,
+ category: Literal["skill", "session"],
+ target_key: str,
+ ):
+ self._privacy = privacy
+ self._ctx = ctx
+ self._category = category
+ self._target_key = target_key
+ field = r"([^}:]+)" if category == "skill" else r"([A-Za-z0-9_-]{8})"
+ self._placeholder = re.compile(
+ r"\{\{ov_privacy:" + category + ":" + re.escape(target_key) + ":" + field + r"\}\}"
+ )
+ self._configs: dict[tuple[str, str], UserPrivacyConfigVersion | None] = {}
+ self._targets: set[tuple[str, str]] = set()
+ self._matches: dict[str, list[re.Match[str]]] = {}
+ self.fields: dict[str, PrivacyFieldReference] = {}
+ self.values: dict[str, Any] = {}
+
+ def collect_text(self, content: str) -> str:
+ """Record matches for later replacement and return the input text."""
+ if content in self._matches:
+ return content
+ matches = self._matches[content] = []
+ for match in _REFERENCE.finditer(content):
+ placeholder = match[0]
+ if placeholder not in self.fields:
+ location = parse_privacy_field_reference(placeholder)
+ if location is None:
+ own = self._placeholder.fullmatch(placeholder)
+ if own is not None:
+ location = PrivacyFieldReference(
+ self._ctx.user.user_id, self._category, self._target_key, own[1]
+ )
+ if location is None or location.owner_user_id != self._ctx.user.user_id:
+ continue
+ self._targets.add((location.category, location.target_key))
+ if len(self._targets) > MAX_RESTORE_TARGETS:
+ raise ResourceExhaustedError("Privacy reference target limit exceeded")
+ self.fields[placeholder] = location
+ matches.append(match)
+ return content
+
+ async def get_current(self, category: str, target_key: str) -> UserPrivacyConfigVersion | None:
+ target = (category, target_key)
+ if target not in self._configs:
+ try:
+ self._configs[target] = await self._privacy.get_current(
+ self._ctx, category, target_key
+ )
+ except (NotFoundError, FileNotFoundError, InvalidArgumentError):
+ self._configs[target] = None
+ return self._configs[target]
+
+ async def load_values(self) -> None:
+ """Load active values for the collected fields."""
+ for placeholder, location in self.fields.items():
+ current = await self.get_current(location.category, location.target_key)
+ if current is None or location.field not in current.values:
+ continue
+ value = current.values[location.field]
+ if value is None or value == "":
+ continue
+ self.values[placeholder] = value
+
+ def restore_text(self, content: str) -> str:
+ """Splice values into original matches without scanning inserted content."""
+ chunks = []
+ start = 0
+ for match in self._matches.get(content, ()):
+ if match[0] in self.values:
+ chunks.extend((content[start : match.start()], str(self.values[match[0]])))
+ start = match.end()
+ if not chunks:
+ return content
+ chunks.append(content[start:])
+ return "".join(chunks)
diff --git a/openviking/privacy/rules.py b/openviking/privacy/rules.py
new file mode 100644
index 000000000..f5547a489
--- /dev/null
+++ b/openviking/privacy/rules.py
@@ -0,0 +1,38 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Python interface to the native fixed-rule PrivacyExtractor."""
+
+from dataclasses import dataclass
+from functools import lru_cache
+
+from openviking.pyagfs import get_privacy_extractor_class
+from openviking_cli.exceptions import InvalidArgumentError
+
+MAX_TEXT_CHARS = 4 * 1024 * 1024
+MAX_MATCHES = 100_000
+
+
+@dataclass(frozen=True)
+class PrivacyMatch:
+ start: int
+ end: int
+ field_name: str
+
+
+@lru_cache(maxsize=1)
+def _extractor():
+ return get_privacy_extractor_class()()
+
+
+def is_sensitive_key(key: str) -> bool:
+ return _extractor().is_sensitive_key(key)
+
+
+def find_privacy_matches(content: str, *, field_name: str | None = None) -> list[PrivacyMatch]:
+ """Discover sensitive spans using Unicode character offsets."""
+ if len(content) > MAX_TEXT_CHARS:
+ raise InvalidArgumentError("Privacy extraction text limit exceeded")
+ try:
+ return [PrivacyMatch(*match) for match in _extractor().extract(content, field_name)]
+ except ValueError as exc:
+ raise InvalidArgumentError(str(exc)) from None
diff --git a/openviking/privacy/sanitizer.py b/openviking/privacy/sanitizer.py
index 91d481127..9ae109960 100644
--- a/openviking/privacy/sanitizer.py
+++ b/openviking/privacy/sanitizer.py
@@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, Any, Callable
from openviking.privacy.reference import build_privacy_field_reference
from openviking.pyagfs import get_privacy_matcher_class
from openviking.server.identity import RequestContext
-from openviking_cli.exceptions import ResourceExhaustedError
+from openviking_cli.exceptions import InvalidArgumentError, ResourceExhaustedError
if TYPE_CHECKING:
from openviking.privacy.service import UserPrivacyConfigService
@@ -68,7 +68,7 @@ class PrivacySanitizer:
self._monotonic_clock = monotonic_clock
matcher_class: Any = get_privacy_matcher_class()
self._matcher_class = matcher_class
- self._cache: dict[tuple[str, str, int], tuple[float, Any]] = {}
+ self._cache: dict[tuple[str, str, int, bool], tuple[float, Any]] = {}
self._cache_lock = asyncio.Lock()
@property
@@ -76,6 +76,42 @@ class PrivacySanitizer:
"""Maximum UTF-8 input size accepted by this sanitizer."""
return self._max_content_bytes
+ @property
+ def max_replacements(self) -> int:
+ return self._max_replacements
+
+ async def prepare_matcher(
+ self, ctx: RequestContext, *, prefer_credentials: bool = False
+ ) -> Callable[[str], list[PrivacyReplacement]]:
+ """Prepare a cached, bounded match query for a batch of original texts.
+
+ The callable may run in a worker thread. It returns positions and existing
+ references so rule extraction can combine hits before rewriting content.
+ """
+ matcher = await self._matcher(ctx, prefer_credentials=prefer_credentials)
+
+ def find(content: str) -> list[PrivacyReplacement]:
+ try:
+ replacements, ambiguous, exceeded = matcher.find_limited(
+ content, self._max_replacements, self._max_content_bytes
+ )
+ except OverflowError:
+ raise ResourceExhaustedError(
+ "Content exceeds the Privacy sanitizer size limit"
+ ) from None
+ if ambiguous:
+ raise InvalidArgumentError(
+ "Content contains a Privacy value mapped to multiple fields; "
+ "insert the intended owner-bound reference explicitly"
+ )
+ if exceeded:
+ raise ResourceExhaustedError(
+ "Content exceeds the Privacy sanitizer replacement limit"
+ )
+ return [PrivacyReplacement(*item) for item in replacements]
+
+ return find
+
async def sanitize(
self,
content: str,
@@ -84,6 +120,7 @@ class PrivacySanitizer:
uri: str = "",
max_replacements: int | None = None,
fail_on_match_limit: bool = True,
+ prefer_credentials: bool = False,
) -> PrivacySanitizationResult:
if not content or self._is_privacy_storage_uri(uri, ctx):
return PrivacySanitizationResult(content=content)
@@ -97,7 +134,7 @@ class PrivacySanitizer:
"max_bytes": self._max_content_bytes,
},
)
- matcher = await self._matcher(ctx)
+ matcher = await self._matcher(ctx, prefer_credentials=prefer_credentials)
effective_max_replacements = (
self._max_replacements if max_replacements is None else max_replacements
)
@@ -128,9 +165,9 @@ class PrivacySanitizer:
match_limit_exceeded=match_limit_exceeded,
)
- async def _matcher(self, ctx: RequestContext) -> Any:
+ async def _matcher(self, ctx: RequestContext, *, prefer_credentials: bool = False) -> Any:
revision = self._privacy.catalog_revision(ctx)
- cache_key = (ctx.account_id, ctx.user.user_id, revision)
+ cache_key = (ctx.account_id, ctx.user.user_id, revision, prefer_credentials)
now = self._monotonic_clock()
cached = self._cache.get(cache_key)
if cached is not None and now - cached[0] < self._cache_ttl_seconds:
@@ -145,16 +182,19 @@ class PrivacySanitizer:
cached = self._cache.get(cache_key)
if cached is not None and now - cached[0] < self._cache_ttl_seconds:
return cached[1]
- matcher = await self._build_matcher(ctx)
+ matcher = await self._build_matcher(ctx, prefer_credentials=prefer_credentials)
owner_key = cache_key[:2]
self._cache = {
- key: item for key, item in self._cache.items() if key[:2] != owner_key
+ key: item
+ for key, item in self._cache.items()
+ if key[:2] != owner_key or key[2] == revision
}
self._cache[cache_key] = (now, matcher)
return matcher
- async def _build_matcher(self, ctx: RequestContext) -> Any:
+ async def _build_matcher(self, ctx: RequestContext, *, prefer_credentials: bool = False) -> Any:
references: dict[str, list[str]] = {}
+ credentials: dict[str, list[str]] = {}
for category in await self._privacy.list_categories(ctx):
for target_key in await self._privacy.list_targets(ctx, category):
current = await self._privacy.get_current(ctx, category, target_key)
@@ -177,10 +217,12 @@ class PrivacySanitizer:
field_name,
)
references.setdefault(value, []).append(reference)
+ if prefer_credentials and category == "credential":
+ credentials.setdefault(value, []).append(reference)
targets: dict[str, list[str]] = {}
for secret, candidates in references.items():
- targets[secret] = sorted(set(candidates))
+ targets[secret] = sorted(set(credentials.get(secret, candidates)))
return self._matcher_class(targets, _AMBIGUOUS_PLACEHOLDER)
@staticmethod
diff --git a/openviking/privacy/service.py b/openviking/privacy/service.py
index b7b1edbd8..a60aaa626 100644
--- a/openviking/privacy/service.py
+++ b/openviking/privacy/service.py
@@ -30,7 +30,7 @@ from openviking.privacy.validation import (
from openviking.server.identity import RequestContext
from openviking.storage.viking_fs import VikingFS
from openviking.utils.time_utils import get_current_timestamp
-from openviking_cli.exceptions import NotFoundError
+from openviking_cli.exceptions import AlreadyExistsError, NotFoundError
class UserPrivacyConfigService:
@@ -251,10 +251,10 @@ class UserPrivacyConfigService:
async with self._config_lock(
ctx, category, target_key, owner_lease_ref=owner_lease_ref
) as lease:
+ current = await self.get_current(ctx, category, target_key)
if preserve_fields:
# Resolve retained references under the write lock so a Skill
# prepared before a credential rotation keeps the latest value.
- current = await self.get_current(ctx, category, target_key)
retained = (
{key: value for key, value in current.values.items() if key in preserve_fields}
if current is not None
@@ -270,6 +270,7 @@ class UserPrivacyConfigService:
change_reason=change_reason,
labels=labels,
lease_ref=lease,
+ current=current,
)
async def patch_values(
@@ -282,7 +283,7 @@ class UserPrivacyConfigService:
change_reason: str = "",
labels: Optional[dict[str, Any]] = None,
) -> UserPrivacyConfigVersion:
- """Atomically merge fields into current values, creating the target if absent."""
+ """Atomically update named fields, preserving independent fields with equal values."""
async with self._config_lock(ctx, category, target_key) as lease:
current = await self.get_current(ctx, category, target_key)
values = dict(current.values) if current is not None else {}
@@ -296,6 +297,36 @@ class UserPrivacyConfigService:
change_reason=change_reason,
labels=labels,
lease_ref=lease,
+ current=current,
+ )
+
+ async def insert_values(
+ self,
+ ctx: RequestContext,
+ category: str,
+ target_key: str,
+ updates: dict[str, Any],
+ updated_by: str = "",
+ change_reason: str = "",
+ labels: Optional[dict[str, Any]] = None,
+ ) -> UserPrivacyConfigVersion:
+ """Atomically add new fields; labels apply only when creating the target."""
+ async with self._config_lock(ctx, category, target_key) as lease:
+ current = await self.get_current(ctx, category, target_key)
+ values = dict(current.values) if current is not None else {}
+ if not values.keys().isdisjoint(updates):
+ raise AlreadyExistsError(f"{category}/{target_key}", "privacy field")
+ values.update(updates)
+ return await self._upsert_locked(
+ ctx=ctx,
+ category=category,
+ target_key=target_key,
+ values=values,
+ updated_by=updated_by,
+ change_reason=change_reason,
+ labels=labels if current is None else None,
+ lease_ref=lease,
+ current=current,
)
async def _upsert_locked(
@@ -309,14 +340,14 @@ class UserPrivacyConfigService:
change_reason: str,
labels: Optional[dict[str, Any]],
lease_ref: Optional[dict[str, Any]],
+ current: Optional[UserPrivacyConfigVersion],
) -> UserPrivacyConfigVersion:
"""Persist a complete snapshot while the caller holds the target lock."""
- validate_privacy_values(values)
+ validate_privacy_values(values, category=category)
validate_privacy_metadata(change_reason=change_reason, labels=labels)
await self._ensure_root(ctx, category, target_key, lease_ref)
now = get_current_timestamp()
meta = await self.get_meta(ctx, category, target_key)
- current = await self.get_current(ctx, category, target_key)
if current and canonicalize_values(current.values) == canonicalize_values(values):
if meta is None:
diff --git a/openviking/privacy/session_extractor.py b/openviking/privacy/session_extractor.py
new file mode 100644
index 000000000..c68bcdaba
--- /dev/null
+++ b/openviking/privacy/session_extractor.py
@@ -0,0 +1,335 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Extract Session credentials before externalization and message persistence."""
+
+import asyncio
+import hashlib
+import re
+from collections.abc import Callable, Iterable, Iterator
+from dataclasses import dataclass, replace
+from secrets import token_urlsafe
+from typing import Any, TypeVar
+
+from openviking.message.part import ContextPart, ImagePart, Part, TextPart, ToolPart
+from openviking.privacy.reference import parse_privacy_field_reference
+from openviking.privacy.rules import (
+ MAX_MATCHES,
+ MAX_TEXT_CHARS,
+ find_privacy_matches,
+ is_sensitive_key,
+)
+from openviking.privacy.sanitizer import PrivacyReplacement, PrivacySanitizer
+from openviking.privacy.service import UserPrivacyConfigService
+from openviking.privacy.validation import validate_privacy_identifier
+from openviking.server.identity import RequestContext
+from openviking_cli.exceptions import (
+ AlreadyExistsError,
+ InvalidArgumentError,
+ ResourceExhaustedError,
+)
+
+MAX_BATCH_CHARS = 16 * 1024 * 1024
+MAX_DEPTH = 32
+MAX_NODES = 100_000
+MAX_FIELD_ID_ATTEMPTS = 8
+_Matcher = Callable[[str], list[PrivacyReplacement]]
+_Text = TypeVar("_Text", str, None)
+_HASHED_TARGET = re.compile(r"_[0-9a-f]{24}")
+
+
+async def extract_and_store_session_privacy(
+ session_id: str,
+ messages_spec: list[dict],
+ ctx: RequestContext,
+ privacy: UserPrivacyConfigService,
+ sanitizer: PrivacySanitizer | None,
+) -> list[dict]:
+ """Extract on copies, persist discoveries, then protect remaining registered values."""
+ target_key = session_privacy_target(session_id)
+ labels = None if target_key == session_id else {"session_id": session_id}
+ matcher = await _prepare_session_matcher(sanitizer, ctx, target_key)
+ for _ in range(MAX_FIELD_ID_ATTEMPTS):
+ sanitized, added = await asyncio.to_thread(
+ extract_session_privacy_values,
+ target_key,
+ messages_spec,
+ match_registered=matcher,
+ )
+ if not added:
+ return sanitized
+ try:
+ await privacy.insert_values(
+ ctx,
+ "session",
+ target_key,
+ added,
+ updated_by=ctx.user.user_id,
+ change_reason="Session message extraction",
+ labels=labels,
+ )
+ except AlreadyExistsError:
+ continue
+ break
+ else:
+ raise ResourceExhaustedError("Could not allocate unique Session privacy field IDs")
+ # Refresh the matcher to include newly saved values.
+ matcher = await _prepare_session_matcher(sanitizer, ctx, target_key)
+ rewriter = _SessionReferenceRewriter(matcher)
+ return await asyncio.to_thread(rewriter.transform_messages, sanitized)
+
+
+def extract_session_privacy_values(
+ target_key: str,
+ messages_spec: list[dict],
+ *,
+ match_registered: _Matcher | None = None,
+) -> tuple[list[dict], dict[str, Any]]:
+ """Return protected copies and discoveries without modifying caller-owned data."""
+ extraction = _SessionExtraction(target_key, match_registered or (lambda _: []))
+ return extraction.transform_messages(messages_spec), extraction.values
+
+
+def session_privacy_target(session_id: str) -> str:
+ if not _HASHED_TARGET.fullmatch(session_id):
+ # Use valid Privacy identifiers as-is
+ try:
+ return validate_privacy_identifier(session_id, "target_key")
+ except InvalidArgumentError:
+ pass
+ # hash other IDs and digest-shaped IDs.
+ digest = hashlib.sha256(session_id.encode("utf-8", "surrogatepass")).hexdigest()
+ return f"_{digest[:24]}"
+
+
+def build_session_placeholder(target_key: str, key: str) -> str:
+ return f"{{{{ov_privacy:session:{target_key}:{key}}}}}"
+
+
+async def _prepare_session_matcher(
+ sanitizer: PrivacySanitizer | None, ctx: RequestContext, target_key: str
+) -> _Matcher:
+ """Use Session placeholders for matching eight-character fields in this Session."""
+ if sanitizer is None:
+ return lambda _: []
+ matcher = await sanitizer.prepare_matcher(ctx, prefer_credentials=True)
+
+ def find(text: str) -> list[PrivacyReplacement]:
+ matches: list[PrivacyReplacement] = []
+ for match in matcher(text):
+ reference = parse_privacy_field_reference(match.reference)
+ if (
+ reference is not None
+ and reference.owner_user_id == ctx.user.user_id
+ and reference.category == "session"
+ and reference.target_key == target_key
+ and re.fullmatch(r"[A-Za-z0-9_-]{8}", reference.field)
+ ):
+ match = replace(
+ match, reference=build_session_placeholder(target_key, reference.field)
+ )
+ matches.append(match)
+ return matches
+
+ return find
+
+
+@dataclass
+class _ExtractionBudget:
+ nodes: int = 0
+ chars: int = 0
+ matches: int = 0
+
+ def check_node(self, depth: int) -> None:
+ self.nodes += 1
+ if depth > MAX_DEPTH or self.nodes > MAX_NODES:
+ raise InvalidArgumentError("Session privacy structure limit exceeded")
+
+ def check_text(self, text: str | None) -> None:
+ if not text:
+ return
+ self.chars += len(text)
+ if len(text) > MAX_TEXT_CHARS or self.chars > MAX_BATCH_CHARS:
+ raise InvalidArgumentError("Session privacy text limit exceeded")
+
+ def record_match(self) -> None:
+ self.matches += 1
+ if self.matches > MAX_MATCHES:
+ raise InvalidArgumentError("Session privacy match limit exceeded")
+
+
+class _PayloadTransformer:
+ """Traverse only payload fields; default text and field handlers preserve values."""
+
+ def __init__(self, budget: _ExtractionBudget | None = None):
+ self.budget = budget
+
+ def check_node(self, depth: int) -> None:
+ if self.budget is not None:
+ self.budget.check_node(depth)
+
+ def transform_text(self, text: _Text) -> _Text:
+ if self.budget is not None:
+ self.budget.check_text(text)
+ return text
+
+ def transform_field(self, key: str, value: Any, depth: int) -> Any:
+ return self.transform_value(value, depth)
+
+ def transform_value(self, value: Any, depth: int = 0) -> Any:
+ self.check_node(depth)
+ if isinstance(value, str):
+ return self.transform_text(value)
+ if isinstance(value, dict):
+ result = {}
+ for key, item in value.items():
+ if not isinstance(key, str):
+ raise InvalidArgumentError("Session privacy requires string object keys")
+ clean_key = self.transform_text(key)
+ if clean_key in result:
+ raise InvalidArgumentError("Session privacy object key collision")
+ result[clean_key] = self.transform_field(key, item, depth + 1)
+ return result
+ if isinstance(value, (list, tuple)):
+ items = [self.transform_value(item, depth + 1) for item in value]
+ return tuple(items) if isinstance(value, tuple) else items
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ raise InvalidArgumentError("Session privacy requires JSON-compatible tool input")
+
+ def transform_part(self, part: Part) -> Part:
+ if isinstance(part, TextPart):
+ part.text = self.transform_text(part.text)
+ elif isinstance(part, ContextPart):
+ part.abstract = self.transform_text(part.abstract)
+ elif isinstance(part, ToolPart):
+ part.tool_input = self.transform_value(part.tool_input)
+ part.tool_output = self.transform_text(part.tool_output)
+ part.tool_output_externalization_error = self.transform_text(
+ part.tool_output_externalization_error
+ )
+ elif not isinstance(part, ImagePart):
+ raise InvalidArgumentError("Session privacy received unsupported Part type")
+ return part
+
+ def transform_messages(self, messages_spec: list[dict]) -> list[dict]:
+ result = []
+ for spec in messages_spec:
+ self.check_node(0)
+ copied = dict(spec)
+ parts = []
+ for part in spec.get("parts", []):
+ self.check_node(0)
+ parts.append(self.transform_part(part))
+ if "parts" in copied:
+ copied["parts"] = parts
+ result.append(copied)
+ return result
+
+
+class _SessionExtraction(_PayloadTransformer):
+ """Discover values while copying inputs; sensitive fields are captured whole."""
+
+ budget: _ExtractionBudget
+
+ def __init__(self, target_key: str, value_matcher: _Matcher):
+ super().__init__(_ExtractionBudget())
+ self.target_key = target_key
+ self.value_matcher = value_matcher
+ self.values: dict[str, Any] = {}
+ self.text_references: dict[str, str] = {}
+ # Same input budget, with identity handlers: validate and copy, never extract.
+ self.literal = _PayloadTransformer(self.budget)
+
+ def transform_part(self, part: Part) -> Part:
+ if not isinstance(part, (TextPart, ContextPart, ToolPart, ImagePart)):
+ raise InvalidArgumentError("Session privacy received unsupported Part type")
+ return super().transform_part(replace(part))
+
+ def transform_field(self, key: str, value: Any, depth: int) -> Any:
+ if not is_sensitive_key(key):
+ return self.transform_value(value, depth)
+ copied = self.literal.transform_value(value, depth)
+ # Empty strings, references and environment variables retain their meaning.
+ # A neutral name captures Authorization including its authentication scheme.
+ if isinstance(copied, str) and not find_privacy_matches(copied, field_name="password"):
+ return copied
+ return self.get_reference(copied) if copied is not None else None
+
+ def get_reference(self, value: Any) -> str:
+ self.budget.record_match()
+ if isinstance(value, str):
+ matches = self.value_matcher(value)
+ if len(matches) == 1 and matches[0].start == 0 and matches[0].end == len(value):
+ return matches[0].reference
+ for _ in range(MAX_FIELD_ID_ATTEMPTS):
+ # Six random bytes encode to eight URL-safe characters.
+ key = token_urlsafe(6)
+ if key not in self.values:
+ self.values[key] = value
+ return build_session_placeholder(self.target_key, key)
+ raise ResourceExhaustedError("Could not allocate unique Session privacy field IDs")
+
+ def transform_text(self, text: _Text) -> _Text:
+ super().transform_text(text)
+ if text is None or not text:
+ return text
+ spans: list[tuple[int, int, str | None]] = [
+ (match.start, match.end, match.reference) for match in self.value_matcher(text)
+ ]
+ spans.extend((match.start, match.end, None) for match in find_privacy_matches(text))
+ replacements = []
+ for start, end, reference in _merge_spans(spans):
+ if reference is None:
+ value = text[start:end]
+ reference = self.text_references.get(value)
+ if reference is None:
+ reference = self.get_reference(value)
+ self.text_references[value] = reference
+ else:
+ self.budget.record_match()
+ else:
+ self.budget.record_match()
+ replacements.append(PrivacyReplacement(start, end, reference))
+ return _replace_spans(text, replacements)
+
+
+class _SessionReferenceRewriter(_PayloadTransformer):
+ """Protect batch-wide repeats without rebinding references to other fields."""
+
+ def __init__(self, value_matcher: _Matcher):
+ super().__init__()
+ self.value_matcher = value_matcher
+
+ def transform_text(self, text: _Text) -> _Text:
+ if text is None:
+ return text
+ return _replace_spans(text, self.value_matcher(text))
+
+
+def _merge_spans(
+ spans: list[tuple[int, int, str | None]],
+) -> Iterator[tuple[int, int, str | None]]:
+ """Union overlapping hits; reuse a registered reference only for the full union."""
+ if not spans:
+ return
+ spans.sort(key=lambda span: (span[0], -span[1]))
+ start, end, reference = spans[0]
+ for left, right, candidate in spans[1:]:
+ if left >= end:
+ yield start, end, reference
+ start, end, reference = left, right, candidate
+ elif right > end:
+ end, reference = right, None
+ elif left == start and right == end and candidate is not None:
+ reference = candidate
+ yield start, end, reference
+
+
+def _replace_spans(text: str, replacements: Iterable[PrivacyReplacement]) -> str:
+ chunks = []
+ cursor = 0
+ for match in replacements:
+ chunks.extend((text[cursor : match.start], match.reference))
+ cursor = match.end
+ chunks.append(text[cursor:])
+ return "".join(chunks)
diff --git a/openviking/privacy/session_restore.py b/openviking/privacy/session_restore.py
new file mode 100644
index 000000000..31d901546
--- /dev/null
+++ b/openviking/privacy/session_restore.py
@@ -0,0 +1,101 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Restore user-owned references only at the public Session content boundary."""
+
+import json
+from collections.abc import Callable
+from typing import Any
+
+from openviking.privacy.restore import PrivacyRestorer
+from openviking.privacy.service import UserPrivacyConfigService
+from openviking.privacy.session_extractor import session_privacy_target
+from openviking.server.identity import RequestContext
+from openviking_cli.exceptions import InvalidArgumentError
+
+_TEXT_FIELDS = {
+ "text": ("text",),
+ "context": ("abstract",),
+ "tool": ("tool_output", "tool_output_externalization_error"),
+}
+
+
+def get_session_id_from_uri(uri: str, session_root: str) -> str | None:
+ prefix = session_root + "/"
+ if not uri.startswith(prefix):
+ return None
+ session_id, *path = uri[len(prefix) :].split("/")
+ if not session_id:
+ return None
+ if path == ["messages.jsonl"]:
+ return session_id
+ if len(path) == 3 and path[0] == "history" and path[1].startswith("archive_"):
+ return session_id if path[2] == "messages.jsonl" else None
+ if len(path) == 3 and path[0] == "tool-results" and path[2] == "output.txt":
+ return session_id
+ return None
+
+
+async def restore_session_content(
+ privacy: UserPrivacyConfigService,
+ content: str,
+ ctx: RequestContext,
+ *,
+ session_id: str,
+ jsonl: bool = False,
+) -> str:
+ """Resolve user-owned references from current values without rewriting disk."""
+ restorer = PrivacyRestorer(
+ privacy, ctx, category="session", target_key=session_privacy_target(session_id)
+ )
+ if not jsonl:
+ restorer.collect_text(content)
+ await restorer.load_values()
+ return restorer.restore_text(content)
+
+ lines = content.split("\n")
+
+ def map_content(replace_text: Callable[[str], str]) -> None:
+ def structured(value: Any) -> Any:
+ if isinstance(value, str):
+ if value in restorer.values:
+ return restorer.values[value]
+ return replace_text(value)
+ if isinstance(value, list):
+ return [structured(item) for item in value]
+ if isinstance(value, dict):
+ result = {}
+ for key, item in value.items():
+ clean_key = replace_text(key)
+ if clean_key in result:
+ raise InvalidArgumentError("Session privacy restored object key collision")
+ result[clean_key] = structured(item)
+ return result
+ return value
+
+ for line, message in zip(lines, messages, strict=True):
+ if not line.strip():
+ continue
+ if not isinstance(message, dict):
+ raise TypeError("Session message must be an object")
+ for part in message.get("parts", []):
+ for field in _TEXT_FIELDS.get(part.get("type"), ()):
+ if isinstance(part.get(field), str):
+ part[field] = replace_text(part[field])
+ if part.get("type") == "tool" and "tool_input" in part:
+ part["tool_input"] = structured(part["tool_input"])
+
+ try:
+ messages = [json.loads(line) if line.strip() else None for line in lines]
+ map_content(restorer.collect_text)
+ except (ValueError, TypeError, AttributeError):
+ raise InvalidArgumentError("Session privacy requires valid message JSONL") from None
+
+ await restorer.load_values()
+ if not restorer.values:
+ return content
+
+ map_content(restorer.restore_text)
+ return "\n".join(
+ json.dumps(message, ensure_ascii=False) if line.strip() else line
+ for line, message in zip(lines, messages, strict=True)
+ )
diff --git a/openviking/privacy/skill_restore.py b/openviking/privacy/skill_restore.py
index 04473adfd..2d0465b99 100644
--- a/openviking/privacy/skill_restore.py
+++ b/openviking/privacy/skill_restore.py
@@ -2,9 +2,10 @@
# SPDX-License-Identifier: AGPL-3.0
"""Read-time restore helpers for skill privacy placeholders."""
-import re
-
+from openviking.privacy.restore import PrivacyRestorer
+from openviking.privacy.service import UserPrivacyConfigService
from openviking.privacy.skill_placeholder import build_placeholder
+from openviking.server.identity import RequestContext
def get_skill_name_from_uri(uri: str) -> str | None:
@@ -14,48 +15,46 @@ def get_skill_name_from_uri(uri: str) -> str | None:
if marker not in normalized or not normalized.endswith(suffix):
return None
start = normalized.rfind(marker)
- if start < 0:
- return None
middle = normalized[start + len(marker) : -len(suffix)]
if not middle or "/" in middle:
return None
return middle
-def _extract_placeholder_keys(content: str, skill_name: str) -> list[str]:
- pattern = re.compile(r"\{\{ov_privacy:skill:" + re.escape(skill_name) + r":([^}:]+)\}\}")
- keys: list[str] = []
- seen: set[str] = set()
- for match in pattern.finditer(content):
- key = match.group(1)
- if key not in seen:
- seen.add(key)
- keys.append(key)
- return keys
-
-
-def restore_skill_content(content: str, skill_name: str, values: dict[str, str]) -> str:
- restored = content
+async def restore_skill_content(
+ privacy: UserPrivacyConfigService,
+ content: str,
+ ctx: RequestContext,
+ *,
+ skill_name: str,
+) -> str:
+ restorer = PrivacyRestorer(privacy, ctx, category="skill", target_key=skill_name)
+ restorer.collect_text(content)
+ await restorer.load_values()
+ current = await restorer.get_current("skill", skill_name)
+ values = current.values if current else {}
unresolved_entries: list[str] = []
- placeholder_keys = _extract_placeholder_keys(content, skill_name)
- placeholder_key_set = set(placeholder_keys)
- for field_name in placeholder_keys:
- placeholder = build_placeholder(skill_name, field_name)
- raw_value = values.get(field_name)
- if raw_value is None or str(raw_value) == "":
- shown_value = "<missing>" if raw_value is None else '""'
- unresolved_entries.append(f"{field_name}={shown_value}")
- continue
- restored = restored.replace(placeholder, str(raw_value))
+ for placeholder, location in restorer.fields.items():
+ if placeholder == build_placeholder(skill_name, location.field):
+ raw_value = values.get(location.field)
+ if raw_value is None or raw_value == "":
+ shown_value = "<missing>" if raw_value is None else '""'
+ unresolved_entries.append(f"{location.field}={shown_value}")
+ used_fields = {
+ location.field
+ for location in restorer.fields.values()
+ if location.category == "skill" and location.target_key == skill_name
+ }
extra_config_entries = [
f"{key}={value}"
for key, value in values.items()
- if key not in placeholder_key_set and value is not None and str(value) != ""
+ if key not in used_fields and value is not None and value != ""
]
- if unresolved_entries or extra_config_entries:
+ restored = restorer.restore_text(content)
+ if current and (unresolved_entries or extra_config_entries):
restored += "\n\n[Privacy Config Notice]\n"
if unresolved_entries:
restored += "Missing config: " + ", ".join(unresolved_entries) + "\n"
diff --git a/openviking/privacy/validation.py b/openviking/privacy/validation.py
index 650e826ae..94634e4f4 100644
--- a/openviking/privacy/validation.py
+++ b/openviking/privacy/validation.py
@@ -14,6 +14,7 @@ from openviking_cli.exceptions import InvalidArgumentError
PRIVACY_IDENTIFIER_MAX_CHARS = 255
PRIVACY_FIELD_NAME_MAX_BYTES = 255
PRIVACY_MAX_FIELDS = 128
+SESSION_PRIVACY_MAX_FIELDS = 1024
PRIVACY_MAX_STRING_BYTES = 64 * 1024
PRIVACY_VALUES_MAX_BYTES = 1024 * 1024
PRIVACY_VALUES_MAX_DEPTH = 16
@@ -151,21 +152,22 @@ def _serialized_size(value: Mapping[str, Any]) -> int:
)
-def validate_privacy_values(values: Mapping[str, Any]) -> None:
+def validate_privacy_values(values: Mapping[str, Any], *, category: str = "") -> None:
"""Validate the complete active values snapshot before persistence."""
if not isinstance(values, Mapping):
raise InvalidArgumentError(
"Privacy values must be a JSON object.",
details={"field": "values", "reason": "expected object"},
)
- if len(values) > PRIVACY_MAX_FIELDS:
+ max_fields = SESSION_PRIVACY_MAX_FIELDS if category == "session" else PRIVACY_MAX_FIELDS
+ if len(values) > max_fields:
raise InvalidArgumentError(
- f"Privacy values contain {len(values)} fields; at most {PRIVACY_MAX_FIELDS} are allowed.",
+ f"Privacy values contain {len(values)} fields; at most {max_fields} are allowed.",
details={
"field": "values",
"reason": "too many fields",
"actual_fields": len(values),
- "max_fields": PRIVACY_MAX_FIELDS,
+ "max_fields": max_fields,
},
)
_validate_json_tree(values, location="values", depth=1)
diff --git a/openviking/pyagfs/__init__.py b/openviking/pyagfs/__init__.py
index fd900cc2f..da3d0c89c 100644
--- a/openviking/pyagfs/__init__.py
+++ b/openviking/pyagfs/__init__.py
@@ -158,6 +158,16 @@ def get_privacy_matcher_class():
) from exc
+def get_privacy_extractor_class():
+ """Return the native fixed-rule credential extractor."""
+ try:
+ return _load_rust_module().PrivacyExtractor
+ except (ImportError, AttributeError) as exc:
+ raise ImportError(
+ "ragfs_python PrivacyExtractor is not available; rebuild the native extension"
+ ) from exc
+
+
def reopen_rust_tracing_file() -> None:
"""Reopen the Rust tracing log file after Python rotates the active file."""
try:
diff --git a/openviking/service/core.py b/openviking/service/core.py
index 708225c99..9a71f277a 100644
--- a/openviking/service/core.py
+++ b/openviking/service/core.py
@@ -599,6 +599,8 @@ class OpenVikingService:
viking_fs=self._viking_fs,
session_compressor=self._session_compressor,
vlm_resolver=self._vlm_resolver,
+ privacy_config_service=self._privacy_config_service,
+ privacy_sanitizer=self._privacy_sanitizer,
)
self._resource_memory_link_service.set_dependencies(
vikingdb=self._vikingdb_manager,
diff --git a/openviking/service/fs_service.py b/openviking/service/fs_service.py
index 7166ae0a4..4ef6b5a7e 100644
--- a/openviking/service/fs_service.py
+++ b/openviking/service/fs_service.py
@@ -15,6 +15,7 @@ from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Literal,
from openviking.core.context import ContextLevel
from openviking.core.namespace import (
+ canonical_session_root,
classify_uri,
context_type_for_uri,
is_session_uri,
@@ -27,6 +28,7 @@ from openviking.core.namespace_policy import (
)
from openviking.privacy.sanitizer import PrivacySanitizer
from openviking.privacy.service import UserPrivacyConfigService
+from openviking.privacy.session_restore import get_session_id_from_uri, restore_session_content
from openviking.privacy.skill_restore import get_skill_name_from_uri, restore_skill_content
from openviking.resource.uri_mutation_coordinator import UriMutationCoordinator
from openviking.resource.watch_storage import is_watch_task_control_uri
@@ -1459,12 +1461,9 @@ class FSService:
viking_fs = self._ensure_initialized()
await viking_fs._ensure_access(uri, ctx, action=AclAction.WRITE)
- async def read(self, uri: str, ctx: RequestContext, offset: int = 0, limit: int = -1) -> str:
- """Read file content. Accepts a Viking URI or a 32-char hex vector record id."""
+ async def _read_content(self, uri: str, ctx: RequestContext) -> tuple[str, str]:
+ """Resolve the URI and read stored content without Privacy restoration."""
viking_fs = self._ensure_initialized()
- # Resolve ids to URIs so that downstream helpers (get_skill_name_from_uri)
- # always see a real viking:// URI. VikingFS.read_file also resolves, which
- # is harmless defense-in-depth when the input was already a URI.
resolved_uri = await self._resolve_uri(uri, ctx)
try:
content = await viking_fs.read_file(resolved_uri, ctx=ctx)
@@ -1474,15 +1473,29 @@ class FSService:
legacy_uri = validate_safe_viking_uri_path(resolved_uri.replace("%20", " "))
content = await viking_fs.read_file(legacy_uri, ctx=ctx)
resolved_uri = legacy_uri
- skill_name = get_skill_name_from_uri(resolved_uri)
- if skill_name and self._privacy_config_service:
- current = await self._privacy_config_service.get_current(
- ctx=ctx,
- category="skill",
- target_key=skill_name,
- )
- if current:
- content = restore_skill_content(content, skill_name, current.values)
+ return resolved_uri, content
+
+ async def read(self, uri: str, ctx: RequestContext, offset: int = 0, limit: int = -1) -> str:
+ """Read file content, restoring Privacy references for Skills and Sessions."""
+ resolved_uri, content = await self._read_content(uri, ctx)
+ if self._privacy_config_service is not None:
+ skill_name = get_skill_name_from_uri(resolved_uri)
+ session_id = get_session_id_from_uri(resolved_uri, canonical_session_root(ctx))
+ if skill_name is not None:
+ content = await restore_skill_content(
+ self._privacy_config_service,
+ content,
+ ctx,
+ skill_name=skill_name,
+ )
+ elif session_id is not None:
+ content = await restore_session_content(
+ self._privacy_config_service,
+ content,
+ ctx,
+ session_id=session_id,
+ jsonl=resolved_uri.endswith("/messages.jsonl"),
+ )
if offset == 0 and limit == -1:
return content
@@ -1520,12 +1533,20 @@ class FSService:
"max_bytes": self._privacy_sanitizer.max_content_bytes,
},
)
- content = await self.read(resolved_uri, ctx=ctx)
+ resolved_uri, content = await self._read_content(resolved_uri, ctx)
if classify_uri(resolved_uri).is_memory:
content = visible_content(content, uri=resolved_uri)
if self._privacy_sanitizer is not None:
content = (
- await self._privacy_sanitizer.sanitize(content, ctx=ctx, uri=resolved_uri)
+ await self._privacy_sanitizer.sanitize(
+ content,
+ ctx=ctx,
+ uri=resolved_uri,
+ prefer_credentials=(
+ get_session_id_from_uri(resolved_uri, canonical_session_root(ctx))
+ is not None
+ ),
+ )
).content
if offset == 0 and limit == -1:
return content
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index 18f5a75aa..b964f42d2 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -12,6 +12,8 @@ from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from openviking.core.namespace import canonical_session_uri
+from openviking.privacy.sanitizer import PrivacySanitizer
+from openviking.privacy.service import UserPrivacyConfigService
from openviking.server.config import ToolOutputExternalizationConfig
from openviking.server.identity import RequestContext
from openviking.server.user_config import read_user_memory_policy
@@ -82,6 +84,8 @@ class SessionService:
self._default_user_memory_policy: Optional[Dict[str, Any]] = None
self._default_user_auto_commit_policy: Optional[Dict[str, Any]] = None
self._usage_reporter: Optional["UsageReporter"] = None
+ self._privacy_config_service: Optional[UserPrivacyConfigService] = None
+ self._privacy_sanitizer: Optional[PrivacySanitizer] = None
# Server-wide controls remain disabled until configured during app setup.
self._session_auto_commit_config = SessionAutoCommitConfig()
# Per-worker in-flight guard so bursts don't spawn duplicate commit
@@ -115,12 +119,16 @@ class SessionService:
viking_fs: VikingFS,
session_compressor: "SessionCompressorV3",
vlm_resolver: Optional["VLMResolver"] = None,
+ privacy_config_service: Optional[UserPrivacyConfigService] = None,
+ privacy_sanitizer: Optional[PrivacySanitizer] = None,
) -> None:
"""Set dependencies (for deferred initialization)."""
self._vikingdb = vikingdb
self._viking_fs = viking_fs
self._session_compressor = session_compressor
self._vlm_resolver = vlm_resolver
+ self._privacy_config_service = privacy_config_service
+ self._privacy_sanitizer = privacy_sanitizer
def set_tool_output_externalization_config(
self, config: ToolOutputExternalizationConfig
@@ -248,6 +256,8 @@ class SessionService:
usage_reporter=self._usage_reporter,
vlm_resolver=self._vlm_resolver,
expiry_reporter=self._session_expiry_adapter,
+ privacy_config_service=self._privacy_config_service,
+ privacy_sanitizer=self._privacy_sanitizer,
)
async def _get_user_memory_policy(self, ctx: RequestContext) -> Optional[Dict[str, Any]]:
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 55457a633..0e83e1909 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -31,6 +31,9 @@ from openviking.core.namespace import canonical_session_uri
from openviking.core.peer_id import normalize_peer_id, safe_peer_id
from openviking.message import Message, Part
from openviking.message.part import TextPart, ToolPart
+from openviking.privacy.sanitizer import PrivacySanitizer
+from openviking.privacy.service import UserPrivacyConfigService
+from openviking.privacy.session_extractor import extract_and_store_session_privacy
from openviking.server.config import ToolOutputExternalizationConfig
from openviking.server.error_mapping import map_exception
from openviking.server.identity import RequestContext, Role
@@ -463,8 +466,12 @@ class Session:
memory_policy_provider: Optional[MemoryPolicyProvider] = None,
vlm_resolver: Optional["VLMResolver"] = None,
expiry_reporter: Optional[SessionExpiryReporter] = None,
+ privacy_config_service: Optional[UserPrivacyConfigService] = None,
+ privacy_sanitizer: Optional[PrivacySanitizer] = None,
):
self._viking_fs = viking_fs
+ self._privacy_config_service = privacy_config_service
+ self._privacy_sanitizer = privacy_sanitizer
self._vikingdb_manager = vikingdb_manager
self._session_compressor = session_compressor
self.user = user or UserIdentifier.the_default_user()
@@ -761,9 +768,10 @@ class Session:
if not self._viking_fs:
return
self._meta.updated_at = get_current_timestamp()
+ # bytes bypass VikingFS PrivacySanitizer, preserving JSON keys and identity fields.
await self._viking_fs.write_file(
uri=f"{self._session_uri}/.meta.json",
- content=json.dumps(self._meta.to_dict(), ensure_ascii=False),
+ content=json.dumps(self._meta.to_dict(), ensure_ascii=False).encode("utf-8"),
ctx=self.ctx,
lease_ref=lease_ref,
)
@@ -843,12 +851,9 @@ class Session:
content = await self._reload()
await self._apply_appended_messages_to_state(messages)
batch_content = "".join(message.to_jsonl() + "\n" for message in messages)
- # Preserve existing JSONL verbatim, as append_file did. Existing
- # content is already stored bytes; only initial creation used the
- # text-write privacy transformation.
- persisted_content = (
- batch_content if content is None else (content + batch_content).encode("utf-8")
- )
+ # Payloads are already protected. Bytes bypass the generic sanitizer
+ # so it cannot rewrite JSON keys or identity fields.
+ persisted_content = ((content or "") + batch_content).encode("utf-8")
await self._viking_fs.write_file(
f"{self._session_uri}/messages.jsonl",
persisted_content,
@@ -983,6 +988,14 @@ class Session:
messages_spec: List[dict],
) -> List[Message]:
"""Asynchronously add multiple messages without blocking the caller loop."""
+ if self._privacy_config_service is not None:
+ messages_spec = await extract_and_store_session_privacy(
+ self.session_id,
+ messages_spec,
+ self.ctx,
+ self._privacy_config_service,
+ self._privacy_sanitizer,
+ )
message_groups = self._build_message_groups(messages_spec)
messages = []
for group in message_groups:
@@ -1127,7 +1140,7 @@ class Session:
meta.update(updates)
await self._viking_fs.write_file(
uri=f"{archive_uri}/.meta.json",
- content=json.dumps(meta, ensure_ascii=False),
+ content=json.dumps(meta, ensure_ascii=False).encode("utf-8"),
ctx=self.ctx,
lease_ref=lease_ref,
)
@@ -1678,7 +1691,7 @@ class Session:
archive_persist_tasks.append(
self._viking_fs.write_file(
uri=f"{archive_uri}/messages.jsonl",
- content="\n".join(lines) + "\n",
+ content=("\n".join(lines) + "\n").encode("utf-8"),
ctx=self.ctx,
)
)
@@ -1883,7 +1896,7 @@ class Session:
try:
await self._viking_fs.write_file(
f"{archive_uri}/.done",
- json.dumps({"context_reset": True, "enable_working_memory": False}),
+ json.dumps({"context_reset": True, "enable_working_memory": False}).encode("utf-8"),
ctx=self.ctx,
)
except Exception as exc:
@@ -2700,7 +2713,7 @@ class Session:
)
await self._viking_fs.write_file(
uri=f"{archive_uri}/.done",
- content=content,
+ content=content.encode("utf-8"),
ctx=self.ctx,
)
@@ -2716,6 +2729,9 @@ class Session:
"""Persist a terminal failure marker under the marker file's own lock."""
if not self._viking_fs:
return
+ # Sanitize error separately because bytes bypass VikingFS PrivacySanitizer.
+ if self._privacy_sanitizer is not None:
+ error = (await self._privacy_sanitizer.sanitize(error, ctx=self.ctx)).content
payload = {
"stage": stage,
"error": error,
@@ -2727,7 +2743,7 @@ class Session:
payload["blocked_by"] = blocked_by
await self._viking_fs.write_file(
uri=f"{archive_uri}/.failed.json",
- content=json.dumps(payload, ensure_ascii=False),
+ content=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
ctx=self.ctx,
)
@@ -3477,6 +3493,8 @@ class Session:
abstract = self._generate_abstract()
overview = self._generate_overview(turn_count)
+ # Payloads are already sanitized; bytes bypass VikingFS PrivacySanitizer
+ # to preserve JSON keys and identity fields.
lines = [m.to_jsonl() for m in messages]
content = "\n".join(lines) + "\n" if lines else ""
abstract_content = render_abstract_overview(
@@ -3505,7 +3523,7 @@ class Session:
root_write_results = await asyncio.gather(
viking_fs.write_file(
uri=f"{self._session_uri}/messages.jsonl",
- content=content,
+ content=content.encode("utf-8"),
ctx=self.ctx,
lease_ref=lease_ref,
),
diff --git a/openviking/session/tool_result_store.py b/openviking/session/tool_result_store.py
index a72912f4f..6e98d4dca 100644
--- a/openviking/session/tool_result_store.py
+++ b/openviking/session/tool_result_store.py
@@ -192,9 +192,11 @@ class ToolResultStore:
"offset_unit": "unicode_code_point",
}
await self._viking_fs.write_file(output_uri, content, ctx=self._ctx)
+ # Output is already sanitized; bytes bypass VikingFS PrivacySanitizer
+ # to preserve JSON keys and identity fields.
await self._viking_fs.write_file(
metadata_uri,
- json.dumps(metadata, ensure_ascii=False, indent=2),
+ json.dumps(metadata, ensure_ascii=False, indent=2).encode("utf-8"),
ctx=self._ctx,
)
return StoredToolResult(
diff --git a/tests/server/test_privacy_config_service.py b/tests/server/test_privacy_config_service.py
index 596239649..0c77317f2 100644
--- a/tests/server/test_privacy_config_service.py
+++ b/tests/server/test_privacy_config_service.py
@@ -2,17 +2,21 @@
# SPDX-License-Identifier: AGPL-3.0
import asyncio
+import json
+from unittest.mock import AsyncMock
import pytest
from openviking.core.namespace import canonical_user_root
+from openviking.privacy.reference import build_privacy_field_reference
from openviking.privacy.service import UserPrivacyConfigService
+from openviking.privacy.session_extractor import build_session_placeholder
from openviking.privacy.skill_extractor import extract_skill_privacy_values
from openviking.privacy.skill_placeholder import placeholderize_skill_content_with_blocks
-from openviking.privacy.validation import PRIVACY_MAX_FIELDS
+from openviking.privacy.validation import PRIVACY_MAX_FIELDS, SESSION_PRIVACY_MAX_FIELDS
from openviking.server.identity import RequestContext, Role
from openviking.storage.viking_fs import VikingFS
-from openviking_cli.exceptions import InvalidArgumentError, NotFoundError
+from openviking_cli.exceptions import AlreadyExistsError, InvalidArgumentError, NotFoundError
from openviking_cli.session.user_id import UserIdentifier
@@ -66,6 +70,26 @@ class _MemoryPrivacyStorage:
]
+async def test_patch_values_preserves_snapshot_history():
+ privacy = UserPrivacyConfigService(_MemoryPrivacyStorage())
+ ctx = RequestContext(user=UserIdentifier.the_default_user("privacy_merge"), role=Role.ROOT)
+ for added, expected, version in [
+ ({"one": "secret-1"}, {"one": "secret-1"}, 1),
+ ({"one": "secret-1"}, {"one": "secret-1"}, 1),
+ ({"two": "secret-2"}, {"one": "secret-1", "two": "secret-2"}, 2),
+ ]:
+ result = await privacy.patch_values(ctx, "session", "demo", added)
+ assert result.values == expected
+ assert result.version == version
+
+ await privacy.activate_version(ctx, "session", "demo", 1)
+ result = await privacy.patch_values(ctx, "session", "demo", {"three": "secret-3"})
+ assert result.version == 3
+ assert result.values == {"one": "secret-1", "three": "secret-3"}
+ assert await privacy.list_versions(ctx, "session", "demo") == [1, 2, 3]
+
+
@pytest.mark.asyncio
async def test_privacy_config_service_versions(service):
ctx = RequestContext(user=UserIdentifier.the_default_user("privacy_user"), role=Role.ROOT)
@@ -153,22 +177,27 @@ async def test_privacy_config_concurrent_patches_do_not_lose_distinct_fields():
@pytest.mark.asyncio
-async def test_privacy_config_patch_validates_final_snapshot_and_preserves_current_on_failure():
+ "category,limit", [("credential", PRIVACY_MAX_FIELDS), ("session", SESSION_PRIVACY_MAX_FIELDS)]
+)
+async def test_privacy_config_patch_validates_final_snapshot_and_preserves_current_on_failure(
+ category, limit
+):
ctx = RequestContext(user=UserIdentifier.the_default_user("privacy_limit"), role=Role.ROOT)
privacy = UserPrivacyConfigService(_MemoryPrivacyStorage())
- original = {f"key_{index}": index for index in range(PRIVACY_MAX_FIELDS)}
- await privacy.upsert(ctx, "credential", "full", original, updated_by=ctx.user.user_id)
+ original = {f"key_{index}": index for index in range(limit)}
+ await privacy.upsert(ctx, category, "full", original, updated_by=ctx.user.user_id)
- with pytest.raises(InvalidArgumentError, match="at most 128"):
+ with pytest.raises(InvalidArgumentError, match=f"at most {limit}"):
await privacy.patch_values(
ctx,
- "credential",
+ category,
"full",
{"one_more": "value"},
updated_by=ctx.user.user_id,
)
- current = await privacy.get_current(ctx, "credential", "full")
+ current = await privacy.get_current(ctx, category, "full")
assert current is not None
assert current.version == 1
assert current.values == original
@@ -255,6 +284,81 @@ async def test_skill_read_restores_placeholder_for_agent_segment_name(service):
assert "https://example.com" in restored
+async def test_skill_default_read_preserves_references_and_raw_restores_credentials(
+ client, service, monkeypatch
+):
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+ await service.initialize_user_directories(ctx)
+ await service.privacy_configs.upsert(ctx, "skill", "read-boundary", {"token": "pin"})
+ await service.privacy_configs.upsert(ctx, "credential", "managed", {"key": 'quote"secret'})
+ reference = build_privacy_field_reference(ctx.user.user_id, "credential", "managed", "key")
+ local = build_privacy_field_reference(ctx.user.user_id, "skill", "read-boundary", "token")
+ content = (
+ f"token={{{{ov_privacy:skill:read-boundary:token}}}}\nlocal={local}\nmanaged={reference}\n"
+ )
+ root = f"{canonical_user_root(ctx)}/skills/read-boundary"
+ await service.viking_fs.mkdir(root, exist_ok=True, ctx=ctx)
+ uri = root + "/SKILL.md"
+ await service.viking_fs.write_file(uri, content, ctx=ctx)
+ visible = await client.get("/api/v1/content/read", params={"uri": uri})
+ assert visible.status_code == 200, visible.text
+ assert visible.json()["result"] == content
+ read = AsyncMock(wraps=service.privacy_configs.get_current)
+ monkeypatch.setattr(service.privacy_configs, "get_current", read)
+ raw = await client.get("/api/v1/content/read", params={"uri": uri, "raw": True})
+ assert raw.status_code == 200, raw.text
+ assert raw.json()["result"] == 'token=pin\nlocal=pin\nmanaged=quote"secret\n'
+ assert read.await_count == 2
+
+
[email protected]("entrypoint", ["skill", "session"])
+async def test_read_preserves_empty_privacy_references(client, service, entrypoint):
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+ await service.initialize_user_directories(ctx)
+ values = {"empty000": "", "null0000": None, "false000": False, "zero0000": 0}
+ references, expected = [], []
+ for category in ["skill", "credential", "session"]:
+ await service.privacy_configs.upsert(ctx, category, "empty-values", values)
+ placeholders = [
+ build_privacy_field_reference(ctx.user.user_id, category, "empty-values", field)
+ for field in values
+ ]
+ references.extend(placeholders)
+ expected.extend([*placeholders[:2], False, 0])
+ if entrypoint == "session":
+ placeholders = [build_session_placeholder("empty-values", field) for field in values]
+ references.extend(placeholders)
+ expected.extend([*placeholders[:2], False, 0])
+ text = "\n".join(references)
+ expected_text = "\n".join(map(str, expected))
+ if entrypoint == "skill":
+ root = f"{canonical_user_root(ctx)}/skills/empty-values"
+ await service.viking_fs.mkdir(root, exist_ok=True, ctx=ctx)
+ uri, content = root + "/SKILL.md", text
+ else:
+ session = await service.sessions.create(ctx, "empty-values")
+ uri = session.uri + "/messages.jsonl"
+ content = json.dumps(
+ {
+ "parts": [
+ {"type": "text", "text": text},
+ {"type": "tool", "tool_input": {"rows": references}},
+ ]
+ }
+ )
+ await service.viking_fs.write_file(uri, content, ctx=ctx)
+ response = await client.get("/api/v1/content/read", params={"uri": uri, "raw": True})
+ assert response.status_code == 200, response.text
+ restored = response.json()["result"]
+ if entrypoint == "skill":
+ assert restored == expected_text
+ else:
+ parts = json.loads(restored)["parts"]
+ assert parts[0]["text"] == expected_text
+ assert json.dumps(parts[1]["tool_input"]["rows"]) == json.dumps(expected)
+
+
@pytest.mark.asyncio
async def test_skill_privacy_extraction_returns_content_blocks():
content = 'api_key: "secret-xyz"\nbase_url: "https://example.com"\n'
@@ -451,3 +555,41 @@ def test_placeholderization_preserves_quoted_value_matching():
assert result.sanitized_content == (
'note: use "{{ov_privacy:skill:quoted-skill:api_key}}" in prose\n'
)
+
+
+async def test_patch_preserves_equal_fields_and_rotates_only_named_field(monkeypatch):
+ category = "credential"
+ from unittest.mock import AsyncMock
+
+ privacy = UserPrivacyConfigService(_MemoryPrivacyStorage())
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+ await privacy.upsert(ctx, category, "demo", {"a": "old-secret", "b": "new-secret"})
+ read = AsyncMock(wraps=privacy.get_current)
+ monkeypatch.setattr(privacy, "get_current", read)
+ current = await privacy.patch_values(
+ ctx, category, "demo", {"a": "new-secret", "c": "new-secret"}
+ )
+ assert current.values == {"a": "new-secret", "b": "new-secret", "c": "new-secret"}
+ read.assert_awaited_once()
+ rotated = await privacy.patch_values(ctx, category, "demo", {"a": "rotated-secret"})
+ assert rotated.values == {"a": "rotated-secret", "b": "new-secret", "c": "new-secret"}
+ previous = await privacy.get_version(ctx, category, "demo", current.version)
+ assert previous.values == current.values
+
+
+async def test_insert_values_rejects_the_entire_batch_even_when_existing_value_is_equal():
+ privacy = UserPrivacyConfigService(_MemoryPrivacyStorage())
+ ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+ await privacy.upsert(ctx, "session", "demo", {"taken001": "old-secret"})
+ with pytest.raises(AlreadyExistsError):
+ await privacy.insert_values(
+ ctx,
+ "session",
+ "demo",
+ updates={"taken001": "old-secret", "free0002": "new-secret"},
+ )
+ current = await privacy.get_current(ctx, "session", "demo")
+ assert current.values == {"taken001": "old-secret"}
+ assert await privacy.list_versions(ctx, "session", "demo") == [1]
diff --git a/tests/server/test_session_privacy.py b/tests/server/test_session_privacy.py
new file mode 100644
index 000000000..a1169e95a
--- /dev/null
+++ b/tests/server/test_session_privacy.py
@@ -0,0 +1,569 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Protect Session persistence and restore only on explicit raw reads."""
+
+import asyncio
+import json
+from copy import deepcopy
+from dataclasses import asdict
+from unittest.mock import AsyncMock
+
+import pytest
+
+from openviking.message import ContextPart, ImagePart, TextPart, ToolPart
+from openviking.privacy.reference import build_privacy_field_reference
+from openviking.privacy.session_extractor import (
+ build_session_placeholder,
+ extract_and_store_session_privacy,
+ session_privacy_target,
+)
+from openviking.privacy.session_restore import restore_session_content
+from openviking.server.config import ToolOutputExternalizationConfig
+from openviking.server.identity import RequestContext, Role
+from openviking_cli.exceptions import InvalidArgumentError, ResourceExhaustedError
+from openviking_cli.session.user_id import UserIdentifier
+
+
+def ctx():
+ return RequestContext(user=UserIdentifier.the_default_user(), role=Role.ROOT)
+
+
+async def test_http_preserves_protected_content_and_restores_only_raw_reads(client, service, ctx):
+ sid = "http-privacy"
+ response = await client.post("/api/v1/sessions", json={"session_id": sid})
+ assert response.status_code == 200, response.text
+ uri = response.json()["result"]["uri"] + "/messages.jsonl"
+ reference = build_privacy_field_reference(ctx.user.user_id, "credential", "github", "pat")
+ await service.privacy_configs.upsert(ctx, "credential", "github", {"pat": "registered-secret"})
+ response = await client.post(
+ f"/api/v1/sessions/{sid}/messages/batch",
+ json={
+ "messages": [
+ {
+ "role": "user",
+ "content": "password=http-secret registered-secret repeated http-secret",
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "type": "tool",
+ "tool_id": "pending",
+ "tool_status": "pending",
+ "tool_output": None,
+ }
+ ],
+ },
+ ]
+ },
+ )
+ assert response.status_code == 200, response.text
+ disk = await service.viking_fs.read_file(uri, ctx=ctx)
+ assert "http-secret" not in disk and "registered-secret" not in disk
+ assert reference in disk
+ for raw in [False, True]:
+ read = await client.get("/api/v1/content/read", params={"uri": uri, "raw": raw})
+ assert read.status_code == 200, read.text
+ public = read.json()["result"]
+ assert ("http-secret" in public) == raw
+ assert ("registered-secret" in public) == raw
+ assert (reference in public) == (not raw)
+ json.loads(public.splitlines()[1]) # Pending tool output remains valid JSON.
+ internal = await client.get(f"/api/v1/sessions/{sid}/context")
+ assert internal.status_code == 200, internal.text
+ assert "registered-secret" not in internal.text and "http-secret" not in internal.text
+ current = await service.privacy_configs.get_current(ctx, "session", sid)
+ assert list(current.values.values()) == ["http-secret"]
+ assert (await client.delete(f"/api/v1/sessions/{sid}")).status_code == 200
+ assert (await client.get(f"/api/v1/privacy-configs/session/{sid}")).status_code == 200
+
+
+async def test_default_read_keeps_escaped_short_and_container_values_protected(
+ client, service, ctx
+):
+ original = {
+ "password": 'quote"secret',
+ "token": "line\nsecret",
+ "api_key": "back\\secret",
+ "secret": "pin",
+ "credentials": {"api_key": "container-secret", "items": [False, None, 7]},
+ }
+ session = await service.sessions.create(ctx, "protected-read")
+ await session.add_message_async("assistant", [ToolPart(tool_input=original)])
+ uri = session.uri + "/messages.jsonl"
+ disk = await service.viking_fs.read_file(uri, ctx=ctx)
+ visible = await client.get("/api/v1/content/read", params={"uri": uri})
+ assert visible.status_code == 200, visible.text
+ assert visible.json()["result"] == disk
+ raw = await client.get("/api/v1/content/read", params={"uri": uri, "raw": True})
+ assert raw.status_code == 200, raw.text
+ assert json.loads(raw.json()["result"])["parts"][0]["tool_input"] == original
+
+
+async def test_new_equal_fields_keep_independent_references_when_one_rotates(service, ctx):
+ session = await service.sessions.create(ctx, "equal-new-fields")
+ original = {"password": "same-new-value", "api_key": "same-new-value"}
+ await session.add_message_async("assistant", [ToolPart(tool_input=original)])
+ protected = session.messages[0].parts[0].tool_input
+ fields = {key: ref.removesuffix("}}").rsplit(":", 1)[1] for key, ref in protected.items()}
+ current = await service.privacy_configs.get_current(ctx, "session", session.session_id)
+ assert current.values == dict.fromkeys(fields.values(), "same-new-value")
+ await service.privacy_configs.patch_values(
+ ctx, "session", session.session_id, {fields["password"]: "rotated-value"}
+ )
+ restored = json.loads(await service.fs.read(session.uri + "/messages.jsonl", ctx=ctx))
+ assert restored["parts"][0]["tool_input"] == {
+ "password": "rotated-value",
+ "api_key": "same-new-value",
+ }
+
+
+async def test_batch_repeated_text_values_allow_later_messages(service, ctx):
+ session = await service.sessions.create(ctx, "batch-repeat")
+ texts = [
+ "password=shared-secret password=shared-secret",
+ "**password=shared-secret**",
+ "password=shared-secret",
+ ]
+ await session.add_messages_async(
+ [
+ {"role": "user", "parts": [TextPart(texts[0])]},
+ {"role": "assistant", "parts": [TextPart(texts[1])]},
+ ]
+ )
+ await session.add_message_async("user", [TextPart(texts[2])])
+ current = await service.privacy_configs.get_current(ctx, "session", session.session_id)
+ assert list(current.values.values()) == ["shared-secret"]
+ assert await service.privacy_configs.list_versions(ctx, "session", session.session_id) == [1]
+ disk = await service.viking_fs.read_file(session.uri + "/messages.jsonl", ctx=ctx)
+ assert "shared-secret" not in disk
+ restored = await service.fs.read(session.uri + "/messages.jsonl", ctx=ctx)
+ assert [json.loads(line)["parts"][0]["text"] for line in restored.splitlines()] == texts
+
+
+async def test_basic_prose_does_not_register_words_for_later_messages(service, ctx):
+ session = await service.sessions.create(ctx, "basic-prose")
+ text = "This is a basic example of configuration.\nBasic usage\nUse basic Python syntax."
+ await session.add_message_async("user", [TextPart(text)])
+ await session.add_message_async("assistant", [TextPart("Python usage example")])
+ assert await service.privacy_configs.get_current(ctx, "session", session.session_id) is None
+ disk = await service.viking_fs.read_file(session.uri + "/messages.jsonl", ctx=ctx)
+ assert [json.loads(line)["parts"][0]["text"] for line in disk.splitlines()] == [
+ text,
+ "Python usage example",
+ ]
+
+
[email protected]("sid", ["markdown-restatement", "中文会话"])
+async def test_markdown_restatement_reuses_references_without_new_versions(service, ctx, sid):
+ session = await service.sessions.create(ctx, sid)
+ user_text = "API_KEY=demo-api-secret\nAuthorization: Bearer demo-bearer-secret\nsk-abcdefghijklmnopqrstuv"
+ await session.add_message_async("user", [TextPart(user_text)])
+ target_key = session_privacy_target(sid)
+ initial = await service.privacy_configs.get_current(ctx, "session", target_key)
+ wrappers = [
+ "**{}**",
+ "`{}`",
+ "``{}``",
+ "**`{}`**",
+ "`**heading**` `{}`",
+ "```text\n{}\n```",
+ "~~~text\n{}\n~~~",
+ ]
+ assistant_text = "\n".join(
+ wrapper.format(line) for wrapper in wrappers for line in user_text.splitlines()
+ )
+ await session.add_message_async(
+ "assistant",
+ [TextPart(assistant_text), ToolPart(tool_input={"api_key": "demo-api-secret"})],
+ )
+ current = await service.privacy_configs.get_current(ctx, "session", target_key)
+ assert current.values == initial.values
+ assert await service.privacy_configs.list_versions(ctx, "session", target_key) == [1]
+ disk = await service.viking_fs.read_file(session.uri + "/messages.jsonl", ctx=ctx)
+ assert all(value not in disk for value in initial.values.values())
+ user, assistant = [json.loads(line)["parts"] for line in disk.splitlines()]
+ assert assistant[0]["text"] == "\n".join(
+ wrapper.format(line) for wrapper in wrappers for line in user[0]["text"].splitlines()
+ )
+ assert assistant[1]["tool_input"]["api_key"] == user[0]["text"].splitlines()[0].split("=", 1)[1]
+ restored = await service.fs.read(session.uri + "/messages.jsonl", ctx=ctx)
+ assert [json.loads(line)["parts"][0]["text"] for line in restored.splitlines()] == [
+ user_text,
+ assistant_text,
+ ]
+
+
[email protected]("entrypoint", ["session", "skill"])
+async def test_session_and_skill_require_explicit_reference_for_ambiguous_value(
+ service, ctx, entrypoint
+):
+ await service.privacy_configs.upsert(
+ ctx, "credential", "ambiguous", {"a": "same-registered-value", "b": "same-registered-value"}
+ )
+ with pytest.raises(InvalidArgumentError, match="mapped to multiple fields"):
+ if entrypoint == "skill":
+ await service._skill_processor.prepare_skill_privacy(
+ {"name": "ambiguous", "content": "password=same-registered-value"}, ctx
+ )
+ else:
+ session = await service.sessions.create(ctx, "ambiguous")
+ await session.add_message_async("user", [TextPart("password=same-registered-value")])
+ if entrypoint == "session":
+ assert await service.viking_fs.read_file(session.uri + "/messages.jsonl", ctx=ctx) == ""
+ assert await service.privacy_configs.get_current(ctx, "session", session.session_id) is None
+ refs = [
+ build_privacy_field_reference(ctx.user.user_id, "credential", "ambiguous", field)
+ for field in ("a", "b")
+ ]
+ await session.add_message_async("user", [TextPart(" ".join(refs))])
+ restored = json.loads(await service.fs.read(session.uri + "/messages.jsonl", ctx=ctx))
+ assert restored["parts"][0]["text"] == "same-registered-value same-registered-value"
+
+
+async def test_batch_discovery_protects_all_payloads_without_mutating_inputs(service, ctx):
+ await service.privacy_configs.upsert(ctx, "credential", "github", {"pat": "registered-value"})
+ fresh = "alpha-987654"
+ credentials = {"api_key": "nested-value", "items": [False, None, "中文"]}
+ specs = [
+ {
+ "role": "assistant",
+ "peer_id": fresh,
+ "parts": [
+ TextPart(f"retry {fresh}; registered-value"),
+ ContextPart(uri=f"viking://resources/{fresh}", abstract=fresh),
+ ImagePart(url=f"https://example.test/{fresh}"),
+ ToolPart(
+ tool_id=fresh,
+ tool_input={
+ fresh: fresh,
+ "rows": ({"note": fresh}, False, None),
+ "credentials": credentials,
+ },
+ tool_output=fresh,
+ tool_output_externalization_error=fresh,
+ ),
+ ToolPart(tool_id="pending", tool_output=None),
+ TextPart(f"password={fresh}"),
+ ],
+ }
+ ]
+ before = deepcopy(specs)
+ protected = await extract_and_store_session_privacy(
+ "traversal", specs, ctx, service.privacy_configs, service._privacy_sanitizer
+ )
+ assert specs == before
+ parts = protected[0]["parts"]
+ current = await service.privacy_configs.get_current(ctx, "session", "traversal")
+ assert credentials in current.values.values()
+ reference = next(
+ build_session_placeholder("traversal", field)
+ for field, value in current.values.items()
+ if value == fresh
+ )
+ assert parts[0].text.startswith(f"retry {reference}; ")
+ assert parts[1].abstract == reference
+ assert parts[3].tool_input[reference] == reference
+ assert parts[3].tool_input["rows"][0]["note"] == reference
+ assert parts[3].tool_output == reference
+ assert parts[3].tool_output_externalization_error == reference
+ encoded = json.dumps({**protected[0], "parts": [asdict(part) for part in parts]})
+ restored = await restore_session_content(
+ service.privacy_configs,
+ encoded,
+ ctx,
+ session_id="traversal",
+ jsonl=True,
+ )
+ expected = json.dumps({**before[0], "parts": [asdict(part) for part in before[0]["parts"]]})
+ assert json.loads(restored) == json.loads(expected)
+
+
+async def test_batch_discovery_rejects_key_collision_before_message_write(
+ service, ctx, monkeypatch
+):
+ from openviking.privacy import session_extractor
+
+ fixed_id = "same0001"
+ monkeypatch.setattr(session_extractor, "token_urlsafe", lambda _: fixed_id)
+ session = await service.sessions.create(ctx, "collision")
+ reference = build_session_placeholder(session.session_id, fixed_id)
+ part = ToolPart(
+ tool_input={"alpha-987654": 1, reference: 2}, tool_output="password=alpha-987654"
+ )
+ before = deepcopy(part)
+ externalize = AsyncMock()
+ monkeypatch.setattr(session._tool_outputs, "externalize_group", externalize)
+ with pytest.raises(InvalidArgumentError, match="object key collision"):
+ await session.add_message_async("assistant", [part])
+ externalize.assert_not_awaited()
+ assert part == before
+ assert await service.viking_fs.read_file(session.uri + "/messages.jsonl", ctx=ctx) == ""
+
+
+async def test_externalized_output_restores_without_corrupting_metadata(service, ctx):
+ session = await service.sessions.create(ctx, "externalized")
+ session._tool_output_externalization_config = ToolOutputExternalizationConfig(
+ enabled=True, threshold_chars=1024, preview_chars=200
+ )
+ output = "padding\n" * 1500 + "password=session"
+ await session.add_message_async("assistant", [ToolPart(tool_id="read", tool_output=output)])
+ part = session.messages[0].parts[0]
+ ref = part.tool_output_ref
+ assert ref
+ stored = await service.viking_fs.read_file(ref + "/output.txt", ctx=ctx)
+ assert "password=session" not in stored
+ assert await service.fs.read(ref + "/output.txt", ctx=ctx) == output
+ visible = await service.fs.read_visible(ref + "/output.txt", ctx=ctx)
+ assert "password=session" not in visible
+ assert "{{ov_privacy:" in visible
+ metadata = json.loads(await service.viking_fs.read_file(ref + "/metadata.json", ctx=ctx))
+ assert metadata["session_id"] == session.session_id
+ reloaded = await service.sessions.get(session.session_id, ctx)
+ assert "password=session" not in json.dumps(
+ [message.to_dict() for message in reloaded.messages]
+ )
+
+
+async def test_auto_created_session_extracts_before_persistence(service, ctx):
+ session = await service.sessions.get("auto-created", ctx, auto_create=True)
+ await session.add_message_async("user", [TextPart("password=default-secret")])
+ uri = session.uri + "/messages.jsonl"
+ disk = await service.viking_fs.read_file(uri, ctx=ctx)
+ assert "default-secret" not in disk
+ current = await service.privacy_configs.get_current(ctx, "session", session.session_id)
+ assert list(current.values.values()) == ["default-secret"]
+ assert "default-secret" in await service.fs.read(uri, ctx=ctx)
+
+
+ "sid",
+ ["中文会话", "team session@@group", " leading and trailing ", "x" * 300, "group:100%~"],
+)
+async def test_custom_session_ids_support_privacy_and_cross_session_reuse(service, ctx, sid):
+ session = await service.sessions.create(ctx, sid)
+ await session.add_message_async("user", [TextPart("password=custom-session-secret")])
+ target_key = session_privacy_target(sid)
+ current = await service.privacy_configs.get_current(ctx, "session", target_key)
+ [field] = current.values
+ meta = await service.privacy_configs.get_meta(ctx, "session", target_key)
+ assert meta.labels == {"session_id": sid}
+ uri = session.uri + "/messages.jsonl"
+ disk = await service.viking_fs.read_file(uri, ctx=ctx)
+ assert "custom-session-secret" not in disk
+ assert build_session_placeholder(target_key, field) in disk
+ restored = await service.fs.read(uri, ctx=ctx)
+ assert json.loads(restored)["parts"][0]["text"] == "password=custom-session-secret"
+ target = await service.sessions.create(ctx, "reuse-custom-id")
+ await target.add_message_async("user", [TextPart("password=custom-session-secret")])
+ reference = build_privacy_field_reference(ctx.user.user_id, "session", target_key, field)
+ assert target.messages[0].parts[0].text == f"password={reference}"
+ restored = await service.fs.read(target.uri + "/messages.jsonl", ctx=ctx)
+ assert json.loads(restored)["parts"][0]["text"] == "password=custom-session-secret"
+
+
+async def test_concurrent_writers_preserve_messages_and_independent_fields(
+ service, ctx, monkeypatch
+):
+ from openviking.privacy import session_extractor
+
+ ids = iter(["same0001"] * 8 + [f"next{i:04d}" for i in range(8)])
+ monkeypatch.setattr(session_extractor, "token_urlsafe", lambda _: next(ids))
+ session = await service.sessions.create(ctx, "concurrent")
+ await service.privacy_configs.upsert(
+ ctx, "session", session.session_id, {"same0001": "old-secret"}
+ )
+ old_reference = build_privacy_field_reference(
+ ctx.user.user_id, "session", session.session_id, "same0001"
+ )
+ await session.add_message_async("user", [TextPart(old_reference)])
+ await asyncio.gather(
+ *(
+ service.sessions.session(ctx, "concurrent").add_message_async(
+ "user", [TextPart(f"password=secret-{i}")]
+ )
+ for i in range(8)
+ )
+ )
+ loaded = await service.sessions.get("concurrent", ctx)
+ current = await service.privacy_configs.get_current(ctx, "session", "concurrent")
+ assert set(current.values.values()) == {"old-secret", *(f"secret-{i}" for i in range(8))}
+ assert current.version == 9
+ restored = await service.fs.read(loaded.uri + "/messages.jsonl", ctx=ctx)
+ assert sorted(json.loads(line)["parts"][0]["text"] for line in restored.splitlines()) == [
+ "old-secret",
+ *(f"password=secret-{i}" for i in range(8)),
+ ]
+
+
+ "error", [ResourceExhaustedError, OSError], ids=["id-exhaustion", "storage"]
+)
+async def test_privacy_write_failure_rejects_batch_before_externalization(
+ service, ctx, monkeypatch, error
+):
+ from openviking.privacy import session_extractor
+
+ session = await service.sessions.create(ctx, "privacy-write-failure")
+ await service.privacy_configs.upsert(
+ ctx, "session", session.session_id, {"taken001": "old-secret"}
+ )
+ if error is ResourceExhaustedError:
+ monkeypatch.setattr(session_extractor, "token_urlsafe", lambda _: "taken001")
+ else:
+ monkeypatch.setattr(
+ service.privacy_configs,
+ "insert_values",
+ AsyncMock(side_effect=OSError("storage unavailable")),
+ )
+ externalize = AsyncMock()
+ monkeypatch.setattr(session._tool_outputs, "externalize_group", externalize)
+ with pytest.raises(error):
+ await session.add_message_async("user", [TextPart("password=new-secret")])
+ externalize.assert_not_awaited()
+ assert await service.viking_fs.read_file(session.uri + "/messages.jsonl", ctx=ctx) == ""
+ current = await service.privacy_configs.get_current(ctx, "session", session.session_id)
+ assert current.values == {"taken001": "old-secret"}
+ assert await service.privacy_configs.list_versions(ctx, "session", session.session_id) == [1]
+
+
+async def test_values_equal_to_json_keys_do_not_change_message_identity(service, ctx):
+ session = await service.sessions.create(ctx, "identity")
+ original = {"password": "tool_input", "token": "assistant", "secret": "default"}
+ await session.add_message_async("assistant", [ToolPart(tool_input=original)])
+ # A full rewrite takes a different storage path than append.
+ await session._write_to_agfs_async(session.messages)
+ reloaded = await service.sessions.get(session.session_id, ctx)
+ assert reloaded.messages[0].role == "assistant"
+ assert isinstance(reloaded.messages[0].parts[0], ToolPart)
+ restored = json.loads(await service.fs.read(session.uri + "/messages.jsonl", ctx=ctx))
+ assert restored["role"] == "assistant"
+ assert restored["parts"][0]["tool_input"] == original
+ archive = session.uri + "/history/archive_001"
+ await session._merge_archive_meta(archive, {"phase1": {"user": ctx.user.to_dict()}})
+ saved = json.loads(await service.viking_fs.read_file(archive + "/.meta.json", ctx=ctx))
+ assert saved["phase1"]["user"] == ctx.user.to_dict()
+ await session._write_done_file(archive, "default", "default")
+ done = json.loads(await service.viking_fs.read_file(archive + "/.done", ctx=ctx))
+ assert done["starting_message_id"] == "default"
+
+
+async def test_repeated_explicit_references_restore_exact_types_without_new_fields(service, ctx):
+ session = await service.sessions.create(ctx, "repeated")
+ values = {
+ "short": "a",
+ "number": 1234,
+ "object": {"a": [False, None]},
+ "named-field": "existing-session-secret",
+ }
+ await service.privacy_configs.upsert(ctx, "session", session.session_id, values)
+ row = {
+ key: build_privacy_field_reference(ctx.user.user_id, "session", session.session_id, field)
+ for key, field in [("password", "short"), ("token", "number"), ("secret", "object")]
+ }
+ await session.add_message_async(
+ "assistant",
+ [ToolPart(tool_input={"rows": [row] * 1300}), TextPart("password=existing-session-secret")],
+ )
+ current = await service.privacy_configs.get_current(ctx, "session", session.session_id)
+ assert current.values == values
+ restored = json.loads(await service.fs.read(session.uri + "/messages.jsonl", ctx=ctx))
+ assert (
+ restored["parts"][0]["tool_input"]["rows"]
+ == [{"password": "a", "token": 1234, "secret": {"a": [False, None]}}] * 1300
+ )
+ assert restored["parts"][1]["text"] == "password=existing-session-secret"
+
+
+async def test_restore_leaves_foreign_missing_and_nested_references_unchanged(
+ service, ctx, monkeypatch
+):
+ own = build_privacy_field_reference(ctx.user.user_id, "credential", "demo", "pat")
+ missing = build_privacy_field_reference(ctx.user.user_id, "credential", "demo", "missing")
+ unconfigured = build_privacy_field_reference(ctx.user.user_id, "credential", "absent", "pat")
+ foreign = build_privacy_field_reference("alice", "credential", "demo", "pat")
+ nested = build_privacy_field_reference(ctx.user.user_id, "credential", "other", "pat")
+ await service.privacy_configs.upsert(ctx, "credential", "demo", {"pat": nested})
+ await service.privacy_configs.upsert(ctx, "credential", "other", {"pat": "nested-secret"})
+ session = await service.sessions.create(ctx, "reference-boundary")
+ await session.add_message_async("user", [TextPart(f"{own} {missing} {unconfigured} {foreign}")])
+ read = AsyncMock(wraps=service.privacy_configs.get_current)
+ monkeypatch.setattr(service.privacy_configs, "get_current", read)
+ restored = json.loads(await service.fs.read(session.uri + "/messages.jsonl", ctx=ctx))
+ assert restored["parts"][0]["text"] == f"{nested} {missing} {unconfigured} {foreign}"
+ assert read.await_count == 2 # One read per target, not per occurrence.
+ read.assert_any_await(ctx, "credential", "absent")
+
+
+async def test_later_credential_registration_preserves_session_reference_identity(
+ client, service, ctx
+):
+ value = "shared-managed-secret"
+ first = await service.sessions.create(ctx, "first")
+ await first.add_message_async("user", [TextPart(f"password={value}")])
+ first_uri = first.uri + "/messages.jsonl"
+ stored = await service.viking_fs.read_file(first_uri, ctx=ctx)
+ current = await service.privacy_configs.get_current(ctx, "session", "first")
+ [field] = current.values
+ assert json.loads(stored)["parts"][0]["text"] == (
+ f"password={build_session_placeholder('first', field)}"
+ )
+
+ await service.privacy_configs.upsert(ctx, "credential", "managed", {"key": value})
+ credential = build_privacy_field_reference(ctx.user.user_id, "credential", "managed", "key")
+ second = await service.sessions.create(ctx, "second")
+ await second.add_message_async(
+ "assistant", [TextPart(f"password={value}"), ToolPart(tool_input={"password": value})]
+ )
+ assert second.messages[0].parts[0].text == f"password={credential}"
+ assert second.messages[0].parts[1].tool_input == {"password": credential}
+
+ visible = await client.get("/api/v1/content/read", params={"uri": first_uri})
+ assert visible.status_code == 200, visible.text
+ assert visible.json()["result"] == stored
+
+ await service.privacy_configs.patch_values(ctx, "credential", "managed", {"key": "rotated-key"})
+ for session, expected in [(first, value), (second, "rotated-key")]:
+ read = await client.get(
+ "/api/v1/content/read", params={"uri": session.uri + "/messages.jsonl", "raw": True}
+ )
+ assert read.status_code == 200, read.text
+ assert json.loads(read.json()["result"])["parts"][0]["text"] == f"password={expected}"
+ assert await service.viking_fs.read_file(first_uri, ctx=ctx) == stored
+
+
+async def test_cross_session_reuse_requires_full_reference_but_short_reference_stays_local(
+ service, ctx
+):
+ source = await service.sessions.create(ctx, "source")
+ original = "password=cross-session-secret"
+ await source.add_message_async("user", [TextPart(original)])
+ current = await service.privacy_configs.get_current(ctx, "session", "source")
+ [field] = current.values
+ short = build_session_placeholder("source", field)
+ full = build_privacy_field_reference(ctx.user.user_id, "session", "source", field)
+ target = await service.sessions.create(ctx, "target")
+ await target.add_message_async("user", [TextPart(f"{original} {short}")])
+ assert target.messages[0].parts[0].text == f"password={full} {short}"
+ raw = json.loads(await service.fs.read(target.uri + "/messages.jsonl", ctx=ctx))
+ assert raw["parts"][0]["text"] == f"{original} {short}"
+ assert await service.privacy_configs.get_current(ctx, "session", "target") is None
+
+
+async def test_short_reference_resolves_only_current_users_session_config(service):
+ field = "AbCd1234"
+ short = build_session_placeholder("same-id", field)
+ for user in ["alice", "bob"]:
+ ctx = RequestContext(user=UserIdentifier("default", user), role=Role.USER)
+ await service.initialize_user_directories(ctx)
+ await service.privacy_configs.upsert(ctx, "session", "same-id", {field: f"{user}-private"})
+ session = await service.sessions.create(ctx, "same-id")
+ await session.add_message_async("user", [TextPart(short)])
+ restored = json.loads(await service.fs.read(session.uri + "/messages.jsonl", ctx=ctx))
+ assert restored["parts"][0]["text"] == f"{user}-private"
+ alice = RequestContext(user=UserIdentifier("default", "alice"), role=Role.USER)
+ restored = await service.fs.read(
+ "viking://user/alice/sessions/same-id/messages.jsonl", ctx=alice
+ )
+ assert json.loads(restored)["parts"][0]["text"] == "alice-private"
diff --git a/tests/unit/session/test_privacy.py b/tests/unit/session/test_privacy.py
new file mode 100644
index 000000000..34f6b1a85
--- /dev/null
+++ b/tests/unit/session/test_privacy.py
@@ -0,0 +1,197 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Session privacy round-trips complete messages and rejects unsafe input."""
+
+import json
+import re
+from copy import deepcopy
+from dataclasses import asdict
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from openviking.message.part import ContextPart, ImagePart, TextPart, ToolPart
+from openviking.privacy import session_extractor as extraction
+from openviking.privacy.session_extractor import extract_session_privacy_values
+from openviking.privacy.session_restore import get_session_id_from_uri, restore_session_content
+from openviking_cli.exceptions import InvalidArgumentError, ResourceExhaustedError
+
+
+def message_jsonl(specs):
+ return (
+ "\n".join(
+ json.dumps(
+ {**spec, "parts": [asdict(part) for part in spec["parts"]]}, ensure_ascii=False
+ )
+ for spec in specs
+ )
+ + "\n"
+ )
+
+
+def privacy():
+ return SimpleNamespace(get_current=AsyncMock())
+
+
+async def test_extract_and_restore_complete_messages(privacy, request_context):
+ specs = [
+ {
+ "role": "user",
+ "parts": [
+ TextPart("password='中文密码'"),
+ ContextPart(uri="viking://resource/doc", abstract="api_key=abstract-secret"),
+ ImagePart(url="https://example.test/password=image-reference"),
+ ],
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ ToolPart(
+ tool_input={
+ "credentials": {
+ "password": 'quote" and\nnewline',
+ "nested": [1, False, None],
+ },
+ "password": [],
+ "token": 1234,
+ "secret": {},
+ "nested": {"password": "another-secret"},
+ "region": "cn",
+ },
+ tool_output="password='hello world'",
+ tool_output_externalization_error="api_key=error-secret",
+ ),
+ ToolPart(tool_id="pending", tool_output=None),
+ ],
+ },
+ ]
+ before = deepcopy(specs)
+ sanitized, values = extract_session_privacy_values("demo", specs)
+ assert all(re.fullmatch(r"[A-Za-z0-9_-]{8}", key) for key in values)
+ # Sensitive containers are captured whole, with no references inside them.
+ assert list(values.values()) == [
+ "中文密码",
+ "abstract-secret",
+ specs[1]["parts"][0].tool_input["credentials"],
+ [],
+ 1234,
+ {},
+ "another-secret",
+ "hello world",
+ "error-secret",
+ ]
+ assert specs == before
+ clean = message_jsonl(sanitized)
+ for secret in ["中文密码", "abstract-secret", "another-secret", "hello world", "error-secret"]:
+ assert secret not in clean
+ privacy.get_current.return_value = SimpleNamespace(values=values)
+ assert await restore_session_content(
+ privacy, clean, request_context, session_id="demo", jsonl=True
+ ) == message_jsonl(before)
+ specs[1]["parts"][0].tool_input["credentials"]["nested"].append("changed")
+ assert "changed" not in json.dumps(list(values.values()))
+
+
+async def test_batch_field_id_collision_preserves_both_values(
+ monkeypatch, privacy, request_context
+):
+ ids = iter(["same0001", "same0001", "next0002"])
+ monkeypatch.setattr(extraction, "token_urlsafe", lambda _: next(ids))
+ specs = [{"parts": [ToolPart(tool_input={"password": "first", "api_key": "second"})]}]
+ protected, values = extract_session_privacy_values("demo", specs)
+ assert sorted(values.values()) == ["first", "second"]
+ privacy.get_current.return_value = SimpleNamespace(values=values)
+ assert await restore_session_content(
+ privacy, message_jsonl(protected), request_context, session_id="demo", jsonl=True
+ ) == message_jsonl(specs)
+
+
+def test_exhausted_field_ids_reject_without_mutating_input(monkeypatch):
+ monkeypatch.setattr(extraction, "token_urlsafe", lambda _: "same0001")
+ specs = [{"parts": [ToolPart(tool_input={"password": "first", "api_key": "second"})]}]
+ before = deepcopy(specs)
+ with pytest.raises(ResourceExhaustedError, match="unique Session privacy field IDs"):
+ extract_session_privacy_values("demo", specs)
+ assert specs == before
+
+
+async def test_sensitive_field_names_do_not_leak_into_references(privacy, request_context):
+ key = "sk-proj-12345678901234567890_api_key"
+ specs = [{"parts": [ToolPart(tool_input={key: "secret-value"})]}]
+ sanitized, values = extract_session_privacy_values("demo", specs)
+ assert key not in message_jsonl(sanitized)
+ privacy.get_current.return_value = SimpleNamespace(values=values)
+ assert await restore_session_content(
+ privacy, message_jsonl(sanitized), request_context, session_id="demo", jsonl=True
+ ) == message_jsonl(specs)
+
+
[email protected]("sensitive", [False, True], ids=["nested-input", "sensitive-container"])
+ "limit,bound",
+ [
+ ("MAX_TEXT_CHARS", 20),
+ ("MAX_BATCH_CHARS", 20),
+ ("MAX_NODES", 4),
+ ("MAX_MATCHES", 1),
+ ("MAX_DEPTH", 1),
+ ],
+)
+def test_limits_reject_batch_without_mutating_input(monkeypatch, limit, bound, sensitive):
+ monkeypatch.setattr(extraction, limit, bound)
+ value = {"a": {"password": "secret-value" * 4}}
+ specs = [
+ {
+ "parts": [
+ ToolPart(
+ tool_input={"credentials": value} if sensitive else value,
+ tool_output="password=another-secret",
+ )
+ ]
+ }
+ ]
+ before = deepcopy(specs)
+ with pytest.raises(InvalidArgumentError) as exc:
+ extract_session_privacy_values("demo", specs)
+ assert "secret-value" not in str(exc.value)
+ assert specs == before
+
+
[email protected]("kind", ["cycle", "non-string-key", "unsupported-value"])
+def test_invalid_sensitive_container_is_rejected(kind):
+ value = {"cycle": {}, "non-string-key": {1: "secret"}, "unsupported-value": {"x": object()}}[
+ kind
+ ]
+ if kind == "cycle":
+ value["self"] = value
+ with pytest.raises(InvalidArgumentError):
+ extract_session_privacy_values(
+ "demo", [{"parts": [ToolPart(tool_input={"credentials": value})]}]
+ )
+
+
+ "owner,path,expected",
+ [
+ ("alice", "messages.jsonl", "demo"),
+ ("alice", "history/archive_001/messages.jsonl", "demo"),
+ ("alice", "tool-results/tool-1/output.txt", "demo"),
+ ("alice", ".meta.json", None),
+ ("alice", "history/archive_001/.overview.md", None),
+ ("alice", "tool-results/tool-1/meta.json", None),
+ ("bob", "messages.jsonl", None),
+ ],
+)
+def test_restore_is_scoped_to_session_content(owner, path, expected):
+ root = "viking://user/alice/sessions"
+ assert get_session_id_from_uri(f"viking://user/{owner}/sessions/demo/{path}", root) == expected
+
+
[email protected]("content", ["not json", '{"parts": null}'])
+async def test_invalid_message_jsonl_is_rejected(privacy, request_context, content):
+ with pytest.raises(InvalidArgumentError):
+ await restore_session_content(
+ privacy, content, request_context, session_id="demo", jsonl=True
+ )
diff --git a/tests/unit/session/test_session_commit_resume.py b/tests/unit/session/test_session_commit_resume.py
index 716b39b3c..1ae18e66a 100644
--- a/tests/unit/session/test_session_commit_resume.py
+++ b/tests/unit/session/test_session_commit_resume.py
@@ -73,7 +73,7 @@ class _MemoryVikingFS:
return content.decode("utf-8") if isinstance(content, bytes) else content
async def write_file(self, uri, content, ctx=None, lease_ref=None):
- self.files[uri] = content
+ self.files[uri] = content.decode("utf-8") if isinstance(content, bytes) else content
async def append_file(self, uri, content, ctx=None):
self.files[uri] += content
diff --git a/tests/unit/test_privacy_rules.py b/tests/unit/test_privacy_rules.py
new file mode 100644
index 000000000..e5d3d4b3f
--- /dev/null
+++ b/tests/unit/test_privacy_rules.py
@@ -0,0 +1,140 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Credential rules distinguish secrets from business values and references."""
+
+import pytest
+
+from openviking.privacy.rules import find_privacy_matches
+
+BODY = "abcd012345678901234567890123wxyz"
+
+
+def matched_values(content):
+ return [content[match.start : match.end] for match in find_privacy_matches(content)]
+
+
+ "secret",
+ [
+ prefix + BODY
+ for prefix in (
+ "sk-",
+ "sk-proj-",
+ "sk-svcacct-",
+ "sk-ant-api03-",
+ "ak-",
+ "ark-",
+ "AKLT",
+ "AKTP",
+ "ghp_",
+ "gho_",
+ "ghu_",
+ "ghs_",
+ "ghr_",
+ "github_pat_",
+ )
+ ]
+ + ["AKIAABCDEFGHIJKLMNOP", "ASIAABCDEFGHIJKLMNOP"],
+)
+def test_known_credentials_in_free_text(secret):
+ assert matched_values(f"凭据:{secret};不要改动这些说明。") == [secret]
+
+
+ "syntax",
+ [
+ 'api_key="{value}"',
+ '"clientSecret": "{value}"',
+ "api key:'{value}'",
+ 'os.environ["AWS_SECRET_ACCESS_KEY"] = "{value}"',
+ "VOLCENGINE_SECRET_ACCESS_KEY={value}",
+ "MY-API-KEY={value}",
+ "EVAL_ARK_API_KEY={value}",
+ "DB_PASSWORD={value}",
+ "AccessKeySecret={value}",
+ "SLACK_BOT_TOKEN={value}",
+ "privateKey={value}",
+ "Authorization: Bearer {value}",
+ "Proxy-Authorization: Basic {value}",
+ "Authorization: basic {value}",
+ '"Authorization": "Basic {value}"',
+ "'Proxy-Authorization': 'Basic {value}'",
+ "**Authorization: Basic {value}**",
+ ],
+)
+def test_named_fields_capture_only_value(syntax):
+ content = syntax.format(value=BODY)
+ assert matched_values(content) == [BODY]
+
+
+ "command,secret",
+ [
+ (f"run --api-key={BODY} --limit=10", BODY),
+ (f"run --api-key {BODY} --limit 10", BODY),
+ (f"run --access-key-secret '{BODY}'", BODY),
+ (f"curl --oauth2-bearer {BODY} url", BODY),
+ (f"curl -uuser:{BODY} url", f"user:{BODY}"),
+ (f'curl -U "proxy:{BODY}" url', f"proxy:{BODY}"),
+ ("curl --authorization 'Basic demo-secret'", "demo-secret"),
+ ("run --password 'two words' --limit 10", "two words"),
+ ('run --password "true" --limit 10', "true"),
+ (r"run --password two\ words --limit 10", r"two\ words"),
+ ('run --password pre"two words"post --limit 10', 'pre"two words"post'),
+ ('run --password "escaped\\"value" --limit 10', 'escaped\\"value'),
+ ("run --api-key \\\n " + BODY, BODY),
+ ],
+)
+def test_cli_credentials_without_expansion(command, secret):
+ assert matched_values(command) == [secret]
+
+
+def test_field_context_does_not_replace_same_value_in_prose():
+ content = 'password="prod"\nThe prod configuration uses region=cn and max_tokens=8192.'
+ [match] = find_privacy_matches(content)
+ assert content[match.start : match.end] == "prod"
+ assert content[match.end :] == '"\nThe prod configuration uses region=cn and max_tokens=8192.'
+
+
+ "content",
+ [
+ "region=cn; max_tokens=8192; token_count=42; cache_key=cache-key",
+ "base_url=https://example.test; project=prod; collection=default",
+ "sk-example ark-example",
+ 'api_key="${API_KEY}"; password=$PASSWORD',
+ "api_key=${API_KEY}; password=${DB_PASSWORD}",
+ 'curl --user alice --password --output result.json --user-agent "test client"',
+ "{{ov_privacy:skill:sk-" + BODY + ":token}}",
+ ],
+)
+def test_noncredentials_and_references_are_preserved(content):
+ assert matched_values(content) == []
+
+
+ "content,secret",
+ [
+ ("password=*", "*"),
+ ('password="***"', "***"),
+ ("run --password '[REDACTED]'", "[REDACTED]"),
+ ("Authorization: Bearer ab****yz", "ab****yz"),
+ ("Proxy-Authorization: Basic sk-ab****yz", "sk-ab****yz"),
+ ("run --authorization 'Bearer ***'", "***"),
+ ],
+)
+def test_mask_like_credentials_are_extracted(content, secret):
+ assert matched_values(content) == [secret]
+
+
+ "content",
+ [
+ "This is a basic example of configuration.",
+ "Basic usage",
+ "Use basic Python syntax.",
+ "Basic dXNlcjpwYXNz",
+ ],
+)
+def test_basic_without_authentication_context_is_not_a_credential(content):
+ assert matched_values(content) == []
diff --git a/tests/unit/test_privacy_sanitizer.py b/tests/unit/test_privacy_sanitizer.py
index a0014ec6b..ea47708ca 100644
--- a/tests/unit/test_privacy_sanitizer.py
+++ b/tests/unit/test_privacy_sanitizer.py
@@ -1,6 +1,7 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+import asyncio
from types import SimpleNamespace
import pytest
@@ -14,7 +15,7 @@ from openviking.privacy.reference import (
)
from openviking.privacy.sanitizer import PrivacySanitizer
from openviking.server.identity import RequestContext, Role
-from openviking_cli.exceptions import ResourceExhaustedError
+from openviking_cli.exceptions import InvalidArgumentError, ResourceExhaustedError
from openviking_cli.session.user_id import UserIdentifier
@@ -43,17 +44,10 @@ def _ctx(user_id="alice"):
return RequestContext(user=UserIdentifier("account-a", user_id), role=Role.USER)
-def test_privacy_sanitizer_uses_native_ragfs_matcher():
- sanitizer = PrivacySanitizer(_PrivacyCatalog())
- assert sanitizer._matcher_class.__module__ == "ragfs_python"
- assert sanitizer._matcher_class.__name__ == "PrivacyMatcher"
-
-
def test_privacy_reference_roundtrip_encodes_individual_segments():
rendered = build_privacy_field_reference("alice", "custom-config", "prod-key", "api/key")
assert rendered == (
- "{{ov_privacy:alice:viking://~/privacy/custom-config/"
- "prod-key#/values/api%2Fkey}}"
+ "{{ov_privacy:alice:viking://~/privacy/custom-config/prod-key#/values/api%2Fkey}}"
)
assert parse_privacy_field_reference(rendered) == PrivacyFieldReference(
owner_user_id="alice",
@@ -233,3 +227,96 @@ async def test_sanitizer_never_rewrites_privacy_storage_itself():
assert result.content == "secret"
assert not result.changed
assert catalog.build_reads == 0
+
+
+async def test_prepared_matcher_returns_original_offsets_in_worker_thread():
+ catalog = _PrivacyCatalog({"credential": {"service": {"key": "secret", "long_key": "secrets"}}})
+ find = await PrivacySanitizer(catalog).prepare_matcher(_ctx())
+ reference = build_privacy_field_reference("alice", "credential", "service", "key")
+ text = f"前缀🙂secrets {reference} secret"
+
+ matches = await asyncio.to_thread(find, text)
+
+ assert [(item.start, item.end, item.reference) for item in matches] == [
+ (3, 10, build_privacy_field_reference("alice", "credential", "service", "long_key")),
+ (len(text) - 6, len(text), reference),
+ ]
+
+
[email protected]("text", ["abcdef", "中文"])
+async def test_prepared_matcher_enforces_utf8_byte_limit_with_empty_catalog(text):
+ find = await PrivacySanitizer(_PrivacyCatalog(), max_content_bytes=6).prepare_matcher(_ctx())
+
+ assert find(text) == []
+ with pytest.raises(ResourceExhaustedError, match="size limit"):
+ find(text + "a")
+
+
+async def test_prepared_matcher_rejects_dense_or_ambiguous_matches():
+ catalog = _PrivacyCatalog({"credential": {"service": {"key": "secret"}}})
+ find = await PrivacySanitizer(catalog, max_replacements=2).prepare_matcher(_ctx())
+
+ assert len(find("secret secret")) == 2
+ with pytest.raises(ResourceExhaustedError, match="replacement limit"):
+ find("secret secret secret")
+
+ catalog.configs["credential"]["other"] = {"key": "secret"}
+ catalog.revision += 1
+ find = await PrivacySanitizer(catalog).prepare_matcher(_ctx())
+ with pytest.raises(InvalidArgumentError, match="multiple fields"):
+ find("secret")
+
+
+async def test_prepared_matcher_rejects_unpaired_surrogates():
+ find = await PrivacySanitizer(_PrivacyCatalog()).prepare_matcher(_ctx())
+
+ with pytest.raises(UnicodeEncodeError):
+ find("invalid \ud800")
+
+
+ "credentials,ordinary,expected",
+ [
+ (1, 2, ("credential", "target-0")),
+ (2, 1, None),
+ (0, 2, None),
+ ],
+)
+async def test_credential_preference_selects_only_an_unambiguous_field(
+ credentials, ordinary, expected
+):
+ configs = {
+ category: {f"target-{i}": {"key": "shared-secret"} for i in range(count)}
+ for category, count in [("credential", credentials), ("session", ordinary)]
+ }
+ sanitizer = PrivacySanitizer(_PrivacyCatalog(configs))
+ find = await sanitizer.prepare_matcher(_ctx(), prefer_credentials=True)
+ if expected is None:
+ with pytest.raises(InvalidArgumentError, match="multiple fields"):
+ find("shared-secret")
+ else:
+ assert [hit.reference for hit in find("shared-secret")] == [
+ build_privacy_field_reference("alice", *expected, "key")
+ ]
+
+
+async def test_matcher_cache_separates_policies_and_refreshes_both_after_rotation():
+ catalog = _PrivacyCatalog(
+ {
+ "credential": {"managed": {"key": "shared-secret"}},
+ "session": {"captured": {"key": "shared-secret"}},
+ }
+ )
+ sanitizer = PrivacySanitizer(catalog)
+ credential = build_privacy_field_reference("alice", "credential", "managed", "key")
+ captured = build_privacy_field_reference("alice", "session", "captured", "key")
+ for preferred in [False, True] * 2:
+ result = await sanitizer.sanitize("shared-secret", ctx=_ctx(), prefer_credentials=preferred)
+ assert result.content == (credential if preferred else "{{ov_privacy:ambiguous}}")
+ catalog.configs["credential"]["managed"]["key"] = "rotated-secret"
+ catalog.revision += 1
+ for preferred in [False, True]:
+ result = await sanitizer.sanitize(
+ "shared-secret rotated-secret", ctx=_ctx(), prefer_credentials=preferred
+ )
+ assert result.content == f"{captured} {credential}"