Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(desktop): handle missing PII redaction in search results

Steven Enamakele0b0f1b0bd4b
diff --git a/crates/openhuman-core/src/desktop/app_state/ops/current_user_generation.rs b/crates/openhuman-core/src/desktop/app_state/ops/current_user_generation.rs
new file mode 100644
index 0000000000..f0f02a8dbc
--- /dev/null
+++ b/crates/openhuman-core/src/desktop/app_state/ops/current_user_generation.rs
@@ -0,0 +1,185 @@
+// Sign-out invalidation for the current-user caches.
+//
+// `CURRENT_USER_CACHE`, `CURRENT_USER_FAILURE` and `LAST_CURRENT_USER_SUCCESS`
+// are all keyed on `(api_base, token)`, so clearing them is not enough on its
+// own:
+// `fetch_current_user_cached` awaits the network between reading them and
+// writing them, and a refresh already in flight when sign-out lands would
+// re-publish exactly the state the sign-out removed. A generation counter,
+// read when the token is read and re-checked under each cache's own lock,
+// is what closes that window (#5758).
+
+/// Bumped by [`forget_current_user_caches`]; read by `snapshot` before it
+/// loads the session token, threaded into `fetch_current_user_cached`, and
+/// checked again under the lock before either cache is written.
+///
+/// Counting rather than flagging keeps two overlapping sign-outs from
+/// cancelling each other out.
+static CURRENT_USER_GENERATION: AtomicU64 = AtomicU64::new(0);
+
+/// Serializes session-profile mutation with pending-session persistence. The
+/// generation check must cover the profile write itself, not only the work
+/// that prepares its input, or logout can bump the generation between the
+/// check and `store_provider_token`.
+pub static CURRENT_USER_SESSION_MUTATION_LOCK: Lazy<tokio::sync::Mutex<()>> =
+ Lazy::new(|| tokio::sync::Mutex::new(()));
+
+/// The failure write itself, taking the guard rather than the lock, so a caller
+/// that must decide *under* the lock can do so without re-entering it.
+fn record_current_user_failure_locked(
+ failure: &mut Option<CurrentUserFailure>,
+ api_base: &str,
+ token: &str,
+ error: CurrentUserFetchError,
+) {
+ let consecutive = match failure.as_ref() {
+ Some(entry) if entry.api_base == api_base && entry.token == token => {
+ entry.consecutive.saturating_add(1)
+ }
+ _ => 1,
+ };
+ *failure = Some(CurrentUserFailure {
+ api_base: api_base.to_string(),
+ token: token.to_string(),
+ failed_at: Instant::now(),
+ consecutive,
+ error,
+ });
+}
+
+/// Drop every current-user cache.
+///
+/// Sign-out must forget the positive snapshot *and* the negative failure record
+/// together: signing back in with the same JWT inside their windows would
+/// otherwise replay pre-logout state — the old `/auth/me` snapshot for the rest
+/// of [`CURRENT_USER_REFRESH_TTL`], and the old error for up to
+/// [`CURRENT_USER_BACKOFF_MAX`].
+///
+/// The freshness stamp goes with them. `clear_current_user_success` already
+/// says why — "so the next account does not inherit this one's freshness"
+/// — and sign-out is exactly the case it names; until now it ran only on
+/// the deferred-rejection path (#5930).
+///
+/// Public because the canonical sign-out path lives in
+/// `security::credentials::ops::clear_session`, outside this module, and these
+/// statics are private to it.
+pub fn forget_current_user_caches() {
+ // Bump BEFORE taking either lock. That order is what makes the checks in
+ // `publish_current_user_unless_stale` and
+ // `record_current_user_failure_unless_stale` sufficient: a writer holding
+ // one of these locks either observes the bump and stands down, or read the
+ // generation before it — in which case its write necessarily completed and
+ // released the lock before the clear below could acquire it, so the clear
+ // lands second and wins. There is no interleaving that leaves pre-logout
+ // state behind.
+ CURRENT_USER_GENERATION.fetch_add(1, Ordering::SeqCst);
+ *CURRENT_USER_CACHE.lock() = None;
+ clear_current_user_failure();
+ clear_current_user_success();
+}
+
+/// The sign-out generation a refresh must still be running under to publish.
+fn current_user_generation() -> u64 {
+ CURRENT_USER_GENERATION.load(Ordering::SeqCst)
+}
+
+/// Record an availability failure only if `generation` is still current,
+/// **checked while holding the failure lock**.
+///
+/// Checking before the lock would be a check-then-act: sign-out could land in
+/// the gap and this write would then restore the negative cache it had just
+/// cleared.
+fn record_current_user_failure_unless_stale(
+ generation: u64,
+ api_base: &str,
+ token: &str,
+ error: CurrentUserFetchError,
+) -> bool {
+ if !error.is_availability_failure() {
+ return true;
+ }
+ let mut failure = CURRENT_USER_FAILURE.lock();
+ if current_user_generation() != generation {
+ return false;
+ }
+ record_current_user_failure_locked(&mut failure, api_base, token, error);
+ true
+}
+
+/// Stamp a refreshed user's freshness only if `generation` is still current,
+/// **checked while holding the success lock** — the same check-then-act the
+/// failure recorder avoids, for the same reason.
+fn note_current_user_success_unless_stale(generation: u64, api_base: &str, token: &str) -> bool {
+ let mut success = LAST_CURRENT_USER_SUCCESS.lock();
+ if current_user_generation() != generation {
+ return false;
+ }
+ note_current_user_success_locked(&mut success, api_base, token);
+ true
+}
+
+/// Clear the failure record only while the refresh still belongs to the
+/// current session generation.
+fn clear_current_user_failure_unless_stale(generation: u64) -> bool {
+ let mut failure = CURRENT_USER_FAILURE.lock();
+ if current_user_generation() != generation {
+ return false;
+ }
+ *failure = None;
+ true
+}
+
+/// Publish a fresh `/auth/me` answer to the positive cache, and drop any
+/// recorded outage, only if `generation` is still current — each check taken
+/// under the lock that guards the record it gates.
+///
+/// Returns `false` when sign-out won, in which case nothing was written.
+fn publish_current_user_unless_stale(
+ generation: u64,
+ api_base: &str,
+ token: &str,
+ fetched: Option<Value>,
+) -> bool {
+ // Only a refreshed *user* makes the displayed data fresh: the backend can
+ // answer 200 with no user, and the caller then falls back to `stored_user`,
+ // so stamping here would report an age of ~0s for data that never changed.
+ //
+ // Taken before the cache lock and never inside it, because `ops_staleness`
+ // requires that `LAST_CURRENT_USER_SUCCESS` never nest inside
+ // `CURRENT_USER_CACHE`. Standing down here ends the publish: if sign-out has
+ // landed, none of the three records may be written.
+ if fetched.is_some() && !note_current_user_success_unless_stale(generation, api_base, token) {
+ return false;
+ }
+
+ {
+ let mut cache = CURRENT_USER_CACHE.lock();
+ if current_user_generation() != generation {
+ return false;
+ }
+ match fetched {
+ Some(user) => {
+ debug!("{LOG_PREFIX} refreshed current user from backend");
+ *cache = Some(CachedCurrentUser {
+ api_base: api_base.to_string(),
+ token: token.to_string(),
+ fetched_at: Instant::now(),
+ user,
+ });
+ }
+ None => {
+ debug!("{LOG_PREFIX} backend returned empty current user; clearing cache");
+ *cache = None;
+ }
+ }
+ }
+
+ // Clearing only ever removes state, so it cannot replay a pre-logout answer
+ // — but it could erase an outage a *new* session recorded after signing back
+ // in, so it takes the same guard.
+ let mut failure = CURRENT_USER_FAILURE.lock();
+ if current_user_generation() == generation {
+ *failure = None;
+ }
+ true
+}
diff --git a/crates/openhuman-core/src/memory/safety/pii.rs b/crates/openhuman-core/src/memory/safety/pii.rs
index 78134838d9..b88744b3a4 100644
--- a/crates/openhuman-core/src/memory/safety/pii.rs
+++ b/crates/openhuman-core/src/memory/safety/pii.rs
@@ -22,3 +22,15 @@ mod normalize;
mod patterns;
pub(super) use patterns::{has_likely_email, has_likely_pii, redact_pii};
+
+// Flattened test-only re-exports so `safety_tests.rs` and its own submodules
+// can exercise the internals directly (checksum validators, the
+// normalization pass) the same way they could when everything lived in one
+// `include!`-spliced scope.
+#[cfg(test)]
+pub(super) use checksums::{
+ digits, valid_cnpj, valid_cpf, valid_cuit, valid_dni_es, valid_iban, valid_luhn,
+ valid_nie_es, valid_nino, valid_ssn, valid_verhoeff,
+};
+#[cfg(test)]
+pub(super) use normalize::{scan_candidates, NormalizedView};
diff --git a/crates/openhuman-core/src/search/tools/tavily/types.rs b/crates/openhuman-core/src/search/tools/tavily/types.rs
index a75dc1ca8c..bbda90c7be 100644
--- a/crates/openhuman-core/src/search/tools/tavily/types.rs
+++ b/crates/openhuman-core/src/search/tools/tavily/types.rs
@@ -2,6 +2,7 @@
//! helpers shared by the client and both tools.
use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
const IMAGE_DESCRIPTION_MAX_CHARS: usize = 300;
@@ -113,7 +114,7 @@ pub struct TavilyExtractFailure {
pub error: Option<String>,
}
-fn non_empty(value: Option<&str>) -> Option<String> {
+pub(super) fn non_empty(value: Option<&str>) -> Option<String> {
value
.map(str::trim)
.filter(|s| !s.is_empty())
@@ -123,7 +124,7 @@ fn non_empty(value: Option<&str>) -> Option<String> {
/// Escape a remote page title for use as a markdown link label. Titles are
/// attacker-controlled, and an unescaped `[`/`]` breaks out of the link and
/// lets a crafted page inject markdown into the agent transcript.
-fn escape_link_text(raw: &str) -> String {
+pub(super) fn escape_link_text(raw: &str) -> String {
raw.replace('\\', r"\\")
.replace('[', r"\[")
.replace(']', r"\]")
@@ -132,7 +133,7 @@ fn escape_link_text(raw: &str) -> String {
/// Render a URL as a markdown link destination. Bare parentheses (common in
/// Wikipedia URLs) terminate the destination early, so wrap in angle brackets
/// and drop the characters that would close them.
-fn escape_link_destination(raw: &str) -> String {
+pub(super) fn escape_link_destination(raw: &str) -> String {
let cleaned: String = raw
.trim()
.chars()
@@ -144,7 +145,7 @@ fn escape_link_destination(raw: &str) -> String {
/// Copy a string array argument onto the Tavily request body.
/// Copy a string array argument onto the Tavily request body.
-fn copy_domain_filter(args: &Value, from: &str, body: &mut Value) {
+pub(super) fn copy_domain_filter(args: &Value, from: &str, body: &mut Value) {
if let Some(list) = args.get(from).filter(|v| v.is_array()) {
body[from] = list.clone();
}
@@ -152,14 +153,14 @@ fn copy_domain_filter(args: &Value, from: &str, body: &mut Value) {
/// Copy an optional string argument onto the Tavily request body under the
/// same (already snake_case) key.
-fn copy_string(args: &Value, key: &str, body: &mut Value) {
+pub(super) fn copy_string(args: &Value, key: &str, body: &mut Value) {
if let Some(value) = non_empty(args.get(key).and_then(Value::as_str)) {
body[key] = json!(value);
}
}
/// Copy an optional boolean argument onto the Tavily request body.
-fn copy_bool(args: &Value, key: &str, body: &mut Value) {
+pub(super) fn copy_bool(args: &Value, key: &str, body: &mut Value) {
if let Some(value) = args.get(key).and_then(Value::as_bool) {
body[key] = json!(value);
}