use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
use tracing::{info, warn};
use aidaemon_secrets::SecretStore;
use crate::OutcomeTool as Tool;
use crate::config_file::ConfigFile;
use crate::http_request::{HttpAuthProfile, HttpAuthType, HttpRequestTool, SharedHttpProfiles};
use crate::semantics::{
ApprovalScope, OwnerApprovalNeed, ToolCallContext, ToolCallMetadata, ToolCallOutcome,
ToolCallSemantics, ToolCapabilities, ToolCollectionObservation, ToolMutationEffects,
ToolObservationEvidence, ToolSemanticFacet, ToolTargetHint, ToolTargetHintKind,
semantics_for_exact_read_actions,
};
use crate::services::OAuthStore;
const MAX_VERIFY_TIMEOUT_SECS: u64 = 60;
const DEFAULT_VERIFY_TIMEOUT_SECS: u64 = 20;
#[derive(Deserialize, Default)]
struct ManageHttpAuthArgs {
action: String,
profile: Option<String>,
auth_type: Option<String>,
allowed_domains: Option<Vec<String>>,
header_name: Option<String>,
username: Option<String>,
user_id: Option<String>,
url: Option<String>,
method: Option<String>,
timeout_secs: Option<u64>,
}
struct UpsertPlan {
doc: toml::Table,
auth_type: HttpAuthType,
allowed_domains: Vec<String>,
}
#[derive(Clone)]
struct ManualProfileResolution {
auth_type: HttpAuthType,
allowed_domains: Vec<String>,
live_profile: HttpAuthProfile,
missing_direct_fields: Vec<&'static str>,
missing_secret_fields: Vec<&'static str>,
detected_secret_fields: Vec<&'static str>,
configured_secret_fields: Vec<&'static str>,
}
impl ManualProfileResolution {
fn status_label(&self) -> &'static str {
if !self.missing_direct_fields.is_empty() || !self.missing_secret_fields.is_empty() {
"incomplete"
} else if !self.detected_secret_fields.is_empty() {
"stored-secrets-detected"
} else {
"ready"
}
}
}
fn validate_profile_name(raw: &str) -> anyhow::Result<String> {
crate::services::validate_identifier(raw, "Profile")
}
use crate::services::normalize_domains;
pub struct ManageHttpAuthTool {
config: ConfigFile,
profiles: SharedHttpProfiles,
state_store: Arc<dyn OAuthStore>,
secrets: Arc<dyn SecretStore>,
}
pub struct ProfileVerification {
pub text: String,
pub ready: bool,
}
impl From<String> for ProfileVerification {
fn from(text: String) -> Self {
Self { text, ready: true }
}
}
impl ManageHttpAuthTool {
const AUTH_PROFILE_COLLECTION_ID: &'static str = "auth_profile_collection:configured";
pub fn new(
config: ConfigFile,
profiles: SharedHttpProfiles,
state_store: Arc<dyn OAuthStore>,
secrets: Arc<dyn SecretStore>,
) -> Self {
Self {
config,
profiles,
state_store,
secrets,
}
}
fn parse_auth_type(raw: &str) -> anyhow::Result<HttpAuthType> {
match raw.trim().to_ascii_lowercase().as_str() {
"oauth1a" | "oauth_1a" | "oauth-1a" => Ok(HttpAuthType::Oauth1a),
"bearer" => Ok(HttpAuthType::Bearer),
"header" => Ok(HttpAuthType::Header),
"basic" => Ok(HttpAuthType::Basic),
other => anyhow::bail!(
"Unknown auth_type '{}'. Use one of: oauth1a, bearer, header, basic.",
other
),
}
}
fn auth_type_name(auth_type: &HttpAuthType) -> &'static str {
match auth_type {
HttpAuthType::Oauth1a => "oauth1a",
HttpAuthType::Bearer => "bearer",
HttpAuthType::Header => "header",
HttpAuthType::Basic => "basic",
}
}
fn required_secret_fields(auth_type: &HttpAuthType) -> &'static [&'static str] {
match auth_type {
HttpAuthType::Oauth1a => &[
"api_key",
"api_secret",
"access_token",
"access_token_secret",
],
HttpAuthType::Bearer => &["token"],
HttpAuthType::Header => &["header_value"],
HttpAuthType::Basic => &["password"],
}
}
fn required_direct_fields(auth_type: &HttpAuthType) -> &'static [&'static str] {
match auth_type {
HttpAuthType::Oauth1a | HttpAuthType::Bearer => &[],
HttpAuthType::Header => &["header_name"],
HttpAuthType::Basic => &["username"],
}
}
fn optional_direct_fields(auth_type: &HttpAuthType) -> &'static [&'static str] {
match auth_type {
HttpAuthType::Oauth1a => &["user_id"],
_ => &[],
}
}
fn is_direct_field_relevant(auth_type: &HttpAuthType, field: &str) -> bool {
Self::required_direct_fields(auth_type).contains(&field)
|| Self::optional_direct_fields(auth_type).contains(&field)
}
fn keychain_field_name(profile: &str, field: &str) -> String {
aidaemon_secrets::names::http_auth(profile, field)
}
async fn load_config_doc(&self) -> anyhow::Result<toml::Table> {
self.config.load_table().await
}
async fn save_config_doc(&self, doc: &toml::Table) -> anyhow::Result<()> {
self.config.save_table(doc).await
}
fn http_auth_table(doc: &toml::Table) -> Option<&toml::Table> {
doc.get("http_auth").and_then(toml::Value::as_table)
}
fn http_auth_table_mut(doc: &mut toml::Table) -> anyhow::Result<&mut toml::Table> {
doc.entry("http_auth")
.or_insert_with(|| toml::Value::Table(toml::Table::new()))
.as_table_mut()
.ok_or_else(|| anyhow::anyhow!("`http_auth` is not a table"))
}
fn profile_table<'a>(doc: &'a toml::Table, profile: &str) -> Option<&'a toml::Table> {
Self::http_auth_table(doc)?
.get(profile)
.and_then(toml::Value::as_table)
}
fn profile_table_mut<'a>(
doc: &'a mut toml::Table,
profile: &str,
) -> anyhow::Result<&'a mut toml::Table> {
Self::http_auth_table_mut(doc)?
.entry(profile.to_string())
.or_insert_with(|| toml::Value::Table(toml::Table::new()))
.as_table_mut()
.ok_or_else(|| anyhow::anyhow!("`http_auth.{}` is not a table", profile))
}
fn redact_profile_error(error: &str, profile: &HttpAuthProfile) -> String {
let mut redacted = error.to_string();
for secret in profile.credential_values() {
if secret.len() >= 4 {
redacted = redacted.replace(secret, "[REDACTED]");
}
}
redacted
}
fn read_string_field(table: &toml::Table, field: &str) -> Option<String> {
table
.get(field)
.and_then(toml::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToString::to_string)
}
fn read_allowed_domains(table: &toml::Table) -> Vec<String> {
table
.get("allowed_domains")
.and_then(toml::Value::as_array)
.map(|values| {
values
.iter()
.filter_map(|value| value.as_str())
.map(str::trim)
.filter(|value| !value.is_empty())
.map(|value| value.to_ascii_lowercase())
.collect()
})
.unwrap_or_default()
}
fn resolve_manual_profile(
&self,
profile_name: &str,
table: &toml::Table,
) -> anyhow::Result<ManualProfileResolution> {
let auth_type_raw = Self::read_string_field(table, "auth_type")
.ok_or_else(|| anyhow::anyhow!("Profile '{}' is missing auth_type", profile_name))?;
let auth_type = Self::parse_auth_type(&auth_type_raw)?;
let allowed_domains = Self::read_allowed_domains(table);
let mut missing_direct_fields = Vec::new();
if allowed_domains.is_empty() {
missing_direct_fields.push("allowed_domains");
}
for field in Self::required_direct_fields(&auth_type) {
if Self::read_string_field(table, field).is_none() {
missing_direct_fields.push(field);
}
}
let mut live_profile = HttpAuthProfile {
auth_type: auth_type.clone(),
allowed_domains: allowed_domains.clone(),
api_key: None,
api_secret: None,
access_token: None,
access_token_secret: None,
user_id: Self::read_string_field(table, "user_id"),
token: None,
header_name: Self::read_string_field(table, "header_name"),
header_value: None,
username: Self::read_string_field(table, "username"),
password: None,
};
let mut missing_secret_fields = Vec::new();
let mut detected_secret_fields = Vec::new();
let mut configured_secret_fields = Vec::new();
for field in Self::required_secret_fields(&auth_type) {
let key_name = Self::keychain_field_name(profile_name, field);
let inline_value = Self::read_string_field(table, field);
if let Some(ref value) = inline_value {
if value == "keychain" {
match self.secrets.get(&key_name) {
Ok(secret) if !secret.expose().is_empty() => {
configured_secret_fields.push(*field);
Self::set_secret_field(
&mut live_profile,
field,
Some(secret.into_exposed()),
);
}
_ => missing_secret_fields.push(*field),
}
continue;
}
configured_secret_fields.push(*field);
Self::set_secret_field(&mut live_profile, field, Some(value.clone()));
continue;
}
match self.secrets.get(&key_name) {
Ok(secret) if !secret.expose().is_empty() => {
detected_secret_fields.push(*field);
Self::set_secret_field(&mut live_profile, field, Some(secret.into_exposed()));
}
_ => missing_secret_fields.push(*field),
}
}
Ok(ManualProfileResolution {
auth_type,
allowed_domains,
live_profile,
missing_direct_fields,
missing_secret_fields,
detected_secret_fields,
configured_secret_fields,
})
}
fn set_secret_field(profile: &mut HttpAuthProfile, field: &str, value: Option<String>) {
match field {
"api_key" => profile.api_key = value,
"api_secret" => profile.api_secret = value,
"access_token" => profile.access_token = value,
"access_token_secret" => profile.access_token_secret = value,
"token" => profile.token = value,
"header_value" => profile.header_value = value,
"password" => profile.password = value,
_ => {}
}
}
async fn sync_manual_profile(
&self,
doc: &mut toml::Table,
profile_name: &str,
) -> anyhow::Result<ManualProfileResolution> {
let Some(profile_table) = Self::profile_table(doc, profile_name) else {
anyhow::bail!("Profile '{}' was not found after update", profile_name);
};
let mut resolution = self.resolve_manual_profile(profile_name, profile_table)?;
if !resolution.detected_secret_fields.is_empty() {
{
let profile_table = Self::profile_table_mut(doc, profile_name)?;
for field in &resolution.detected_secret_fields {
profile_table.insert(
(*field).to_string(),
toml::Value::String("keychain".to_string()),
);
}
}
self.save_config_doc(doc).await?;
let profile_table = Self::profile_table(doc, profile_name).ok_or_else(|| {
anyhow::anyhow!("Profile '{}' disappeared during sync", profile_name)
})?;
resolution = self.resolve_manual_profile(profile_name, profile_table)?;
}
self.profiles
.write()
.await
.insert(profile_name.to_string(), resolution.live_profile.clone());
Ok(resolution)
}
fn require_kernel_approval(
kernel_approved: Option<&ApprovalScope>,
action: &str,
) -> anyhow::Result<()> {
crate::semantics::require_call_approval(
kernel_approved,
&format!("manage_http_auth `{action}`"),
)
}
pub async fn owner_approval(&self, arguments: &Value) -> OwnerApprovalNeed {
let Ok(args) = serde_json::from_value::<ManageHttpAuthArgs>(arguments.clone()) else {
return OwnerApprovalNeed::NotNeeded;
};
let Some(profile) = args
.profile
.as_deref()
.and_then(|profile| validate_profile_name(profile).ok())
else {
return OwnerApprovalNeed::NotNeeded;
};
match args.action.as_str() {
"upsert" => match self.upsert_plan(&profile, &args).await {
Ok(Ok(plan)) => {
OwnerApprovalNeed::Ask(Self::upsert_request(&profile, &args, &plan))
}
_ => OwnerApprovalNeed::NotNeeded,
},
"remove" => match self.manual_profile_exists(&profile).await {
Ok(true) => OwnerApprovalNeed::Ask(Self::remove_request(&profile)),
_ => OwnerApprovalNeed::NotNeeded,
},
_ => OwnerApprovalNeed::NotNeeded,
}
}
fn upsert_request(
profile_name: &str,
args: &ManageHttpAuthArgs,
plan: &UpsertPlan,
) -> aidaemon_core::OwnerApprovalRequest {
aidaemon_core::OwnerApprovalRequest {
card: None,
effects: Vec::new(),
summary: format!(
"Update manual API auth profile '{}' (type={}, domains={}, user_id={})",
profile_name,
Self::auth_type_name(&plan.auth_type),
plan.allowed_domains.join(", "),
args.user_id.as_deref().unwrap_or("unchanged")
),
subject: json!({
"action": "upsert",
"profile": profile_name,
"auth_type": args.auth_type,
"allowed_domains": args.allowed_domains,
"header_name": args.header_name,
"username": args.username,
"user_id": args.user_id,
})
.to_string(),
risk: aidaemon_core::ApprovalRisk::High,
warnings: vec![
"Modifies API auth configuration".to_string(),
"Can change which domains receive credentials".to_string(),
"Changing user_id or rebinding credentials can change the remote account behind this profile. Pause or revoke affected autonomous mandates before the change, then reconfirm their account scope."
.to_string(),
],
}
}
fn remove_request(profile_name: &str) -> aidaemon_core::OwnerApprovalRequest {
aidaemon_core::OwnerApprovalRequest::plain(
format!(
"Remove manual API auth profile '{}' and delete its stored credentials",
profile_name
),
json!({"action": "remove", "profile": profile_name}).to_string(),
aidaemon_core::ApprovalRisk::High,
vec![
"Deletes API auth configuration".to_string(),
"Deletes stored credentials for this profile".to_string(),
],
)
}
pub fn effects_for(arguments: &str) -> aidaemon_core::CallEffects {
use aidaemon_core::{CallEffects, EffectClass, EffectKey};
let Ok(args) = serde_json::from_str::<ManageHttpAuthArgs>(arguments) else {
return CallEffects::unknown();
};
match args.action.as_str() {
"list" | "describe" => CallEffects::none(),
"upsert" | "remove" | "verify" => {
let mut effects = CallEffects::unknown();
if let Some(profile) = args
.profile
.as_deref()
.and_then(|profile| validate_profile_name(profile).ok())
{
effects
.keys
.push(EffectKey::named(EffectClass::Credential, &profile));
}
if args.action == "verify"
&& let Some(host) = args
.url
.as_deref()
.map(str::trim)
.filter(|url| !url.is_empty())
.and_then(crate::command_effects::url_effect)
{
effects.keys.push(host);
}
effects
}
_ => CallEffects::unknown(),
}
}
async fn manual_profile_exists(&self, profile_name: &str) -> anyhow::Result<bool> {
let doc = self.load_config_doc().await?;
Ok(Self::http_auth_table(&doc).is_some_and(|table| table.contains_key(profile_name)))
}
async fn upsert_plan(
&self,
profile_name: &str,
args: &ManageHttpAuthArgs,
) -> anyhow::Result<Result<UpsertPlan, String>> {
if self.is_oauth_managed_profile(profile_name).await? {
return Ok(Err(format!(
"Profile '{}' is already managed by OAuth. Use the OAuth flow for that service name, or choose a different manual profile name.",
profile_name
)));
}
let doc = self.load_config_doc().await?;
let existing_auth_type = Self::profile_table(&doc, profile_name)
.and_then(|table| Self::read_string_field(table, "auth_type"));
let auth_type = if let Some(ref raw) = args.auth_type {
Self::parse_auth_type(raw)?
} else if let Some(raw) = existing_auth_type {
Self::parse_auth_type(&raw)?
} else {
anyhow::bail!("action='upsert' requires auth_type when creating a new profile.");
};
let existing_allowed_domains = Self::profile_table(&doc, profile_name)
.map(Self::read_allowed_domains)
.unwrap_or_default();
let allowed_domains = if let Some(ref domains) = args.allowed_domains {
normalize_domains(domains)?
} else if !existing_allowed_domains.is_empty() {
existing_allowed_domains
} else {
anyhow::bail!("action='upsert' requires allowed_domains when creating a new profile.");
};
Ok(Ok(UpsertPlan {
doc,
auth_type,
allowed_domains,
}))
}
async fn is_oauth_managed_profile(&self, profile_name: &str) -> anyhow::Result<bool> {
Ok(self
.state_store
.get_oauth_connection(profile_name)
.await?
.is_some())
}
async fn handle_list_snapshot(&self) -> anyhow::Result<(String, Vec<ToolTargetHint>)> {
let doc = self.load_config_doc().await?;
let manual_names: Vec<String> = Self::http_auth_table(&doc)
.map(|table| table.keys().cloned().collect())
.unwrap_or_default();
let oauth_connections = self.state_store.list_oauth_connections().await?;
let mut lines = Vec::new();
let mut resource_ids = BTreeSet::new();
if manual_names.is_empty() {
lines.push("No manual API auth profiles configured yet.".to_string());
} else {
lines.push("Manual API auth profiles:".to_string());
for name in manual_names {
let resource_id = HttpRequestTool::auth_profile_resource_id(&name);
resource_ids.insert(resource_id.clone());
let table = Self::profile_table(&doc, &name)
.ok_or_else(|| anyhow::anyhow!("Profile '{}' is not a table", name))?;
match self.resolve_manual_profile(&name, table) {
Ok(resolution) => {
let domains = if resolution.allowed_domains.is_empty() {
"(none)".to_string()
} else {
resolution.allowed_domains.join(", ")
};
lines.push(format!(
"- {} [resource_id: {}] [{}] domains: {} ({})",
name,
resource_id,
Self::auth_type_name(&resolution.auth_type),
domains,
resolution.status_label()
));
}
Err(err) => {
lines.push(format!("- {} [invalid] {}", name, err));
}
}
}
}
if !oauth_connections.is_empty() {
if !lines.is_empty() {
lines.push(String::new());
}
lines.push("OAuth-managed profiles:".to_string());
let now = chrono::Utc::now();
for connection in oauth_connections {
let resource_id = HttpRequestTool::auth_profile_resource_id(&connection.service);
resource_ids.insert(resource_id.clone());
let readiness = crate::services::oauth::CredentialReadiness::for_connection(
&connection,
now,
self.secrets.as_ref(),
)
.describe();
lines.push(format!(
"- {} [resource_id: {}] [{}] readiness: {}; manage with OAuth flow tools",
connection.service, resource_id, connection.auth_type, readiness
));
}
}
if lines.is_empty() {
lines.push("No API auth profiles are configured yet.".to_string());
} else {
lines.push(String::new());
lines.push(
"Use `upsert` to create/update a manual profile, `describe` to inspect it, and `verify` to bind stored secrets and refresh it before live API calls."
.to_string(),
);
}
let subjects = resource_ids
.into_iter()
.filter_map(|resource_id| {
ToolTargetHint::new(ToolTargetHintKind::ResourceId, resource_id)
})
.collect();
Ok((lines.join("\n"), subjects))
}
async fn handle_list(&self) -> anyhow::Result<String> {
self.handle_list_snapshot().await.map(|(output, _)| output)
}
async fn handle_describe(&self, profile_name: &str) -> anyhow::Result<String> {
let doc = self.load_config_doc().await?;
let Some(profile_table) = Self::profile_table(&doc, profile_name) else {
if self.is_oauth_managed_profile(profile_name).await? {
return Ok(format!(
"Profile '{}' is managed by OAuth. Use the OAuth management flow for connection state; this tool only manages manual HTTP auth profiles.",
profile_name
));
}
return Ok(format!(
"Manual auth profile '{}' was not found. Use action='upsert' to create it.",
profile_name
));
};
let resolution = self.resolve_manual_profile(profile_name, profile_table)?;
let mut lines = vec![
format!("Manual API auth profile `{}`", profile_name),
format!(
"- auth_type: `{}`",
Self::auth_type_name(&resolution.auth_type)
),
format!(
"- allowed_domains: {}",
if resolution.allowed_domains.is_empty() {
"(none)".to_string()
} else {
resolution.allowed_domains.join(", ")
}
),
format!("- status: {}", resolution.status_label()),
];
if let Some(header_name) = resolution.live_profile.header_name.as_deref() {
lines.push(format!("- header_name: `{}`", header_name));
}
if let Some(username) = resolution.live_profile.username.as_deref() {
lines.push(format!("- username: `{}`", username));
}
if let Some(user_id) = resolution.live_profile.user_id.as_deref() {
lines.push(format!("- user_id: `{}`", user_id));
}
if !resolution.configured_secret_fields.is_empty() {
lines.push(format!(
"- configured secret fields: {}",
resolution.configured_secret_fields.join(", ")
));
}
if !resolution.detected_secret_fields.is_empty() {
lines.push(format!(
"- stored but not yet bound in config: {}",
resolution.detected_secret_fields.join(", ")
));
}
if !resolution.missing_direct_fields.is_empty() {
lines.push(format!(
"- missing direct fields: {}",
resolution.missing_direct_fields.join(", ")
));
}
if !resolution.missing_secret_fields.is_empty() {
lines.push(format!(
"- missing secure credentials: {}",
resolution.missing_secret_fields.join(", ")
));
}
if !resolution.missing_secret_fields.is_empty() {
lines.push(String::new());
lines.push("Store missing credentials securely with:".to_string());
for field in &resolution.missing_secret_fields {
lines.push(format!(
"- `aidaemon keychain set {}`",
Self::keychain_field_name(profile_name, field)
));
}
}
lines.push(String::new());
lines.push(
"After storing or rotating credentials, run `verify` for this profile before making live API calls."
.to_string(),
);
Ok(lines.join("\n"))
}
async fn handle_upsert(
&self,
profile_name: &str,
args: &ManageHttpAuthArgs,
kernel_approved: Option<&ApprovalScope>,
) -> anyhow::Result<String> {
let UpsertPlan {
mut doc,
auth_type,
allowed_domains,
} = match self.upsert_plan(profile_name, args).await? {
Ok(plan) => plan,
Err(message) => return Ok(message),
};
Self::require_kernel_approval(kernel_approved, "upsert")?;
{
let profile_table = Self::profile_table_mut(&mut doc, profile_name)?;
profile_table.insert(
"auth_type".to_string(),
toml::Value::String(Self::auth_type_name(&auth_type).to_string()),
);
profile_table.insert(
"allowed_domains".to_string(),
toml::Value::Array(
allowed_domains
.iter()
.cloned()
.map(toml::Value::String)
.collect(),
),
);
for field in ["header_name", "username", "user_id"] {
if !Self::is_direct_field_relevant(&auth_type, field) {
profile_table.remove(field);
continue;
}
let incoming = match field {
"header_name" => args.header_name.as_deref(),
"username" => args.username.as_deref(),
"user_id" => args.user_id.as_deref(),
_ => None,
};
if let Some(value) = incoming {
let trimmed = value.trim();
if trimmed.is_empty() {
profile_table.remove(field);
} else {
profile_table
.insert(field.to_string(), toml::Value::String(trimmed.to_string()));
}
}
}
for field in [
"api_key",
"api_secret",
"access_token",
"access_token_secret",
"token",
"header_value",
"password",
] {
if !Self::required_secret_fields(&auth_type).contains(&field) {
profile_table.remove(field);
}
}
}
self.save_config_doc(&doc).await?;
let resolution = self.sync_manual_profile(&mut doc, profile_name).await?;
info!(
profile = %profile_name,
auth_type = Self::auth_type_name(&resolution.auth_type),
"Saved manual API auth profile"
);
let mut lines = vec![
format!("Saved manual API auth profile `{}`.", profile_name),
format!(
"- auth_type: `{}`",
Self::auth_type_name(&resolution.auth_type)
),
format!(
"- allowed_domains: {}",
resolution.allowed_domains.join(", ")
),
];
if !resolution.detected_secret_fields.is_empty() {
lines.push(format!(
"- bound stored credentials from keychain/env: {}",
resolution.detected_secret_fields.join(", ")
));
}
if !resolution.missing_direct_fields.is_empty() {
lines.push(format!(
"- missing direct fields: {}",
resolution.missing_direct_fields.join(", ")
));
}
if !resolution.missing_secret_fields.is_empty() {
lines.push(format!(
"- missing secure credentials: {}",
resolution.missing_secret_fields.join(", ")
));
lines.push(String::new());
lines.push("Store the missing credentials with:".to_string());
for field in &resolution.missing_secret_fields {
lines.push(format!(
"- `aidaemon keychain set {}`",
Self::keychain_field_name(profile_name, field)
));
}
lines.push(String::new());
lines.push(
"After storing them, run `verify` for this profile to bind the secrets and refresh the live auth profile."
.to_string(),
);
} else {
lines.push("- runtime profile refreshed".to_string());
}
Ok(lines.join("\n"))
}
async fn handle_remove(
&self,
profile_name: &str,
kernel_approved: Option<&ApprovalScope>,
) -> anyhow::Result<String> {
let mut doc = self.load_config_doc().await?;
let Some(http_auth_table) = Self::http_auth_table_mut(&mut doc).ok() else {
return Ok(format!(
"Manual auth profile '{}' was not found.",
profile_name
));
};
if !http_auth_table.contains_key(profile_name) {
if self.is_oauth_managed_profile(profile_name).await? {
return Ok(format!(
"Profile '{}' is OAuth-managed. Use the OAuth flow to disconnect it; this tool only removes manual profiles.",
profile_name
));
}
return Ok(format!(
"Manual auth profile '{}' was not found.",
profile_name
));
}
Self::require_kernel_approval(kernel_approved, "remove")?;
http_auth_table.remove(profile_name);
if http_auth_table.is_empty() {
doc.remove("http_auth");
}
self.save_config_doc(&doc).await?;
for field in [
"api_key",
"api_secret",
"access_token",
"access_token_secret",
"token",
"header_value",
"password",
] {
let key = Self::keychain_field_name(profile_name, field);
if let Err(err) = self.secrets.delete(&key) {
warn!(key = %key, error = %err, "Failed to delete stored credential for removed HTTP auth profile");
}
}
self.profiles.write().await.remove(profile_name);
Ok(format!(
"Removed manual API auth profile '{}' and purged its stored credentials.",
profile_name
))
}
pub async fn verify_profile(&self, profile_name: &str) -> anyhow::Result<ProfileVerification> {
let profile = validate_profile_name(profile_name)?;
self.handle_verify(&profile, None, None, None).await
}
async fn handle_verify(
&self,
profile_name: &str,
url: Option<&str>,
method: Option<&str>,
timeout_secs: Option<u64>,
) -> anyhow::Result<ProfileVerification> {
let mut doc = self.load_config_doc().await?;
let Some(_) = Self::profile_table(&doc, profile_name) else {
if self.is_oauth_managed_profile(profile_name).await? {
return Ok(format!(
"Profile '{}' is OAuth-managed. Use the OAuth connection tools to inspect it; this tool verifies manual profiles only.",
profile_name
).into());
}
return Ok(format!("Manual auth profile '{}' was not found.", profile_name).into());
};
let resolution = self.sync_manual_profile(&mut doc, profile_name).await?;
if !resolution.missing_direct_fields.is_empty()
|| !resolution.missing_secret_fields.is_empty()
{
let mut lines = vec![format!(
"Profile '{}' is not ready for live API calls yet.",
profile_name
)];
if !resolution.missing_direct_fields.is_empty() {
lines.push(format!(
"- missing direct fields: {}",
resolution.missing_direct_fields.join(", ")
));
}
if !resolution.missing_secret_fields.is_empty() {
lines.push(format!(
"- missing secure credentials: {}",
resolution.missing_secret_fields.join(", ")
));
lines.push("Store them with:".to_string());
for field in &resolution.missing_secret_fields {
lines.push(format!(
"- `aidaemon keychain set {}`",
Self::keychain_field_name(profile_name, field)
));
}
}
return Ok(ProfileVerification {
text: lines.join("\n"),
ready: false,
});
}
let Some(url) = url.map(str::trim).filter(|value| !value.is_empty()) else {
return Ok(format!(
"Profile '{}' is ready. Runtime auth state refreshed for `{}` across domains: {}.",
profile_name,
Self::auth_type_name(&resolution.auth_type),
resolution.allowed_domains.join(", ")
)
.into());
};
let verify_method = method.unwrap_or("GET").trim().to_ascii_uppercase();
if !matches!(verify_method.as_str(), "GET" | "HEAD") {
return Ok("verify currently supports only GET or HEAD probes. Use http_request for other methods.".to_string().into());
}
let parsed_url = reqwest::Url::parse(url)
.map_err(|err| anyhow::anyhow!("Invalid verify URL: {}", err))?;
if parsed_url.scheme() != "https" {
return Ok("Verification probe blocked: only HTTPS URLs are allowed."
.to_string()
.into());
}
let request_host = parsed_url.host_str().unwrap_or("");
let domain_ok = resolution
.allowed_domains
.iter()
.any(|domain| HttpRequestTool::domain_matches(request_host, domain));
if !domain_ok {
return Ok(format!(
"Verification probe blocked: '{}' is not in the allowed domains for profile '{}'.",
request_host, profile_name
)
.into());
}
if let Err(reason) = crate::web::validate_url_for_ssrf(parsed_url.as_str()) {
return Ok(format!("Verification probe blocked: {reason}").into());
}
let client = crate::web::public_probe_client(Duration::from_secs(
timeout_secs
.unwrap_or(DEFAULT_VERIFY_TIMEOUT_SECS)
.min(MAX_VERIFY_TIMEOUT_SECS),
))
.map_err(|err| anyhow::anyhow!("Failed to build HTTP client: {}", err))?;
let builder = match verify_method.as_str() {
"HEAD" => client.head(url),
_ => client.get(url),
};
let builder = HttpRequestTool::apply_auth(
builder,
&resolution.live_profile,
&verify_method,
url,
None,
None,
)
.map_err(|err| {
anyhow::anyhow!(
"Failed to apply auth for profile '{}': {}",
profile_name,
Self::redact_profile_error(&err.to_string(), &resolution.live_profile)
)
})?;
let response = builder.send().await.map_err(|err| {
anyhow::anyhow!(
"Verification request failed: {}",
Self::redact_profile_error(&err.to_string(), &resolution.live_profile)
)
})?;
let status = response.status();
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or("unknown")
.to_string();
if verify_method == "HEAD" {
return Ok(format!(
"Verification probe completed for '{}': {} {} (content-type: {}).",
profile_name, verify_method, status, content_type
)
.into());
}
let body = response.text().await.unwrap_or_default();
let snippet = if body.is_empty() {
"(empty body)".to_string()
} else {
let boundary = crate::text::floor_char_boundary(&body, 400);
let truncated = body.len() > boundary;
let mut snippet = body[..boundary].to_string();
if truncated {
snippet.push_str("...");
}
snippet
};
Ok(format!(
"Verification probe completed for '{}': {} {} (content-type: {}).\nBody preview:\n{}",
profile_name, verify_method, status, content_type, snippet
)
.into())
}
}
const TOOL_DESCRIPTION: &str = "HTTP auth CRUD; keychain secrets; verify refreshes.";
fn manage_http_auth_schema() -> Value {
json!({
"name": "manage_http_auth",
"description": TOOL_DESCRIPTION,
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["list", "describe", "upsert", "remove", "verify"]
},
"profile": { "type": "string" },
"auth_type": {
"type": "string",
"enum": ["oauth1a", "bearer", "header", "basic"]
},
"allowed_domains": {
"description": "Auth hosts",
"type": "array",
"items": { "type": "string" }
},
"header_name": { "type": "string", "description": "header auth" },
"username": { "type": "string", "description": "basic" },
"user_id": {
"type": "string",
"description": "OAuth1a account ID; pause/revoke mandates before rebind, then reconfirm."
},
"url": { "type": "string" },
"method": { "type": "string", "enum": ["GET", "HEAD"] },
"timeout_secs": { "type": "integer" }
},
"required": ["action"],
"additionalProperties": false
}
})
}
#[async_trait]
impl Tool for ManageHttpAuthTool {
fn name(&self) -> &str {
"manage_http_auth"
}
fn description(&self) -> &str {
TOOL_DESCRIPTION
}
fn schema(&self) -> Value {
manage_http_auth_schema()
}
async fn execute(
&self,
arguments: &str,
facts: &crate::semantics::ToolCallContext,
) -> anyhow::Result<crate::semantics::ToolCallOutcome> {
let facts = facts.clone();
let args: ManageHttpAuthArgs = serde_json::from_str(arguments)?;
let (output, list_members) = if args.action == "list" {
let (output, members) = self.handle_list_snapshot().await?;
(output, Some(members))
} else {
(self.run(arguments, &facts).await?, None)
};
let mut observations = Vec::new();
let mut collections = Vec::new();
if let Some(members) = list_members {
observations.extend(members.iter().cloned().map(|subject| {
ToolObservationEvidence::new(subject, &[ToolSemanticFacet::Authorization])
}));
collections.push(ToolCollectionObservation::complete(
ToolTargetHint::new(
ToolTargetHintKind::ResourceId,
Self::AUTH_PROFILE_COLLECTION_ID,
)
.expect("auth profile collection ID is nonempty"),
&[ToolSemanticFacet::Authorization],
members,
));
} else if matches!(args.action.as_str(), "describe" | "verify")
&& let Some(profile) = args.profile.as_deref()
&& let Ok(profile) = validate_profile_name(profile)
&& let Some(subject) = ToolTargetHint::new(
ToolTargetHintKind::ResourceId,
HttpRequestTool::auth_profile_resource_id(&profile),
)
{
observations.push(ToolObservationEvidence::new(
subject,
&[ToolSemanticFacet::Authorization],
));
}
Ok(ToolCallOutcome {
output,
metadata: ToolCallMetadata {
observations,
collection_observations: collections,
..ToolCallMetadata::default()
},
finish: None,
})
}
}
impl ManageHttpAuthTool {
pub async fn run(&self, arguments: &str, facts: &ToolCallContext) -> anyhow::Result<String> {
let args: ManageHttpAuthArgs = serde_json::from_str(arguments)?;
let kernel_approved = facts.kernel_approved.as_ref();
match args.action.as_str() {
"list" => self.handle_list().await,
"describe" => {
let profile = validate_profile_name(
args.profile
.as_deref()
.ok_or_else(|| anyhow::anyhow!("action='describe' requires 'profile'"))?,
)?;
self.handle_describe(&profile).await
}
"upsert" => {
let profile = validate_profile_name(
args.profile
.as_deref()
.ok_or_else(|| anyhow::anyhow!("action='upsert' requires 'profile'"))?,
)?;
self.handle_upsert(&profile, &args, kernel_approved).await
}
"remove" => {
let profile = validate_profile_name(
args.profile
.as_deref()
.ok_or_else(|| anyhow::anyhow!("action='remove' requires 'profile'"))?,
)?;
self.handle_remove(&profile, kernel_approved).await
}
"verify" => {
let profile = validate_profile_name(
args.profile
.as_deref()
.ok_or_else(|| anyhow::anyhow!("action='verify' requires 'profile'"))?,
)?;
self.handle_verify(
&profile,
args.url.as_deref(),
args.method.as_deref(),
args.timeout_secs,
)
.await
.map(|verified| verified.text)
}
other => Ok(format!(
"Unknown action '{}'. Use: list, describe, upsert, remove, verify.",
other
)),
}
}
}
#[async_trait]
impl crate::semantics::ToolSemantics for ManageHttpAuthTool {
async fn owner_approval_request(
&self,
call: &crate::semantics::ApprovalCall<'_>,
_facts: &ToolCallContext,
) -> OwnerApprovalNeed {
self.owner_approval(call.arguments).await
}
fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
Self::effects_for(arguments)
}
fn stable_observation_subjects(&self) -> Vec<crate::semantics::StableObservationSubject> {
vec![crate::semantics::StableObservationSubject::collection(
Self::AUTH_PROFILE_COLLECTION_ID,
&[ToolSemanticFacet::Authorization],
HttpRequestTool::AUTH_PROFILE_NAMESPACE,
"every configured API auth profile, manual or OAuth-backed",
)]
}
fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
let mut semantics = semantics_for_exact_read_actions(
arguments,
&["list", "describe", "verify"],
ToolMutationEffects::CONFIGURATION,
);
if let Ok(args) = serde_json::from_str::<ManageHttpAuthArgs>(arguments) {
if args.action == "list" {
semantics = semantics.with_target_hint(
ToolTargetHintKind::ResourceId,
Self::AUTH_PROFILE_COLLECTION_ID,
);
}
if let Some(profile) = args.profile.as_deref()
&& let Ok(profile) = validate_profile_name(profile)
{
semantics = semantics.with_target_hint(
ToolTargetHintKind::ResourceId,
HttpRequestTool::auth_profile_resource_id(&profile),
);
}
}
semantics
}
fn capabilities(&self) -> ToolCapabilities {
ToolCapabilities::EXTERNAL_HIGH_IMPACT
}
fn output_trust(
&self,
arguments: &str,
_roots: &crate::semantics::TrustRoots<'_>,
) -> aidaemon_core::SourceTrust {
let previews_remote_body = serde_json::from_str::<ManageHttpAuthArgs>(arguments)
.map(|args| {
args.action == "verify"
&& args
.url
.as_deref()
.is_some_and(|url| !url.trim().is_empty())
})
.unwrap_or(true);
if previews_remote_body {
aidaemon_core::SourceTrust::Untrusted
} else {
aidaemon_core::SourceTrust::Trusted
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::semantics::ToolSemantics;
use crate::testing::ToolCalls as _;
use tempfile::{NamedTempFile, TempDir};
use aidaemon_secrets::MemorySecretStore;
use std::path::{Path, PathBuf};
use crate::services::InMemoryOAuthStore;
async fn test_tool(
config_path: PathBuf,
profiles: SharedHttpProfiles,
) -> anyhow::Result<ManageHttpAuthTool> {
Ok(ManageHttpAuthTool::new(
ConfigFile::new(config_path, Arc::new(crate::config_file::toml_only)),
profiles,
Arc::new(InMemoryOAuthStore::new()),
Arc::new(MemorySecretStore::new()),
))
}
fn kernel_facts() -> ToolCallContext {
ToolCallContext {
kernel_approved: Some(ApprovalScope::Call),
..crate::testing::call_facts("test")
}
}
#[tokio::test]
async fn changes_refuse_without_kernel_approval() {
let config_file = NamedTempFile::new().unwrap();
write_minimal_config(
config_file.path(),
"[http_auth.synthetic]\nauth_type = \"bearer\"\nallowed_domains = [\"api.example.invalid\"]",
);
let before = std::fs::read_to_string(config_file.path()).unwrap();
let profiles = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
let tool = test_tool(config_file.path().to_path_buf(), profiles)
.await
.unwrap();
for args in [
r#"{"action":"upsert","profile":"synthetic","auth_type":"header","header_name":"X-Key"}"#,
r#"{"action":"upsert","profile":"other","auth_type":"bearer","allowed_domains":["api.example.invalid"]}"#,
r#"{"action":"remove","profile":"synthetic"}"#,
] {
let error =
crate::testing::call_with_facts(&tool, args, crate::testing::call_facts("test"))
.await
.expect_err("refused");
assert!(
error
.to_string()
.contains("requires approval through the agent kernel"),
"{error}"
);
assert!(tool.call(args).await.is_err(), "{args}");
}
assert_eq!(std::fs::read_to_string(config_file.path()).unwrap(), before);
let missing = tool
.call(r#"{"action":"remove","profile":"absent"}"#)
.await
.unwrap();
assert!(missing.contains("was not found"), "{missing}");
let listed = tool.call(r#"{"action":"list"}"#).await.unwrap();
assert!(listed.contains("synthetic"), "{listed}");
}
#[test]
fn changes_declare_the_credential_and_reads_declare_none() {
use aidaemon_core::{CallEffects, EffectClass, EffectKey};
for args in [
r#"{"action":"upsert","profile":"synthetic","auth_type":"bearer"}"#,
r#"{"action":"remove","profile":"synthetic"}"#,
] {
let effects = ManageHttpAuthTool::effects_for(args);
assert_eq!(
effects.keys,
vec![EffectKey::named(EffectClass::Credential, "synthetic")]
);
assert!(!effects.complete);
}
let verify = ManageHttpAuthTool::effects_for(
r#"{"action":"verify","profile":"synthetic","url":"https://api.example.invalid/me"}"#,
);
assert_eq!(
verify.keys,
vec![
EffectKey::named(EffectClass::Credential, "synthetic"),
EffectKey::egress("https", "api.example.invalid", None),
]
);
for args in [
r#"{"action":"list"}"#,
r#"{"action":"describe","profile":"synthetic"}"#,
] {
assert_eq!(ManageHttpAuthTool::effects_for(args), CallEffects::none());
}
}
fn write_minimal_config(path: &Path, extra: &str) {
std::fs::write(
path,
format!(
"[provider]\napi_key = \"test-key\"\n{}\n",
if extra.is_empty() {
String::new()
} else {
format!("\n{}", extra)
}
),
)
.unwrap();
}
#[tokio::test]
async fn its_output_is_trusted_unless_it_previews_a_remote_body() {
let config_file = NamedTempFile::new().unwrap();
write_minimal_config(config_file.path(), "");
let profiles = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
let tool = test_tool(config_file.path().to_path_buf(), profiles)
.await
.unwrap();
let roots = crate::semantics::TrustRoots::new(&[]);
assert_eq!(
tool.output_trust(r#"{"action":"list"}"#, &roots),
aidaemon_core::SourceTrust::Trusted
);
assert_eq!(
tool.output_trust(r#"{"action":"verify","profile":"demo"}"#, &roots),
aidaemon_core::SourceTrust::Trusted
);
assert_eq!(
tool.output_trust(
r#"{"action":"verify","profile":"demo","url":"https://api.example.invalid/issues/1"}"#,
&roots
),
aidaemon_core::SourceTrust::Untrusted
);
assert_eq!(
tool.output_trust(r#"{"action":"verify","profile":"demo","url":" "}"#, &roots),
aidaemon_core::SourceTrust::Trusted
);
}
#[tokio::test]
async fn upsert_creates_profile_and_reports_missing_secret_commands() {
let config_file = NamedTempFile::new().unwrap();
write_minimal_config(config_file.path(), "");
let profiles = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
let tool = test_tool(config_file.path().to_path_buf(), profiles.clone())
.await
.unwrap();
let result = crate::testing::call_with_facts(
&tool,
r#"{
"action": "upsert",
"profile": "stripe",
"auth_type": "bearer",
"allowed_domains": ["api.stripe.com"]
}"#,
kernel_facts(),
)
.await
.unwrap();
assert!(result.contains("Saved manual API auth profile `stripe`."));
assert!(result.contains("aidaemon keychain set http_auth_stripe_token"));
let saved = std::fs::read_to_string(config_file.path()).unwrap();
assert!(saved.contains("[http_auth.stripe]"));
assert!(saved.contains("auth_type = \"bearer\""));
assert!(saved.contains("allowed_domains = [\"api.stripe.com\"]"));
assert!(!saved.contains("token = \"keychain\""));
let runtime = profiles.read().await;
assert!(runtime.contains_key("stripe"));
assert_eq!(runtime["stripe"].allowed_domains, vec!["api.stripe.com"]);
}
#[tokio::test]
async fn verify_binds_detected_env_secret_and_refreshes_runtime_profile() {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
write_minimal_config(
&config_path,
r#"
[http_auth.demo]
auth_type = "bearer"
allowed_domains = ["api.example.com"]
"#,
);
let profiles = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
let tool = test_tool(config_path.clone(), profiles.clone())
.await
.unwrap();
tool.secrets
.set("http_auth_demo_token", "secret-demo-token")
.unwrap();
let result = tool
.call(r#"{"action":"verify","profile":"demo"}"#)
.await
.unwrap();
assert!(result.contains("Profile 'demo' is ready."));
let saved = std::fs::read_to_string(&config_path).unwrap();
assert!(saved.contains("token = \"keychain\""));
let runtime = profiles.read().await;
let profile = runtime.get("demo").expect("runtime profile inserted");
assert_eq!(profile.token.as_deref(), Some("secret-demo-token"));
}
#[tokio::test]
async fn list_emits_exact_profile_readiness_and_complete_collection_evidence() {
let config_file = NamedTempFile::new().unwrap();
write_minimal_config(
config_file.path(),
r#"
[http_auth.synthetic_social]
auth_type = "bearer"
allowed_domains = ["api.example.test"]
"#,
);
let profiles = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
let tool = test_tool(config_file.path().to_path_buf(), profiles)
.await
.unwrap();
let outcome = tool
.call_with_status_outcome(r#"{"action":"list"}"#, None)
.await
.unwrap();
let resource_id = HttpRequestTool::auth_profile_resource_id("synthetic_social");
assert!(outcome.output.contains(&resource_id));
assert!(outcome.metadata.observations.iter().any(|observation| {
observation.subject.value == resource_id
&& observation
.facets
.contains(&ToolSemanticFacet::Authorization)
}));
let collection = outcome
.metadata
.collection_observations
.iter()
.find(|collection| {
collection.collection.value == ManageHttpAuthTool::AUTH_PROFILE_COLLECTION_ID
})
.expect("auth profile collection coverage");
assert_eq!(
collection.completeness,
crate::semantics::ToolCollectionCompleteness::Complete
);
assert_eq!(collection.members.len(), 1);
assert_eq!(collection.members[0].value, resource_id);
}
#[tokio::test]
async fn list_projects_the_same_typed_readiness_for_oauth_managed_profiles() {
let config_file = NamedTempFile::new().unwrap();
write_minimal_config(config_file.path(), "");
let profiles = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new()));
let tool = test_tool(config_file.path().to_path_buf(), profiles)
.await
.unwrap();
for (key, value) in [
("oauth_twitter_access_token", "stale"),
("oauth_twitter_refresh_token", "rt"),
("oauth_twitter_client_id", "id"),
("oauth_twitter_client_secret", "secret"),
] {
tool.secrets.set(key, value).unwrap();
}
let expired = (chrono::Utc::now() - chrono::Duration::hours(3)).to_rfc3339();
tool.state_store
.save_oauth_connection(&crate::services::OAuthConnection {
id: 0,
service: "twitter".to_string(),
auth_type: "oauth2_pkce".to_string(),
username: None,
account_id: Some("1000000000000000001".to_string()),
scopes: r#"["tweet.write"]"#.to_string(),
token_expires_at: Some(expired.clone()),
created_at: chrono::Utc::now().to_rfc3339(),
updated_at: chrono::Utc::now().to_rfc3339(),
})
.await
.unwrap();
let output = tool.call(r#"{"action":"list"}"#).await.unwrap();
let expected = crate::services::oauth::CredentialReadiness::Refreshable {
expired_at: Some(expired),
path: crate::services::oauth::CredentialRefreshPath::RefreshToken,
}
.describe();
assert!(
output.contains(&format!("readiness: {expected};")),
"{output}"
);
}
}