AstrBot-Desktop/src-tauri/src/credentials/mod.rs

363 行
12 KiB
Rust

use desktop_protocol::AuthenticationType;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::database::{ApplicationDatabase, DatabaseError};
use crate::secure_store::{
CredentialReference, SecretCredential, SecureCredentialStore, SecureStoreError,
WindowsCredentialStore,
};
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EnrollCredentialRequest {
pub profile_id: String,
pub authentication_type: AuthenticationType,
/// One-shot secret. Never returned to React and never logged.
pub secret: String,
#[serde(default)]
pub username: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CredentialEnrollmentResult {
pub profile_id: String,
pub credential_reference: String,
pub authentication_type: AuthenticationType,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CredentialCommandError {
pub code: &'static str,
pub message: &'static str,
}
impl std::fmt::Display for CredentialCommandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.message)
}
}
impl std::error::Error for CredentialCommandError {}
impl CredentialCommandError {
fn validation(message: &'static str) -> Self {
Self {
code: "validationFailed",
message,
}
}
fn not_found() -> Self {
Self {
code: "notFound",
message: "The connection profile no longer exists.",
}
}
fn store() -> Self {
Self {
code: "secureStoreUnavailable",
message: "Windows Credential Manager is unavailable.",
}
}
fn database() -> Self {
Self {
code: "databaseUnavailable",
message: "The local profile database is unavailable.",
}
}
}
#[tauri::command]
pub fn enroll_profile_credential(
database: tauri::State<'_, ApplicationDatabase>,
request: EnrollCredentialRequest,
) -> Result<CredentialEnrollmentResult, CredentialCommandError> {
enroll_credential(&database, &WindowsCredentialStore, request)
}
#[tauri::command]
pub fn clear_profile_credential(
database: tauri::State<'_, ApplicationDatabase>,
profile_id: String,
) -> Result<(), CredentialCommandError> {
clear_credential(&database, &WindowsCredentialStore, &profile_id)
}
pub fn enroll_credential(
database: &ApplicationDatabase,
store: &impl SecureCredentialStore,
request: EnrollCredentialRequest,
) -> Result<CredentialEnrollmentResult, CredentialCommandError> {
if Uuid::parse_str(&request.profile_id).is_err() {
return Err(CredentialCommandError::validation(
"profile_id must be a UUID.",
));
}
if request.secret.trim().is_empty() {
return Err(CredentialCommandError::validation(
"credential secret must not be empty.",
));
}
if request.secret.len() > 2_560 {
return Err(CredentialCommandError::validation(
"credential secret exceeds the supported length.",
));
}
let mut profile = database
.profile(&request.profile_id)
.map_err(|_| CredentialCommandError::database())?
.ok_or_else(CredentialCommandError::not_found)?;
// Replace any previous reference after a successful write.
let reference = CredentialReference::new();
let credential =
SecretCredential::with_username(request.username.clone(), request.secret.into_bytes())
.map_err(|error| match error {
SecureStoreError::InvalidSecretLength | SecureStoreError::InvalidUsername => {
CredentialCommandError::validation("credential secret is invalid.")
}
_ => CredentialCommandError::store(),
})?;
store
.write(reference, &credential)
.map_err(|_| CredentialCommandError::store())?;
if let Some(previous) = profile
.credential_reference
.as_ref()
.and_then(|value| Uuid::parse_str(value).ok())
.map(CredentialReference::from_uuid)
{
let _ = store.delete(previous);
}
profile.credential_reference = Some(reference.as_uuid().to_string());
profile.authentication_type = request.authentication_type;
profile.updated_at = current_timestamp();
database
.update_profile(&profile)
.map_err(|error| match error {
DatabaseError::ProfileNotFound => CredentialCommandError::not_found(),
_ => CredentialCommandError::database(),
})?;
Ok(CredentialEnrollmentResult {
profile_id: profile.id,
credential_reference: reference.as_uuid().to_string(),
authentication_type: profile.authentication_type,
})
}
pub fn clear_credential(
database: &ApplicationDatabase,
store: &impl SecureCredentialStore,
profile_id: &str,
) -> Result<(), CredentialCommandError> {
if Uuid::parse_str(profile_id).is_err() {
return Err(CredentialCommandError::validation(
"profile_id must be a UUID.",
));
}
let mut profile = database
.profile(profile_id)
.map_err(|_| CredentialCommandError::database())?
.ok_or_else(CredentialCommandError::not_found)?;
if let Some(previous) = profile
.credential_reference
.as_ref()
.and_then(|value| Uuid::parse_str(value).ok())
.map(CredentialReference::from_uuid)
{
let _ = store.delete(previous);
}
profile.credential_reference = None;
profile.updated_at = current_timestamp();
database
.update_profile(&profile)
.map_err(|_| CredentialCommandError::database())?;
Ok(())
}
/// Loads a secret for Rust-owned networking only. Never exposed through Tauri commands.
pub fn load_profile_secret(
database: &ApplicationDatabase,
store: &impl SecureCredentialStore,
profile_id: &str,
) -> Result<Option<SecretCredential>, CredentialCommandError> {
let profile = database
.profile(profile_id)
.map_err(|_| CredentialCommandError::database())?
.ok_or_else(CredentialCommandError::not_found)?;
let Some(reference) = profile
.credential_reference
.as_ref()
.and_then(|value| Uuid::parse_str(value).ok())
.map(CredentialReference::from_uuid)
else {
return Ok(None);
};
store
.read(reference)
.map_err(|_| CredentialCommandError::store())
}
fn current_timestamp() -> String {
time::OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Rfc3339)
.unwrap_or_else(|_| "1970-01-01T00:00:00Z".into())
}
#[cfg(test)]
mod tests {
use super::*;
use desktop_protocol::{AstrBotProfileRole, ConnectionProfile};
use std::collections::HashMap;
use std::sync::Mutex;
type MemoryCredential = (Option<String>, Vec<u8>);
#[derive(Default)]
struct MemoryStore {
values: Mutex<HashMap<Uuid, MemoryCredential>>,
}
impl SecureCredentialStore for MemoryStore {
fn write(
&self,
reference: CredentialReference,
credential: &SecretCredential,
) -> Result<(), SecureStoreError> {
self.values.lock().expect("lock").insert(
reference.as_uuid(),
(
credential.username().map(str::to_owned),
credential.secret().to_vec(),
),
);
Ok(())
}
fn read(
&self,
reference: CredentialReference,
) -> Result<Option<SecretCredential>, SecureStoreError> {
match self.values.lock().expect("lock").get(&reference.as_uuid()) {
Some((username, secret)) => Ok(Some(SecretCredential::with_username(
username.clone(),
secret.clone(),
)?)),
None => Ok(None),
}
}
fn delete(&self, reference: CredentialReference) -> Result<bool, SecureStoreError> {
Ok(self
.values
.lock()
.expect("lock")
.remove(&reference.as_uuid())
.is_some())
}
}
fn sample_profile() -> ConnectionProfile {
ConnectionProfile {
id: "11111111-1111-1111-1111-111111111111".into(),
display_name: "Probe".into(),
role: AstrBotProfileRole::Companion,
base_url: "http://127.0.0.1:26285/".into(),
event_stream_url: None,
authentication_type: AuthenticationType::ApiKey,
transport_kind: desktop_protocol::TransportKind::AstrBotOpenApi,
credential_reference: None,
allow_insecure_http: true,
pinned_certificate_fingerprint: None,
auto_connect_slot: None,
auto_connect: false,
server_instance_id: None,
server_version: None,
protocol_version: None,
local_tool_policy_id: None,
last_connected_at: None,
remote_username: None,
sticky_session_id: None,
created_at: "2026-07-20T00:00:00Z".into(),
updated_at: "2026-07-20T00:00:00Z".into(),
}
}
#[test]
fn enrolls_and_clears_credential_reference_without_returning_secret() {
let database = ApplicationDatabase::in_memory().expect("db");
let profile = sample_profile();
database.create_profile(&profile).expect("create");
let store = MemoryStore::default();
let enrolled = enroll_credential(
&database,
&store,
EnrollCredentialRequest {
profile_id: profile.id.clone(),
authentication_type: AuthenticationType::ApiKey,
secret: "abk_test_secret".into(),
username: Some("desktop-companion".into()),
},
)
.expect("enroll");
assert!(!enrolled.credential_reference.is_empty());
let stored = database
.profile(&profile.id)
.expect("profile")
.expect("exists");
assert_eq!(
stored.credential_reference.as_deref(),
Some(enrolled.credential_reference.as_str())
);
let secret = load_profile_secret(&database, &store, &profile.id)
.expect("load")
.expect("secret");
assert_eq!(secret.secret(), b"abk_test_secret");
assert_eq!(secret.username(), Some("desktop-companion"));
clear_credential(&database, &store, &profile.id).expect("clear");
let cleared = database
.profile(&profile.id)
.expect("profile")
.expect("exists");
assert!(cleared.credential_reference.is_none());
assert!(
load_profile_secret(&database, &store, &profile.id)
.expect("load missing")
.is_none()
);
}
#[test]
fn rejects_empty_secret() {
let database = ApplicationDatabase::in_memory().expect("db");
database.create_profile(&sample_profile()).expect("create");
let store = MemoryStore::default();
let error = enroll_credential(
&database,
&store,
EnrollCredentialRequest {
profile_id: "11111111-1111-1111-1111-111111111111".into(),
authentication_type: AuthenticationType::ApiKey,
secret: " ".into(),
username: None,
},
)
.expect_err("empty");
assert_eq!(error.code, "validationFailed");
}
}