Skip to content

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

feat(security): refactor credentials ops into modular submodules

Steven Enamakele31fc3c40b25
diff --git a/crates/openhuman-core/src/memory/sources/schemas/cost_schemas.rs b/crates/openhuman-core/src/memory/sources/schemas/cost_schemas.rs
new file mode 100644
index 0000000000..f98029ae87
--- /dev/null
+++ b/crates/openhuman-core/src/memory/sources/schemas/cost_schemas.rs
@@ -0,0 +1,139 @@
+//! Schemas and handlers for the sync audit log, per-source cost estimate, and
+//! the monthly cost summary.
+
+use serde_json::{Map, Value};
+
+use crate::core::all::ControllerFuture;
+use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
+use crate::memory::sources::rpc;
+
+use super::{parse_value, to_json, NAMESPACE};
+
+pub(super) fn schema(function: &str) -> Option<ControllerSchema> {
+ Some(match function {
+ "sync_audit_log" => ControllerSchema {
+ namespace: NAMESPACE,
+ function: "sync_audit_log",
+ description:
+ "Sync audit history — timestamp, tokens consumed, cost, duration for each sync run.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "entries",
+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("SyncAuditEntry"))),
+ comment: "Audit entries, most recent first.",
+ required: true,
+ }],
+ },
+ "estimate_sync_cost" => ControllerSchema {
+ namespace: NAMESPACE,
+ function: "estimate_sync_cost",
+ description:
+ "Estimate the cost of syncing a source before starting. Returns item count, \
+ estimated tokens, and estimated cost in USD.",
+ inputs: vec![FieldSchema {
+ name: "source_id",
+ ty: TypeSchema::String,
+ comment: "Source id to estimate.",
+ required: true,
+ }],
+ outputs: vec![
+ FieldSchema {
+ name: "source_id",
+ ty: TypeSchema::String,
+ comment: "Echo of source id.",
+ required: true,
+ },
+ FieldSchema {
+ name: "item_count",
+ ty: TypeSchema::U64,
+ comment: "Number of items to sync.",
+ required: true,
+ },
+ FieldSchema {
+ name: "estimated_tokens",
+ ty: TypeSchema::U64,
+ comment: "Estimated input tokens.",
+ required: true,
+ },
+ FieldSchema {
+ name: "estimated_cost_usd",
+ ty: TypeSchema::F64,
+ comment: "Estimated cost in USD.",
+ required: true,
+ },
+ FieldSchema {
+ name: "budget_max_cost_usd",
+ ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
+ comment: "Configured cost cap if set.",
+ required: false,
+ },
+ FieldSchema {
+ name: "budget_max_tokens",
+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
+ comment: "Configured token cap if set.",
+ required: false,
+ },
+ ],
+ },
+ "monthly_cost_summary" => ControllerSchema {
+ namespace: NAMESPACE,
+ function: "monthly_cost_summary",
+ description: "Aggregate sync costs for the current calendar month.",
+ inputs: vec![],
+ outputs: vec![
+ FieldSchema {
+ name: "month",
+ ty: TypeSchema::String,
+ comment: "YYYY-MM.",
+ required: true,
+ },
+ FieldSchema {
+ name: "total_cost_usd",
+ ty: TypeSchema::F64,
+ comment: "Total spend in USD.",
+ required: true,
+ },
+ FieldSchema {
+ name: "total_syncs",
+ ty: TypeSchema::U64,
+ comment: "Number of sync runs.",
+ required: true,
+ },
+ FieldSchema {
+ name: "total_items",
+ ty: TypeSchema::U64,
+ comment: "Total items fetched.",
+ required: true,
+ },
+ FieldSchema {
+ name: "total_input_tokens",
+ ty: TypeSchema::U64,
+ comment: "Total input tokens.",
+ required: true,
+ },
+ FieldSchema {
+ name: "total_output_tokens",
+ ty: TypeSchema::U64,
+ comment: "Total output tokens.",
+ required: true,
+ },
+ ],
+ },
+ _ => return None,
+ })
+}
+
+pub(super) fn handle_sync_audit_log(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move { to_json(rpc::sync_audit_log_rpc().await?) })
+}
+
+pub(super) fn handle_estimate_sync_cost(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let req = parse_value::<rpc::EstimateSyncCostRequest>(Value::Object(params))?;
+ to_json(rpc::estimate_sync_cost_rpc(req).await?)
+ })
+}
+
+pub(super) fn handle_monthly_cost_summary(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move { to_json(rpc::monthly_cost_summary_rpc().await?) })
+}
diff --git a/crates/openhuman-core/src/security/credentials/ops.rs b/crates/openhuman-core/src/security/credentials/ops.rs
index e780fa8956..2d56552102 100644
--- a/crates/openhuman-core/src/security/credentials/ops.rs
+++ b/crates/openhuman-core/src/security/credentials/ops.rs
@@ -1,7 +1,30 @@
//! JSON-RPC / CLI controller surface for credentials and app session auth.
+mod composio;
+mod login_tokens;
+mod oauth;
+mod provider_credentials;
+mod session_lifecycle;
+
+pub use composio::{
+ clear_composio_api_key, get_composio_api_key, rpc_store_composio_api_key,
+ store_composio_api_key, COMPOSIO_DIRECT_PROVIDER,
+};
+pub use login_tokens::{auth_create_channel_link_token, consume_login_token};
+pub use oauth::{
+ oauth_connect, oauth_fetch_client_key, oauth_fetch_integration_tokens,
+ oauth_list_integrations, oauth_revoke_integration,
+};
+pub use provider_credentials::{
+ list_provider_credentials, list_provider_credentials_by_prefix, remove_provider_credentials,
+ store_provider_credentials,
+};
+pub use session_lifecycle::{
+ auth_get_me, auth_get_session_token_json, auth_get_state, clear_session, decrypt_secret,
+ encrypt_secret, start_login_gated_services, stop_login_gated_services, store_session,
+ store_session_with_deferred_validation,
+};
+
#[cfg(test)]
#[path = "ops_tests.rs"]
mod tests;
-include!("ops_part_01.rs");
-include!("ops_part_02.rs");
diff --git a/crates/openhuman-core/src/security/policy/policy_command/env_guard.rs b/crates/openhuman-core/src/security/policy/policy_command/env_guard.rs
new file mode 100644
index 0000000000..ac51ca24f0
--- /dev/null
+++ b/crates/openhuman-core/src/security/policy/policy_command/env_guard.rs
@@ -0,0 +1,162 @@
+//! Detection of leading inline environment-variable assignments on a shell
+//! command, and the "dangerous" subset that can redirect execution of an
+//! otherwise-allowed command (pagers, editors, loader overrides, …).
+
+/// Environment variable names that can trigger arbitrary command execution
+/// when supplied as a leading inline assignment on an otherwise-allowed
+/// command. Each name here is either a hook variable that a downstream tool
+/// will spawn as a subprocess (`GIT_PAGER`, `GIT_SSH_COMMAND`, `EDITOR`,
+/// `LESS`/`LESSOPEN`, `MANPAGER`, `BROWSER`, `BAT_PAGER`), a runtime
+/// configuration knob that affects how Python or the shell evaluate user
+/// input (`PYTHONSTARTUP`, `BASH_ENV`, `ENV`, `PROMPT_COMMAND`), or a loader
+/// override that lets an attacker inject a library into the next process
+/// (`LD_PRELOAD`, `LD_LIBRARY_PATH`, `LD_AUDIT`, `DYLD_INSERT_LIBRARIES`,
+/// `DYLD_LIBRARY_PATH`, `DYLD_FORCE_FLAT_NAMESPACE`).
+///
+/// `PATH` and `SHELL` are listed so an inline override cannot redirect
+/// resolution of any allowed binary to an attacker-controlled path. `IFS`
+/// is listed because the shell uses it for word splitting and a malicious
+/// value can hide command boundaries from later parsers.
+const DANGEROUS_ENV_PREFIXES: &[&str] = &[
+ "BASH_ENV",
+ "BAT_PAGER",
+ "BROWSER",
+ "DYLD_FORCE_FLAT_NAMESPACE",
+ "DYLD_INSERT_LIBRARIES",
+ "DYLD_LIBRARY_PATH",
+ "EDITOR",
+ "ENV",
+ "GIT_EDITOR",
+ "GIT_EXTERNAL_DIFF",
+ "GIT_EXTERNAL_FILTER",
+ "GIT_PAGER",
+ "GIT_SSH",
+ "GIT_SSH_COMMAND",
+ "IFS",
+ "LD_AUDIT",
+ "LD_LIBRARY_PATH",
+ "LD_PRELOAD",
+ "LESS",
+ "LESSCLOSE",
+ "LESSOPEN",
+ "MANOPT",
+ "MANPAGER",
+ "PAGER",
+ "PATH",
+ "PROMPT_COMMAND",
+ "PS1",
+ "PS2",
+ "PS3",
+ "PS4",
+ "PYTHONPATH",
+ "PYTHONSTARTUP",
+ "SHELL",
+ "VISUAL",
+];
+
+/// Returns true if `s` starts with one or more inline env assignments and any
+/// of the assigned names are in [`DANGEROUS_ENV_PREFIXES`].
+///
+/// Now superseded by [`has_leading_env_assignment`] for the
+/// allowlist check (which rejects ANY leading env assignment), but kept
+/// for callers that specifically want the dangerous-only signal —
+/// notably tests that pin the old DANGEROUS_ENV_PREFIXES rejection
+/// shape.
+///
+/// The allowlist validation in [`SecurityPolicy::is_command_allowed`] uses
+/// [`skip_env_assignments`] to look past the env prefix before matching the
+/// command name. That leaves a class of attacks where the bare command (e.g.
+/// `git log`) is allowlisted but the env prefix mutates how it executes (e.g.
+/// `GIT_PAGER=<cmd> git log` — `git` spawns `<cmd>` as its pager). Because
+/// the prefix is stripped before allowlisting and the shell evaluates the
+/// prefix at execution time, the bypass lands without ever touching a
+/// blocked command name.
+///
+/// Treating any dangerous prefix as a denial keeps the allowlist
+/// semantically meaningful without having to enumerate every shape of every
+/// downstream tool's hook surface.
+pub(in crate::security::policy) fn has_dangerous_env_prefix(s: &str) -> bool {
+ let mut rest = s.trim_start();
+ loop {
+ let Some(word) = rest.split_whitespace().next() else {
+ return false;
+ };
+ if !word.contains('=') {
+ return false;
+ }
+ if !word
+ .chars()
+ .next()
+ .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
+ {
+ return false;
+ }
+ let (name, _) = word.split_once('=').unwrap_or((word, ""));
+ let upper = name.to_ascii_uppercase();
+ if DANGEROUS_ENV_PREFIXES.contains(&upper.as_str()) {
+ return true;
+ }
+ rest = rest[word.len()..].trim_start();
+ }
+}
+
+/// Returns true if `s` starts with at least one inline env-var
+/// assignment of the shape `NAME=...`, where `NAME` begins with an ASCII
+/// letter or underscore. Catches the entire `GIT_SSH=…`, `SSH_ASKPASS=…`,
+/// `LD_PRELOAD=…`, `IFS=…` family — including names we haven't enumerated
+/// in [`DANGEROUS_ENV_PREFIXES`] — by treating ANY leading assignment as
+/// suspect. The allowlist already names every command we want to permit;
+/// nothing in that list needs the operator to set an env var at invoke
+/// time, so the broader gate has no false-positive surface on the
+/// approved path.
+///
+/// Used by [`SecurityPolicy::is_command_allowed`] as a structural guard
+/// alongside the existing dangerous-prefix check.
+pub(in crate::security::policy) fn has_leading_env_assignment(s: &str) -> bool {
+ let Some(word) = s.split_whitespace().next() else {
+ return false;
+ };
+ let Some((name, _value)) = word.split_once('=') else {
+ return false;
+ };
+ if name.is_empty() {
+ return false;
+ }
+ // Identifier shape: first char letter or `_`, the rest alphanumeric
+ // or `_`. Anything else (e.g. `foo[bar]=`) is not a shell assignment.
+ let mut chars = name.chars();
+ let first = match chars.next() {
+ Some(c) => c,
+ None => return false,
+ };
+ if !(first.is_ascii_alphabetic() || first == '_') {
+ return false;
+ }
+ if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
+ return false;
+ }
+ true
+}
+
+/// Skip leading environment variable assignments (e.g. `FOO=bar cmd args`).
+/// Returns the remainder starting at the first non-assignment word.
+pub(in crate::security::policy) fn skip_env_assignments(s: &str) -> &str {
+ let mut rest = s;
+ loop {
+ let Some(word) = rest.split_whitespace().next() else {
+ return rest;
+ };
+ // Environment assignment: contains '=' and starts with a letter or underscore
+ if word.contains('=')
+ && word
+ .chars()
+ .next()
+ .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
+ {
+ // Advance past this word
+ rest = rest[word.len()..].trim_start();
+ } else {
+ return rest;
+ }
+ }
+}