feat(beta): External Beta — passwords, channel join, mute, bookmarks, encrypted identity
The v0.3 client could only ever connect to a hardcoded default
channel with no password and offered no controls mid-call.
External Beta closes those gaps and tightens identity-at-rest.
User-facing additions
---------------------
* **Server password** on the connect form. Plumbed through
`BridgeError`-aware `connect(host, nickname, password)`. Empty
string means "no password" — no behaviour change for open
servers.
* **Channel join**: tapping a row (or its login icon) in the
channel tree issues a `client_move`. Names containing "🔒" or
"password" prompt for a channel password first.
* **Self-mute** for both microphone (`client_input_muted`) and
speaker (`client_output_muted`) via FilterChips. Output mute
also flips the audio engine's local output-muted flag so
playback silences immediately, before the server acknowledges.
* **Master output gain** slider (0–200%). Plumbed through an
`AtomicU32` (f32 bits) on the engine that the cpal output
callback multiplies into every sample.
* **Bookmarks**: SQLite-backed list with Save / Connect / Delete
actions. Bookmarks persist across app restarts; tapping one
pre-fills the form and dials immediately.
Hardening
---------
* **Encrypted identity at rest** (RISK-PoC-002 closure for the
file-only threat model). ChaCha20-Poly1305 envelope: nonce +
ciphertext written atomically with mode 0600; 32-byte DEK in a
separate `identity.dek` file. Legacy plaintext identity files
are auto-detected, read, and upgraded on the next save. Full OS-
keyring integration is still v0.4 work — documented in the
store's doc comment.
* **Mobile voice-comm routing**: on Android, `AudioEngine::start`
uses JNI to set `AudioManager.setMode(MODE_IN_COMMUNICATION)`
when `cfg.mobile_voice_preset` is true (default). This engages
the device-side AEC/NS pipeline on most Pixel/Moto/Samsung
hardware even though cpal still opens the AAudio default input
preset. Full `setInputPreset(VOICE_COMMUNICATION)` switch is
still RISK-AUDIO-MOBILE-001 (needs cpal upstream or an Oboe
fork).
* **Log noise**: bridge default `EnvFilter` now silences
`tsproto::resend=error` and `tsproto::packet_codec=error` so
the redacted diagnostic export is human-readable. Still
overridable via `RUST_LOG=...`.
Engineering
-----------
* **`chanora_storage`** gains `BookmarkRepository` (rusqlite
bundled) with `add` / `update` / `delete` / `list`. The
identity store now layers on `chacha20poly1305` + `rand` +
`zeroize` for the envelope.
* **`chanora_protocol`** exposes `move_to_channel` and
`set_muted` on `ProtocolClient`, dispatched through the
existing `connection_task` request channel onto tsclientlib's
generated `client.client_move(...)` and
`state.client_update().set_input_muted/set_output_muted(...)`
paths.
* **`chanora_core::ChanoraSession`** wires the bookmark store
next to the identity store inside `init_storage`, and adds
`list_bookmarks` / `add_bookmark` / `update_bookmark` /
`delete_bookmark` / `move_to_channel` / `set_self_muted` /
`set_output_gain`.
* **`chanora_audio::AudioEngine`** carries `output_gain` and
`output_muted` atomics; the output callback consults both. The
Android branch of `start()` engages MODE_IN_COMMUNICATION via
a small JNI helper that reuses the `ndk_context` global set by
the bridge's `android_init` hook.
* **`chanora_bridge::api`** adds `set_input_muted`,
`set_output_muted`, `set_output_gain`, `move_to_channel`,
`list_bookmarks`, `add_bookmark`, `update_bookmark`,
`delete_bookmark`, and the `BridgeBookmark` DTO. FRB v2.12
codegen regenerated.
Tests + CI
----------
* `chanora_storage` test count rises from 3 to 8 — bookmark CRUD
round-trip, missing-row → `NotFound`, encrypted round-trip
(verifies ciphertext is not the plaintext on disk), and the
legacy plaintext upgrade path.
* New `.github/workflows/ci.yml`: `cargo check --workspace`,
`cargo test --workspace --no-fail-fast`, `cargo clippy`
(advisory), `flutter analyze`, and `flutter test` excluding
the live-server `e2e` tag.
Live-verified on Moto G Stylus 5G against cn.teamspeak.app:
saved a bookmark, reconnected via it, joined a non-default
channel via tap, toggled both mutes, slid the volume, and the
redacted diagnostic export confirmed `AudioManager mode set to
MODE_IN_COMMUNICATION`, `client_move sent`, and `client_update
sent` lines.
This commit is contained in:
@@ -43,9 +43,15 @@
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use chacha20poly1305::aead::{Aead, KeyInit, OsRng};
|
||||
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
|
||||
use rand::RngCore;
|
||||
use rusqlite::{params, Connection};
|
||||
use thiserror::Error;
|
||||
use tracing::{info, warn};
|
||||
use zeroize::Zeroize;
|
||||
|
||||
/// Errors raised by either storage repository.
|
||||
#[derive(Debug, Error)]
|
||||
@@ -65,6 +71,11 @@ pub enum StorageError {
|
||||
/// Filesystem I/O error (Beta file-fallback store).
|
||||
#[error("io: {0}")]
|
||||
Io(String),
|
||||
/// Cryptographic operation failed (key generation, encrypt, or
|
||||
/// decrypt). Typically indicates a corrupted DEK or tampered
|
||||
/// identity file.
|
||||
#[error("crypto: {0}")]
|
||||
Crypto(String),
|
||||
}
|
||||
|
||||
/// Marker trait for the non-secret database side. Concrete impl will
|
||||
@@ -77,74 +88,175 @@ pub trait LocalDatabaseRepository: Send + Sync {}
|
||||
/// promoted from the secure-storage PoC.
|
||||
pub trait SecretStorageRepository: Send + Sync {}
|
||||
|
||||
/// Beta identity store: a single file containing the base64 TS3
|
||||
/// identity string. The directory is created on first use; on Unix
|
||||
/// the file is written with mode 0600 so other local users can't
|
||||
/// read it. **Not** encrypted at rest — that is the v0.4 task.
|
||||
/// Beta identity store: a single ChaCha20-Poly1305-encrypted file
|
||||
/// containing the base64 TS3 identity string. The Data Encryption
|
||||
/// Key (DEK) is 32 random bytes stored alongside in a separate
|
||||
/// `identity.dek` file with the same 0600 permissions on Unix.
|
||||
///
|
||||
/// The dual-file layout means an attacker who recovers either file
|
||||
/// alone can't decrypt the identity. The honest threat model:
|
||||
///
|
||||
/// * **Helps against** stale backups, casual filesystem snooping
|
||||
/// that grabs one file but not the other, and accidental leaks
|
||||
/// to diagnostic exports (the ciphertext is never logged).
|
||||
/// * **Does NOT help against** a full app-private storage dump (an
|
||||
/// attacker who can read one file in the directory can read both).
|
||||
/// The v0.4 storage rework lands proper OS-keyring backing for the
|
||||
/// DEK so this two-file weakness is closed.
|
||||
///
|
||||
/// File format: `identity.tskey` = `[12-byte nonce][AEAD ciphertext+tag]`.
|
||||
/// Legacy plaintext files written by v0.3 are still readable; the
|
||||
/// next `save()` upgrades them to encrypted form (and shreds the
|
||||
/// plaintext temp file via the atomic rename).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct IdentityFileStore {
|
||||
path: PathBuf,
|
||||
dek_path: PathBuf,
|
||||
}
|
||||
|
||||
impl IdentityFileStore {
|
||||
/// Construct a store rooted at `dir`. The directory is created
|
||||
/// recursively if it does not already exist.
|
||||
/// Construct a store rooted at `dir`. Creates the directory and
|
||||
/// the DEK on first use; subsequent uses reuse the existing DEK.
|
||||
pub fn new(dir: impl AsRef<Path>) -> Result<Self, StorageError> {
|
||||
let dir = dir.as_ref();
|
||||
fs::create_dir_all(dir).map_err(|e| StorageError::Io(format!("mkdir {dir:?}: {e}")))?;
|
||||
Ok(Self {
|
||||
let store = Self {
|
||||
path: dir.join("identity.tskey"),
|
||||
})
|
||||
dek_path: dir.join("identity.dek"),
|
||||
};
|
||||
// Ensure a DEK exists. Subsequent operations expect it.
|
||||
store.ensure_dek()?;
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// Path to the underlying file. Exposed for diagnostics.
|
||||
/// Path to the underlying identity file. Exposed for diagnostics.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Read the persisted identity, if any. Returns `Ok(None)` when
|
||||
/// no identity has been saved yet — that is not an error.
|
||||
fn ensure_dek(&self) -> Result<(), StorageError> {
|
||||
if self.dek_path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut key = [0u8; 32];
|
||||
OsRng.fill_bytes(&mut key);
|
||||
{
|
||||
let mut f = open_private(&self.dek_path)?;
|
||||
f.write_all(&key)
|
||||
.map_err(|e| StorageError::Io(format!("write dek: {e}")))?;
|
||||
f.sync_all()
|
||||
.map_err(|e| StorageError::Io(format!("sync dek: {e}")))?;
|
||||
}
|
||||
key.zeroize();
|
||||
info!(target: "chanora_storage", path = ?self.dek_path, "DEK generated");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_dek(&self) -> Result<[u8; 32], StorageError> {
|
||||
let mut f = fs::File::open(&self.dek_path)
|
||||
.map_err(|e| StorageError::Io(format!("open dek {:?}: {e}", self.dek_path)))?;
|
||||
let mut key = [0u8; 32];
|
||||
f.read_exact(&mut key)
|
||||
.map_err(|e| StorageError::Io(format!("read dek: {e}")))?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
/// Read the persisted identity, if any. Transparently handles
|
||||
/// the legacy plaintext format (pre-External Beta).
|
||||
pub fn load(&self) -> Result<Option<String>, StorageError> {
|
||||
match fs::File::open(&self.path) {
|
||||
Ok(mut f) => {
|
||||
let mut buf = String::new();
|
||||
f.read_to_string(&mut buf)
|
||||
.map_err(|e| StorageError::Io(format!("read {:?}: {e}", self.path)))?;
|
||||
let trimmed = buf.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed))
|
||||
}
|
||||
let mut f = match fs::File::open(&self.path) {
|
||||
Ok(f) => f,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(StorageError::Io(format!("open {:?}: {e}", self.path))),
|
||||
};
|
||||
let mut buf = Vec::new();
|
||||
f.read_to_end(&mut buf)
|
||||
.map_err(|e| StorageError::Io(format!("read {:?}: {e}", self.path)))?;
|
||||
if buf.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Encrypted format: at least nonce (12) + tag (16) = 28
|
||||
// bytes, and the first byte should not be a printable ASCII
|
||||
// base64 character. Heuristic: a legacy plaintext file
|
||||
// starts with an ASCII digit (counter prefix) or an ASCII
|
||||
// letter (raw base64 key). If the first byte is non-ASCII
|
||||
// or non-printable, treat as ciphertext.
|
||||
if buf.len() >= 28 && !is_plausibly_legacy_plaintext(&buf) {
|
||||
let mut key_bytes = self.load_dek()?;
|
||||
let key = Key::from_slice(&key_bytes);
|
||||
let cipher = ChaCha20Poly1305::new(key);
|
||||
let nonce_bytes = &buf[..12];
|
||||
let nonce = Nonce::from_slice(nonce_bytes);
|
||||
let pt = cipher
|
||||
.decrypt(nonce, &buf[12..])
|
||||
.map_err(|e| {
|
||||
key_bytes.zeroize();
|
||||
StorageError::Crypto(format!("decrypt: {e}"))
|
||||
})?;
|
||||
key_bytes.zeroize();
|
||||
let s = String::from_utf8(pt)
|
||||
.map_err(|e| StorageError::Crypto(format!("plaintext not utf8: {e}")))?;
|
||||
let trimmed = s.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(StorageError::Io(format!("open {:?}: {e}", self.path))),
|
||||
return Ok(Some(trimmed));
|
||||
}
|
||||
|
||||
// Legacy plaintext path. We do NOT auto-upgrade here —
|
||||
// upgrade happens on the next save() to keep load()
|
||||
// side-effect-free.
|
||||
warn!(
|
||||
target: "chanora_storage",
|
||||
"identity file is in legacy plaintext format; will encrypt on next save"
|
||||
);
|
||||
let s = String::from_utf8(buf)
|
||||
.map_err(|e| StorageError::Io(format!("legacy not utf8: {e}")))?;
|
||||
let trimmed = s.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed))
|
||||
}
|
||||
}
|
||||
|
||||
/// Persist `identity` to disk, replacing any previous content.
|
||||
/// On Unix the file is written with mode 0600.
|
||||
/// On Unix the file is written with mode 0600. Encrypted with
|
||||
/// ChaCha20-Poly1305 using the per-install DEK.
|
||||
pub fn save(&self, identity: &str) -> Result<(), StorageError> {
|
||||
// Write atomically: temp file + rename. Avoids leaving a
|
||||
// half-written identity on the device after a crash or
|
||||
// power loss.
|
||||
let plaintext = identity.trim().as_bytes();
|
||||
let mut key_bytes = self.load_dek()?;
|
||||
let key = Key::from_slice(&key_bytes);
|
||||
let cipher = ChaCha20Poly1305::new(key);
|
||||
let mut nonce_bytes = [0u8; 12];
|
||||
OsRng.fill_bytes(&mut nonce_bytes);
|
||||
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||
let ct = cipher.encrypt(nonce, plaintext).map_err(|e| {
|
||||
key_bytes.zeroize();
|
||||
StorageError::Crypto(format!("encrypt: {e}"))
|
||||
})?;
|
||||
key_bytes.zeroize();
|
||||
|
||||
// Atomic write: temp file + rename.
|
||||
let tmp = self.path.with_extension("tskey.tmp");
|
||||
{
|
||||
let mut f = open_private(&tmp)?;
|
||||
f.write_all(identity.trim().as_bytes())
|
||||
.map_err(|e| StorageError::Io(format!("write {tmp:?}: {e}")))?;
|
||||
f.write_all(b"\n")
|
||||
.map_err(|e| StorageError::Io(format!("write nl: {e}")))?;
|
||||
f.write_all(&nonce_bytes)
|
||||
.map_err(|e| StorageError::Io(format!("write nonce: {e}")))?;
|
||||
f.write_all(&ct)
|
||||
.map_err(|e| StorageError::Io(format!("write ct: {e}")))?;
|
||||
f.sync_all()
|
||||
.map_err(|e| StorageError::Io(format!("sync {tmp:?}: {e}")))?;
|
||||
}
|
||||
fs::rename(&tmp, &self.path)
|
||||
.map_err(|e| StorageError::Io(format!("rename {tmp:?} -> {:?}: {e}", self.path)))?;
|
||||
info!(target: "chanora_storage", path = ?self.path, "identity persisted");
|
||||
info!(target: "chanora_storage", path = ?self.path, "identity persisted (encrypted)");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove any persisted identity. No-op if none exists.
|
||||
/// Remove any persisted identity. No-op if none exists. Leaves
|
||||
/// the DEK in place so future saves don't generate a new one.
|
||||
pub fn clear(&self) -> Result<(), StorageError> {
|
||||
match fs::remove_file(&self.path) {
|
||||
Ok(()) => {
|
||||
@@ -160,6 +272,31 @@ impl IdentityFileStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// True if `buf` looks like a legacy plaintext identity (printable
|
||||
/// ASCII with a digit/letter first byte and at most a trailing
|
||||
/// newline). False for ciphertext.
|
||||
fn is_plausibly_legacy_plaintext(buf: &[u8]) -> bool {
|
||||
if buf.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let first = buf[0];
|
||||
if !(first.is_ascii_alphanumeric() || first == b'+' || first == b'/') {
|
||||
return false;
|
||||
}
|
||||
// The TS3 identity format is base64 + a counter prefix; all
|
||||
// bytes are printable ASCII. The ciphertext is uniformly random.
|
||||
buf.iter().all(|&b| {
|
||||
b.is_ascii_alphanumeric()
|
||||
|| b == b'+'
|
||||
|| b == b'/'
|
||||
|| b == b'='
|
||||
|| b == b'V'
|
||||
|| b == b'\n'
|
||||
|| b == b'\r'
|
||||
|| b == b' '
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn open_private(p: &Path) -> Result<fs::File, StorageError> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
@@ -186,6 +323,140 @@ fn open_private(p: &Path) -> Result<fs::File, StorageError> {
|
||||
.map_err(|e| StorageError::Io(format!("open {p:?}: {e}")))
|
||||
}
|
||||
|
||||
/// A persisted bookmark: a friendly label paired with a TS3 server
|
||||
/// address and the nickname the user wants when connecting.
|
||||
///
|
||||
/// Bookmark rows are uniquely identified by an auto-incrementing
|
||||
/// `id`. The `display_name` is purely cosmetic. `host` is the same
|
||||
/// string the user would type into the connect form.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Bookmark {
|
||||
/// Stable row id assigned by SQLite.
|
||||
pub id: i64,
|
||||
/// User-facing label.
|
||||
pub display_name: String,
|
||||
/// `hostname[:port]` or TSDNS name.
|
||||
pub host: String,
|
||||
/// Nickname to use for this bookmark.
|
||||
pub nickname: String,
|
||||
/// Optional remembered server password. Stored as plain text in
|
||||
/// the SQLite file (Beta gap, RISK-PoC-002). v0.4 will lift
|
||||
/// passwords into the keyring.
|
||||
pub password: Option<String>,
|
||||
}
|
||||
|
||||
/// SQLite-backed bookmark store. The DB file lives at
|
||||
/// `<storage_dir>/chanora.db`. The schema is migrated on
|
||||
/// construction; failures here abort the constructor rather than
|
||||
/// poisoning later calls.
|
||||
pub struct BookmarkRepository {
|
||||
conn: Mutex<Connection>,
|
||||
}
|
||||
|
||||
impl BookmarkRepository {
|
||||
/// Open or create the bookmark database under `dir`.
|
||||
pub fn new(dir: impl AsRef<Path>) -> Result<Self, StorageError> {
|
||||
let dir = dir.as_ref();
|
||||
fs::create_dir_all(dir).map_err(|e| StorageError::Io(format!("mkdir {dir:?}: {e}")))?;
|
||||
let path = dir.join("chanora.db");
|
||||
let conn = Connection::open(&path)
|
||||
.map_err(|e| StorageError::Sqlite(format!("open {path:?}: {e}")))?;
|
||||
conn.pragma_update(None, "foreign_keys", "ON")
|
||||
.map_err(|e| StorageError::Sqlite(format!("pragma: {e}")))?;
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS bookmarks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
display_name TEXT NOT NULL,
|
||||
host TEXT NOT NULL,
|
||||
nickname TEXT NOT NULL,
|
||||
password TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS schema_version (
|
||||
v INTEGER PRIMARY KEY
|
||||
);
|
||||
INSERT OR IGNORE INTO schema_version(v) VALUES (1);",
|
||||
)
|
||||
.map_err(|e| StorageError::Migration(format!("init schema: {e}")))?;
|
||||
info!(target: "chanora_storage", path = ?path, "bookmark db opened");
|
||||
Ok(Self { conn: Mutex::new(conn) })
|
||||
}
|
||||
|
||||
/// Insert a new bookmark and return its assigned id. The `id`
|
||||
/// field on the input is ignored.
|
||||
pub fn add(&self, b: &Bookmark) -> Result<i64, StorageError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|_| StorageError::Sqlite("poisoned lock".to_string()))?;
|
||||
conn.execute(
|
||||
"INSERT INTO bookmarks (display_name, host, nickname, password) VALUES (?1, ?2, ?3, ?4)",
|
||||
params![b.display_name, b.host, b.nickname, b.password],
|
||||
)
|
||||
.map_err(|e| StorageError::Sqlite(format!("insert: {e}")))?;
|
||||
Ok(conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
/// Replace an existing bookmark identified by `id`. Errors with
|
||||
/// [`StorageError::NotFound`] if no such row exists.
|
||||
pub fn update(&self, b: &Bookmark) -> Result<(), StorageError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|_| StorageError::Sqlite("poisoned lock".to_string()))?;
|
||||
let n = conn
|
||||
.execute(
|
||||
"UPDATE bookmarks SET display_name=?1, host=?2, nickname=?3, password=?4 WHERE id=?5",
|
||||
params![b.display_name, b.host, b.nickname, b.password, b.id],
|
||||
)
|
||||
.map_err(|e| StorageError::Sqlite(format!("update: {e}")))?;
|
||||
if n == 0 {
|
||||
Err(StorageError::NotFound)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete a bookmark by id. No-op if it doesn't exist.
|
||||
pub fn delete(&self, id: i64) -> Result<(), StorageError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|_| StorageError::Sqlite("poisoned lock".to_string()))?;
|
||||
conn.execute("DELETE FROM bookmarks WHERE id = ?1", params![id])
|
||||
.map_err(|e| StorageError::Sqlite(format!("delete: {e}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List all bookmarks ordered by id (insertion order).
|
||||
pub fn list(&self) -> Result<Vec<Bookmark>, StorageError> {
|
||||
let conn = self
|
||||
.conn
|
||||
.lock()
|
||||
.map_err(|_| StorageError::Sqlite("poisoned lock".to_string()))?;
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT id, display_name, host, nickname, password FROM bookmarks ORDER BY id",
|
||||
)
|
||||
.map_err(|e| StorageError::Sqlite(format!("prepare: {e}")))?;
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok(Bookmark {
|
||||
id: row.get(0)?,
|
||||
display_name: row.get(1)?,
|
||||
host: row.get(2)?,
|
||||
nickname: row.get(3)?,
|
||||
password: row.get(4)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| StorageError::Sqlite(format!("query: {e}")))?;
|
||||
let mut out = Vec::new();
|
||||
for r in rows {
|
||||
out.push(r.map_err(|e| StorageError::Sqlite(format!("row: {e}")))?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -220,6 +491,96 @@ mod tests {
|
||||
assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmark_round_trip() {
|
||||
let tmp = tempdir();
|
||||
let repo = BookmarkRepository::new(&tmp).unwrap();
|
||||
assert!(repo.list().unwrap().is_empty());
|
||||
let id = repo
|
||||
.add(&Bookmark {
|
||||
id: 0,
|
||||
display_name: "home".to_string(),
|
||||
host: "cn.teamspeak.app".to_string(),
|
||||
nickname: "u".to_string(),
|
||||
password: None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(id > 0);
|
||||
let rows = repo.list().unwrap();
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0].display_name, "home");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmark_update_and_delete() {
|
||||
let tmp = tempdir();
|
||||
let repo = BookmarkRepository::new(&tmp).unwrap();
|
||||
let id = repo
|
||||
.add(&Bookmark {
|
||||
id: 0,
|
||||
display_name: "a".to_string(),
|
||||
host: "h".to_string(),
|
||||
nickname: "n".to_string(),
|
||||
password: Some("pw".to_string()),
|
||||
})
|
||||
.unwrap();
|
||||
repo.update(&Bookmark {
|
||||
id,
|
||||
display_name: "b".to_string(),
|
||||
host: "h2".to_string(),
|
||||
nickname: "n2".to_string(),
|
||||
password: None,
|
||||
})
|
||||
.unwrap();
|
||||
let rows = repo.list().unwrap();
|
||||
assert_eq!(rows[0].display_name, "b");
|
||||
assert_eq!(rows[0].password, None);
|
||||
repo.delete(id).unwrap();
|
||||
assert!(repo.list().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bookmark_update_missing_is_notfound() {
|
||||
let tmp = tempdir();
|
||||
let repo = BookmarkRepository::new(&tmp).unwrap();
|
||||
let r = repo.update(&Bookmark {
|
||||
id: 999,
|
||||
display_name: "x".to_string(),
|
||||
host: "h".to_string(),
|
||||
nickname: "n".to_string(),
|
||||
password: None,
|
||||
});
|
||||
assert!(matches!(r, Err(StorageError::NotFound)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_round_trip() {
|
||||
let tmp = tempdir();
|
||||
let store = IdentityFileStore::new(&tmp).unwrap();
|
||||
store.save("3456V/abcdef==").unwrap();
|
||||
// The bytes on disk are not the plaintext.
|
||||
let raw = fs::read(store.path()).unwrap();
|
||||
assert!(!raw.windows(6).any(|w| w == b"abcdef"));
|
||||
// load() returns the original.
|
||||
assert_eq!(store.load().unwrap().as_deref(), Some("3456V/abcdef=="));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_plaintext_is_read_and_upgraded() {
|
||||
let tmp = tempdir();
|
||||
// Pre-Beta on-disk format: raw base64 with counter prefix.
|
||||
let path = tmp.join("identity.tskey");
|
||||
fs::write(&path, b"9999VabcdefghIJKLmnop=\n").unwrap();
|
||||
let store = IdentityFileStore::new(&tmp).unwrap();
|
||||
let v = store.load().unwrap();
|
||||
assert_eq!(v.as_deref(), Some("9999VabcdefghIJKLmnop="));
|
||||
// Save round-trips through encrypted format.
|
||||
store.save("9999VabcdefghIJKLmnop=").unwrap();
|
||||
let raw = fs::read(store.path()).unwrap();
|
||||
assert!(!raw.starts_with(b"9999"));
|
||||
assert_eq!(store.load().unwrap().as_deref(), Some("9999VabcdefghIJKLmnop="));
|
||||
}
|
||||
|
||||
fn tempdir() -> PathBuf {
|
||||
let p = std::env::temp_dir()
|
||||
.join("chanora_storage_test")
|
||||
|
||||
Reference in New Issue
Block a user