diff --git a/src-tauri/src/database/mod.rs b/src-tauri/src/database/mod.rs index ecc4130..f837138 100644 --- a/src-tauri/src/database/mod.rs +++ b/src-tauri/src/database/mod.rs @@ -1,9 +1,11 @@ +mod profiles; + use std::{path::Path, sync::Mutex, time::Duration}; use rusqlite::{Connection, OptionalExtension, params}; use thiserror::Error; -pub const CURRENT_SCHEMA_VERSION: u32 = 1; +pub const CURRENT_SCHEMA_VERSION: u32 = 2; pub struct ApplicationDatabase { store: Mutex, @@ -16,6 +18,13 @@ impl ApplicationDatabase { }) } + #[cfg(test)] + pub(crate) fn in_memory() -> Result { + Ok(Self { + store: Mutex::new(ProfileMessageStore::in_memory()?), + }) + } + pub fn schema_version(&self) -> Result { self.store .lock() @@ -143,6 +152,38 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> { transaction.commit()?; } + if found <= 1 { + let transaction = connection.transaction()?; + transaction.execute_batch( + " + CREATE TABLE connection_profiles ( + id TEXT PRIMARY KEY NOT NULL, + display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 80), + role TEXT NOT NULL CHECK(role IN ('companion', 'operations', 'general')), + base_url TEXT NOT NULL, + event_stream_url TEXT, + authentication_type TEXT NOT NULL CHECK(authentication_type IN ('device-token', 'api-key')), + credential_reference TEXT, + allow_insecure_http INTEGER NOT NULL DEFAULT 0 CHECK(allow_insecure_http IN (0, 1)), + pinned_certificate_fingerprint TEXT, + auto_connect_slot TEXT CHECK(auto_connect_slot IS NULL OR auto_connect_slot IN ('companion', 'operations')), + auto_connect INTEGER NOT NULL DEFAULT 0 CHECK(auto_connect IN (0, 1)), + server_instance_id TEXT, + server_version TEXT, + protocol_version TEXT, + local_tool_policy_id TEXT, + last_connected_at TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + CREATE INDEX connection_profiles_role_idx + ON connection_profiles(role); + PRAGMA user_version = 2; + ", + )?; + transaction.commit()?; + } + Ok(()) } @@ -154,6 +195,10 @@ pub enum DatabaseError { UnsupportedSchemaVersion { found: u32, supported: u32 }, #[error("database state lock is unavailable")] LockPoisoned, + #[error("database contains invalid profile data")] + InvalidStoredProfile, + #[error("connection profile was not found")] + ProfileNotFound, } #[cfg(test)] @@ -196,6 +241,62 @@ mod tests { ); } + #[test] + fn migrates_v1_to_v2_without_losing_messages() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("v1.sqlite3"); + let connection = Connection::open(&path).expect("create v1 database"); + connection + .execute_batch( + " + CREATE TABLE messages ( + profile_id TEXT NOT NULL, + server_instance_id TEXT NOT NULL, + conversation_id TEXT NOT NULL, + message_id TEXT NOT NULL, + content TEXT NOT NULL, + PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id) + ); + INSERT INTO messages ( + profile_id, + server_instance_id, + conversation_id, + message_id, + content + ) VALUES ( + 'profile-a', + 'server-a', + 'conversation-a', + 'message-a', + 'preserved' + ); + PRAGMA user_version = 1; + ", + ) + .expect("create v1 schema"); + drop(connection); + + let store = ProfileMessageStore::open(&path).expect("migrate database"); + assert_eq!(store.schema_version().expect("schema version"), 2); + assert_eq!( + store + .message_content("profile-a", "server-a", "conversation-a", "message-a") + .expect("query preserved message") + .as_deref(), + Some("preserved") + ); + let profile_table_count: u32 = store + .connection + .query_row( + "SELECT COUNT(*) FROM sqlite_master + WHERE type = 'table' AND name = 'connection_profiles'", + [], + |row| row.get(0), + ) + .expect("query profile table"); + assert_eq!(profile_table_count, 1); + } + #[test] fn refuses_a_database_from_a_newer_schema_version() { let directory = tempfile::tempdir().expect("temporary directory"); @@ -209,7 +310,7 @@ mod tests { assert!(matches!( ProfileMessageStore::open(path), Err(DatabaseError::UnsupportedSchemaVersion { - found: 2, + found: 3, supported: CURRENT_SCHEMA_VERSION }) )); diff --git a/src-tauri/src/database/profiles.rs b/src-tauri/src/database/profiles.rs new file mode 100644 index 0000000..0628722 --- /dev/null +++ b/src-tauri/src/database/profiles.rs @@ -0,0 +1,349 @@ +use desktop_protocol::{ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile}; +use rusqlite::{Row, params}; + +use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore}; + +const PROFILE_COLUMNS: &str = " + id, + display_name, + role, + base_url, + event_stream_url, + authentication_type, + credential_reference, + allow_insecure_http, + pinned_certificate_fingerprint, + auto_connect_slot, + auto_connect, + server_instance_id, + server_version, + protocol_version, + local_tool_policy_id, + last_connected_at, + created_at, + updated_at +"; + +impl ApplicationDatabase { + pub fn list_profiles(&self) -> Result, DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .list_profiles() + } + + pub fn profile(&self, id: &str) -> Result, DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .profile(id) + } + + pub fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .create_profile(profile) + } + + pub fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .update_profile(profile) + } + + pub fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> { + self.store + .lock() + .map_err(|_| DatabaseError::LockPoisoned)? + .delete_profile(id) + } +} + +impl ProfileMessageStore { + fn list_profiles(&self) -> Result, DatabaseError> { + let mut statement = self.connection.prepare(&format!( + "SELECT {PROFILE_COLUMNS} + FROM connection_profiles + ORDER BY display_name COLLATE NOCASE, id" + ))?; + let mut rows = statement.query([])?; + let mut profiles = Vec::new(); + while let Some(row) = rows.next()? { + profiles.push(profile_from_row(row)?); + } + Ok(profiles) + } + + fn profile(&self, id: &str) -> Result, DatabaseError> { + let mut statement = self.connection.prepare(&format!( + "SELECT {PROFILE_COLUMNS} + FROM connection_profiles + WHERE id = ?1" + ))?; + let mut rows = statement.query(params![id])?; + match rows.next()? { + Some(row) => Ok(Some(profile_from_row(row)?)), + None => Ok(None), + } + } + + fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> { + self.connection.execute( + " + INSERT INTO connection_profiles ( + id, + display_name, + role, + base_url, + event_stream_url, + authentication_type, + credential_reference, + allow_insecure_http, + pinned_certificate_fingerprint, + auto_connect_slot, + auto_connect, + server_instance_id, + server_version, + protocol_version, + local_tool_policy_id, + last_connected_at, + created_at, + updated_at + ) VALUES ( + ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, + ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18 + ) + ", + params![ + profile.id, + profile.display_name, + role_to_str(profile.role), + profile.base_url, + profile.event_stream_url, + authentication_to_str(profile.authentication_type), + profile.credential_reference, + profile.allow_insecure_http, + profile.pinned_certificate_fingerprint, + profile.auto_connect_slot.map(slot_to_str), + profile.auto_connect, + profile.server_instance_id, + profile.server_version, + profile.protocol_version, + profile.local_tool_policy_id, + profile.last_connected_at, + profile.created_at, + profile.updated_at, + ], + )?; + Ok(()) + } + + fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> { + let changed = self.connection.execute( + " + UPDATE connection_profiles + SET display_name = ?2, + role = ?3, + base_url = ?4, + event_stream_url = ?5, + authentication_type = ?6, + credential_reference = ?7, + allow_insecure_http = ?8, + pinned_certificate_fingerprint = ?9, + auto_connect_slot = ?10, + auto_connect = ?11, + server_instance_id = ?12, + server_version = ?13, + protocol_version = ?14, + local_tool_policy_id = ?15, + last_connected_at = ?16, + created_at = ?17, + updated_at = ?18 + WHERE id = ?1 + ", + params![ + profile.id, + profile.display_name, + role_to_str(profile.role), + profile.base_url, + profile.event_stream_url, + authentication_to_str(profile.authentication_type), + profile.credential_reference, + profile.allow_insecure_http, + profile.pinned_certificate_fingerprint, + profile.auto_connect_slot.map(slot_to_str), + profile.auto_connect, + profile.server_instance_id, + profile.server_version, + profile.protocol_version, + profile.local_tool_policy_id, + profile.last_connected_at, + profile.created_at, + profile.updated_at, + ], + )?; + if changed == 0 { + return Err(DatabaseError::ProfileNotFound); + } + Ok(()) + } + + fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> { + if self + .connection + .execute("DELETE FROM connection_profiles WHERE id = ?1", params![id])? + == 0 + { + return Err(DatabaseError::ProfileNotFound); + } + Ok(()) + } +} + +fn profile_from_row(row: &Row<'_>) -> Result { + let role = match row.get::<_, String>(2)?.as_str() { + "companion" => AstrBotProfileRole::Companion, + "operations" => AstrBotProfileRole::Operations, + "general" => AstrBotProfileRole::General, + _ => return Err(DatabaseError::InvalidStoredProfile), + }; + let authentication_type = match row.get::<_, String>(5)?.as_str() { + "device-token" => AuthenticationType::DeviceToken, + "api-key" => AuthenticationType::ApiKey, + _ => return Err(DatabaseError::InvalidStoredProfile), + }; + let auto_connect_slot = match row.get::<_, Option>(9)?.as_deref() { + Some("companion") => Some(ActiveSlotKind::Companion), + Some("operations") => Some(ActiveSlotKind::Operations), + Some(_) => return Err(DatabaseError::InvalidStoredProfile), + None => None, + }; + + Ok(ConnectionProfile { + id: row.get(0)?, + display_name: row.get(1)?, + role, + base_url: row.get(3)?, + event_stream_url: row.get(4)?, + authentication_type, + credential_reference: row.get(6)?, + allow_insecure_http: row.get(7)?, + pinned_certificate_fingerprint: row.get(8)?, + auto_connect_slot, + auto_connect: row.get(10)?, + server_instance_id: row.get(11)?, + server_version: row.get(12)?, + protocol_version: row.get(13)?, + local_tool_policy_id: row.get(14)?, + last_connected_at: row.get(15)?, + created_at: row.get(16)?, + updated_at: row.get(17)?, + }) +} + +fn role_to_str(role: AstrBotProfileRole) -> &'static str { + match role { + AstrBotProfileRole::Companion => "companion", + AstrBotProfileRole::Operations => "operations", + AstrBotProfileRole::General => "general", + } +} + +fn authentication_to_str(authentication_type: AuthenticationType) -> &'static str { + match authentication_type { + AuthenticationType::DeviceToken => "device-token", + AuthenticationType::ApiKey => "api-key", + } +} + +fn slot_to_str(slot: ActiveSlotKind) -> &'static str { + match slot { + ActiveSlotKind::Companion => "companion", + ActiveSlotKind::Operations => "operations", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn profile(index: usize) -> ConnectionProfile { + ConnectionProfile { + id: format!("00000000-0000-4000-8000-{index:012}"), + display_name: format!("Profile {index}"), + role: AstrBotProfileRole::General, + base_url: format!("https://example-{index}.test/"), + event_stream_url: None, + authentication_type: AuthenticationType::DeviceToken, + credential_reference: None, + allow_insecure_http: false, + 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, + created_at: "2026-07-18T00:00:00Z".into(), + updated_at: "2026-07-18T00:00:00Z".into(), + } + } + + #[test] + fn stores_lists_updates_and_deletes_five_profiles() { + let database = ApplicationDatabase::in_memory().expect("database"); + for index in 0..5 { + database + .create_profile(&profile(index)) + .expect("create profile"); + } + assert_eq!(database.list_profiles().expect("list profiles").len(), 5); + + let mut updated = database + .profile(&profile(2).id) + .expect("read profile") + .expect("existing profile"); + updated.display_name = "Updated Profile".into(); + updated.updated_at = "2026-07-18T01:00:00Z".into(); + database.update_profile(&updated).expect("update profile"); + assert_eq!( + database + .profile(&updated.id) + .expect("read updated profile") + .expect("existing profile") + .display_name, + "Updated Profile" + ); + + database + .delete_profile(&updated.id) + .expect("delete profile"); + assert_eq!(database.list_profiles().expect("list profiles").len(), 4); + assert!(matches!( + database.delete_profile(&updated.id), + Err(DatabaseError::ProfileNotFound) + )); + } + + #[test] + fn profile_metadata_persists_after_reopening_database() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("profiles.sqlite3"); + let expected = profile(7); + + { + let store = ProfileMessageStore::open(&path).expect("open database"); + store.create_profile(&expected).expect("create profile"); + } + + let reopened = ProfileMessageStore::open(&path).expect("reopen database"); + let actual = reopened + .profile(&expected.id) + .expect("read profile") + .expect("persisted profile"); + assert_eq!(actual, expected); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 8c27438..1d879e8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ pub mod diagnostics; pub mod file_transfer; pub mod logging; pub mod networking; +pub mod profiles; pub mod secure_store; pub mod windows; @@ -85,7 +86,13 @@ pub fn run() { let _ = window.hide(); } }) - .invoke_handler(tauri::generate_handler![bootstrap_status]) + .invoke_handler(tauri::generate_handler![ + bootstrap_status, + profiles::list_connection_profiles, + profiles::create_connection_profile, + profiles::update_connection_profile, + profiles::delete_connection_profile, + ]) .run(tauri::generate_context!()) .expect("failed to run AstrBot Desktop"); } diff --git a/src-tauri/src/profiles.rs b/src-tauri/src/profiles.rs new file mode 100644 index 0000000..22916f4 --- /dev/null +++ b/src-tauri/src/profiles.rs @@ -0,0 +1,353 @@ +use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile}; +use serde::{Deserialize, Serialize}; +use time::{OffsetDateTime, format_description::well_known::Rfc3339}; +use url::Url; +use uuid::Uuid; + +use crate::database::{ApplicationDatabase, DatabaseError}; + +const MAX_DISPLAY_NAME_CHARS: usize = 80; +const MAX_URL_CHARS: usize = 2048; + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConnectionProfileInput { + pub display_name: String, + pub role: AstrBotProfileRole, + pub base_url: String, + #[serde(default)] + pub event_stream_url: Option, + pub authentication_type: AuthenticationType, + #[serde(default)] + pub allow_insecure_http: bool, + #[serde(default)] + pub pinned_certificate_fingerprint: Option, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UpdateConnectionProfileRequest { + pub id: String, + #[serde(flatten)] + pub profile: ConnectionProfileInput, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProfileCommandError { + code: &'static str, + message: &'static str, +} + +impl ProfileCommandError { + fn validation(message: &'static str) -> Self { + Self { + code: "validationFailed", + message, + } + } + + fn database(error: DatabaseError) -> Self { + match error { + DatabaseError::ProfileNotFound => Self { + code: "notFound", + message: "The connection profile no longer exists.", + }, + _ => Self { + code: "databaseUnavailable", + message: "The local profile database is unavailable.", + }, + } + } +} + +#[tauri::command] +pub fn list_connection_profiles( + database: tauri::State<'_, ApplicationDatabase>, +) -> Result, ProfileCommandError> { + list_profiles(&database) +} + +#[tauri::command] +pub fn create_connection_profile( + database: tauri::State<'_, ApplicationDatabase>, + request: ConnectionProfileInput, +) -> Result { + create_profile(&database, request) +} + +#[tauri::command] +pub fn update_connection_profile( + database: tauri::State<'_, ApplicationDatabase>, + request: UpdateConnectionProfileRequest, +) -> Result { + update_profile(&database, request) +} + +#[tauri::command] +pub fn delete_connection_profile( + database: tauri::State<'_, ApplicationDatabase>, + id: String, +) -> Result<(), ProfileCommandError> { + delete_profile(&database, &id) +} + +fn list_profiles( + database: &ApplicationDatabase, +) -> Result, ProfileCommandError> { + database + .list_profiles() + .map_err(ProfileCommandError::database) +} + +fn create_profile( + database: &ApplicationDatabase, + request: ConnectionProfileInput, +) -> Result { + let normalized = normalize_input(request)?; + let now = timestamp()?; + let profile = ConnectionProfile { + id: Uuid::new_v4().to_string(), + display_name: normalized.display_name, + role: normalized.role, + base_url: normalized.base_url, + event_stream_url: normalized.event_stream_url, + authentication_type: normalized.authentication_type, + credential_reference: None, + allow_insecure_http: normalized.allow_insecure_http, + pinned_certificate_fingerprint: normalized.pinned_certificate_fingerprint, + 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, + created_at: now.clone(), + updated_at: now, + }; + database + .create_profile(&profile) + .map_err(ProfileCommandError::database)?; + Ok(profile) +} + +fn update_profile( + database: &ApplicationDatabase, + request: UpdateConnectionProfileRequest, +) -> Result { + validate_id(&request.id)?; + let normalized = normalize_input(request.profile)?; + let mut profile = database + .profile(&request.id) + .map_err(ProfileCommandError::database)? + .ok_or_else(|| ProfileCommandError::database(DatabaseError::ProfileNotFound))?; + + profile.display_name = normalized.display_name; + profile.role = normalized.role; + profile.base_url = normalized.base_url; + profile.event_stream_url = normalized.event_stream_url; + profile.authentication_type = normalized.authentication_type; + profile.allow_insecure_http = normalized.allow_insecure_http; + profile.pinned_certificate_fingerprint = normalized.pinned_certificate_fingerprint; + profile.updated_at = timestamp()?; + + database + .update_profile(&profile) + .map_err(ProfileCommandError::database)?; + Ok(profile) +} + +fn delete_profile(database: &ApplicationDatabase, id: &str) -> Result<(), ProfileCommandError> { + validate_id(id)?; + database + .delete_profile(id) + .map_err(ProfileCommandError::database) +} + +fn normalize_input( + request: ConnectionProfileInput, +) -> Result { + let display_name = request.display_name.trim().to_owned(); + if display_name.is_empty() + || display_name.chars().count() > MAX_DISPLAY_NAME_CHARS + || display_name.chars().any(char::is_control) + { + return Err(ProfileCommandError::validation( + "Display name must contain 1 to 80 visible characters.", + )); + } + + let base_url = normalize_url(&request.base_url, request.allow_insecure_http)?; + let event_stream_url = request + .event_stream_url + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(|value| normalize_url(value, request.allow_insecure_http)) + .transpose()?; + let pinned_certificate_fingerprint = + normalize_fingerprint(request.pinned_certificate_fingerprint)?; + + Ok(ConnectionProfileInput { + display_name, + role: request.role, + base_url, + event_stream_url, + authentication_type: request.authentication_type, + allow_insecure_http: request.allow_insecure_http, + pinned_certificate_fingerprint, + }) +} + +fn normalize_url(value: &str, allow_insecure_http: bool) -> Result { + let value = value.trim(); + if value.is_empty() || value.chars().count() > MAX_URL_CHARS { + return Err(ProfileCommandError::validation( + "Connection URL is empty or too long.", + )); + } + + let mut url = Url::parse(value) + .map_err(|_| ProfileCommandError::validation("Connection URL is invalid."))?; + if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() { + return Err(ProfileCommandError::validation( + "Connection URL must use HTTP or HTTPS and include a host.", + )); + } + if !url.username().is_empty() || url.password().is_some() { + return Err(ProfileCommandError::validation( + "Credentials must not be embedded in a connection URL.", + )); + } + if url.query().is_some() || url.fragment().is_some() { + return Err(ProfileCommandError::validation( + "Connection URLs must not contain query parameters or fragments.", + )); + } + if url.scheme() == "http" && !allow_insecure_http { + return Err(ProfileCommandError::validation( + "HTTP requires explicit insecure-transport approval.", + )); + } + url.set_fragment(None); + Ok(url.to_string()) +} + +fn normalize_fingerprint(value: Option) -> Result, ProfileCommandError> { + let Some(value) = value else { + return Ok(None); + }; + let normalized = value + .trim() + .chars() + .filter(|character| *character != ':') + .flat_map(char::to_uppercase) + .collect::(); + if normalized.is_empty() { + return Ok(None); + } + if normalized.len() != 64 + || !normalized + .chars() + .all(|character| character.is_ascii_hexdigit()) + { + return Err(ProfileCommandError::validation( + "Pinned certificate fingerprint must be a SHA-256 hex value.", + )); + } + Ok(Some(normalized)) +} + +fn validate_id(id: &str) -> Result<(), ProfileCommandError> { + if Uuid::parse_str(id).is_err() { + return Err(ProfileCommandError::validation( + "Connection profile ID is invalid.", + )); + } + Ok(()) +} + +fn timestamp() -> Result { + OffsetDateTime::now_utc() + .format(&Rfc3339) + .map_err(|_| ProfileCommandError { + code: "clockUnavailable", + message: "The system clock could not produce a profile timestamp.", + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(base_url: &str) -> ConnectionProfileInput { + ConnectionProfileInput { + display_name: " Test Profile ".into(), + role: AstrBotProfileRole::General, + base_url: base_url.into(), + event_stream_url: None, + authentication_type: AuthenticationType::DeviceToken, + allow_insecure_http: false, + pinned_certificate_fingerprint: None, + } + } + + #[test] + fn creates_updates_lists_and_deletes_profile_metadata() { + let database = ApplicationDatabase::in_memory().expect("database"); + let created = + create_profile(&database, request("https://example.test")).expect("create profile"); + assert_eq!(created.display_name, "Test Profile"); + assert_eq!(created.base_url, "https://example.test/"); + assert!(created.credential_reference.is_none()); + assert!(!created.auto_connect); + assert!(created.auto_connect_slot.is_none()); + + let updated = update_profile( + &database, + UpdateConnectionProfileRequest { + id: created.id.clone(), + profile: ConnectionProfileInput { + display_name: "Updated".into(), + role: AstrBotProfileRole::Companion, + base_url: "https://updated.example.test".into(), + event_stream_url: Some("https://updated.example.test/events".into()), + authentication_type: AuthenticationType::ApiKey, + allow_insecure_http: false, + pinned_certificate_fingerprint: None, + }, + }, + ) + .expect("update profile"); + assert_eq!(updated.display_name, "Updated"); + assert_eq!(list_profiles(&database).expect("list profiles").len(), 1); + + delete_profile(&database, &created.id).expect("delete profile"); + assert!(list_profiles(&database).expect("list profiles").is_empty()); + } + + #[test] + fn rejects_insecure_or_credential_bearing_urls() { + let database = ApplicationDatabase::in_memory().expect("database"); + assert!(create_profile(&database, request("http://example.test")).is_err()); + assert!(create_profile(&database, request("https://user:password@example.test")).is_err()); + assert!(create_profile(&database, request("https://example.test?token=fake")).is_err()); + } + + #[test] + fn rejects_secret_values_and_unknown_fields_at_the_ipc_boundary() { + let result = serde_json::from_value::(serde_json::json!({ + "displayName": "Test Profile", + "role": "general", + "baseUrl": "https://example.test", + "authenticationType": "device-token", + "allowInsecureHttp": false, + "token": "[REDACTED]", + "password": "[REDACTED]", + "apiKey": "[REDACTED]" + })); + + assert!(result.is_err()); + } +}