Skip to content

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

feat(security): add API key credential module with tests

Steven Enamakel952424cbee6f
diff --git a/crates/openhuman-core/src/security/credentials/api_key.rs b/crates/openhuman-core/src/security/credentials/api_key.rs
new file mode 100644
index 0000000000..bb7d911f6b
--- /dev/null
+++ b/crates/openhuman-core/src/security/credentials/api_key.rs
@@ -0,0 +1,114 @@
+//! The TinyHumans **API key** credential — the only credential a library
+//! embedder holds.
+//!
+//! Library mode has no user login: no `/auth/me` round trip, no session JWT,
+//! no `exp` to track. The host hands the core one API key at runtime build
+//! time and every managed-backend request authenticates with it:
+//!
+//! * managed inference (`{api_url}/openai/v1`) sends it as
+//! `Authorization: Bearer <key>` — the OpenAI-compatible endpoint takes a
+//! bearer, and `OpenHumanBackendModel::resolve_bearer` prefers this profile
+//! over the app session;
+//! * SDK REST clients send it as `x-api-key` — `BackendOAuthClient` and
+//! `IntegrationClient` pick the header from [`BackendCredential`].
+//!
+//! The key lives in the same auth-profile store as the app session (the
+//! parent of `config.config_path`), under its own provider id, so a runtime
+//! that has both prefers the API key (see
+//! [`resolve_backend_credential`](super::session_support::resolve_backend_credential)).
+//! It is never written to `config.toml` and never logged.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use anyhow::Result;
+
+use super::core::{AuthService, DEFAULT_AUTH_PROFILE_NAME};
+use super::profiles::AuthProfile;
+use crate::config::Config;
+
+/// Provider id of the API-key auth profile.
+pub const API_KEY_PROVIDER: &str = "api-key";
+
+/// Metadata marker distinguishing the profile from any other token profile.
+pub const API_KEY_KIND_META: &str = "kind";
+/// Value of [`API_KEY_KIND_META`].
+pub const API_KEY_KIND: &str = "tinyhumans-api-key";
+
+/// Persist `key` as the active API-key profile beside `config`'s other
+/// credentials. Blank keys are rejected rather than stored.
+pub fn store_api_key(config: &Config, key: &str) -> Result<AuthProfile> {
+ store_api_key_in(
+ &super::core::state_dir_from_config(config),
+ config.secrets.encrypt,
+ key,
+ )
+}
+
+/// [`store_api_key`] against an explicit credential state directory. Used by
+/// a library runtime that must install the key *before* the core boots (the
+/// scheduler gate reads the credential store once, at boot).
+pub fn store_api_key_in(state_dir: &Path, encrypt: bool, key: &str) -> Result<AuthProfile> {
+ let key = key.trim();
+ if key.is_empty() {
+ anyhow::bail!("API key is blank");
+ }
+ let mut metadata = HashMap::new();
+ metadata.insert(API_KEY_KIND_META.to_string(), API_KEY_KIND.to_string());
+ log::debug!(
+ "[credentials][api-key] storing api-key profile state_dir={}",
+ state_dir.display()
+ );
+ AuthService::new(state_dir, encrypt).store_provider_token(
+ API_KEY_PROVIDER,
+ DEFAULT_AUTH_PROFILE_NAME,
+ key,
+ metadata,
+ true,
+ )
+}
+
+/// The stored API key, if any.
+pub fn get_api_key(config: &Config) -> Result<Option<String>> {
+ get_api_key_in(
+ &super::core::state_dir_from_config(config),
+ config.secrets.encrypt,
+ )
+}
+
+/// [`get_api_key`] against an explicit credential state directory — for
+/// callers that hold `ProviderRuntimeOptions` rather than a `Config`.
+pub fn get_api_key_in(state_dir: &Path, encrypt: bool) -> Result<Option<String>> {
+ AuthService::new(state_dir, encrypt).get_provider_bearer_token(API_KEY_PROVIDER, None)
+}
+
+/// Whether an API key is stored. Errors reading the store count as "no key"
+/// so a corrupt profile file degrades to the session path instead of
+/// panicking a hot path; the error is logged.
+pub fn has_api_key_in(state_dir: &Path, encrypt: bool) -> bool {
+ match get_api_key_in(state_dir, encrypt) {
+ Ok(key) => key.is_some(),
+ Err(e) => {
+ log::debug!("[credentials][api-key] store read failed, treating as absent: {e:#}");
+ false
+ }
+ }
+}
+
+/// Whether an API key is stored for `config`.
+pub fn has_api_key(config: &Config) -> bool {
+ has_api_key_in(
+ &super::core::state_dir_from_config(config),
+ config.secrets.encrypt,
+ )
+}
+
+/// Remove the API-key profile. Returns whether one existed.
+pub fn clear_api_key(config: &Config) -> Result<bool> {
+ log::debug!("[credentials][api-key] clearing api-key profile");
+ AuthService::from_config(config).remove_profile(API_KEY_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)
+}
+
+#[cfg(test)]
+#[path = "api_key_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/security/credentials/api_key_tests.rs b/crates/openhuman-core/src/security/credentials/api_key_tests.rs
new file mode 100644
index 0000000000..ba43d8223e
--- /dev/null
+++ b/crates/openhuman-core/src/security/credentials/api_key_tests.rs
@@ -0,0 +1,72 @@
+use super::*;
+use crate::security::credentials::session_support::{
+ resolve_backend_credential, BackendCredential,
+};
+
+fn config_in(dir: &std::path::Path) -> Config {
+ let mut config = Config::default();
+ config.config_path = dir.join("config.toml");
+ config.workspace_dir = dir.join("workspace");
+ config.secrets.encrypt = false;
+ config
+}
+
+#[test]
+fn store_then_get_round_trips_and_marks_kind() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let config = config_in(dir.path());
+ let profile = store_api_key(&config, " th_live_abc ").expect("store");
+ assert_eq!(profile.provider, API_KEY_PROVIDER);
+ assert_eq!(
+ profile.metadata.get(API_KEY_KIND_META).map(String::as_str),
+ Some(API_KEY_KIND)
+ );
+ assert_eq!(get_api_key(&config).expect("get").as_deref(), Some("th_live_abc"));
+ assert!(has_api_key(&config));
+}
+
+#[test]
+fn blank_key_is_rejected_and_nothing_is_stored() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let config = config_in(dir.path());
+ assert!(store_api_key(&config, " ").is_err());
+ assert!(!has_api_key(&config));
+ assert_eq!(get_api_key(&config).expect("get"), None);
+}
+
+#[test]
+fn clear_removes_the_profile() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let config = config_in(dir.path());
+ store_api_key(&config, "th_x").expect("store");
+ assert!(clear_api_key(&config).expect("clear"));
+ assert!(!has_api_key(&config));
+ assert!(!clear_api_key(&config).expect("clear again"));
+}
+
+#[test]
+fn api_key_wins_over_an_expired_session() {
+ use crate::security::credentials::session_support::SESSION_EXPIRES_AT_META;
+ use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};
+
+ let dir = tempfile::tempdir().expect("tempdir");
+ let config = config_in(dir.path());
+ let mut meta = std::collections::HashMap::new();
+ meta.insert(
+ SESSION_EXPIRES_AT_META.to_string(),
+ (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339(),
+ );
+ AuthService::from_config(&config)
+ .store_provider_token(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME, "jwt", meta, true)
+ .expect("store session");
+ assert!(matches!(
+ resolve_backend_credential(&config),
+ Err(e) if e.contains("SESSION_EXPIRED")
+ ));
+
+ store_api_key(&config, "th_key").expect("store key");
+ assert_eq!(
+ resolve_backend_credential(&config).expect("credential"),
+ BackendCredential::ApiKey("th_key".to_string())
+ );
+}