use std::fmt;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use sew_e2ee::{
DeviceIdentity, DeviceStore, Enrollment, MemberId, Pins, SoftwareSigner, TrustAnchors,
};
pub use sew_proto::e2ee::DevicePlatform;
use sew_proto::e2ee::reasons;
use zeroize::Zeroizing;
use crate::e2ee::transport::KeyTransport;
pub mod hardware;
#[cfg(feature = "sim-software-key")]
pub use hardware::SimSoftwareKey;
pub use hardware::{DeviceKey, HardwareDeviceKey, p1363_from_der};
#[cfg(all(
feature = "sim-software-key",
not(any(
all(target_os = "ios", target_abi = "sim"),
all(target_os = "ios", target_arch = "x86_64"),
all(
target_os = "android",
any(target_arch = "x86_64", target_arch = "x86")
),
))
))]
compile_error!(
"sew-call-client: feature `sim-software-key` builds only for the iOS simulator \
(aarch64-apple-ios-sim, x86_64-apple-ios) and the x86 Android emulator \
(x86_64-linux-android, i686-linux-android); never ship it"
);
pub const fn default_platform() -> DevicePlatform {
if cfg!(target_os = "ios") {
DevicePlatform::Ios
} else if cfg!(target_os = "android") {
DevicePlatform::Android
} else {
DevicePlatform::Desktop
}
}
pub use sew_e2ee::StoredDevice;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyStorage {
Host,
Os,
File,
Memory,
Hardware,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DeviceWarning {
KeyStorageFile,
PinsReset,
}
impl DeviceWarning {
pub fn code(self) -> &'static str {
match self {
DeviceWarning::KeyStorageFile => "key_storage_file",
DeviceWarning::PinsReset => "pins_reset",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum DeviceError {
#[error("device store: {0}")]
Store(String),
#[error("enrolment refused ({status} {reason:?})")]
EnrollRefused {
status: u16,
reason: Option<String>,
},
#[error("certificate refused: {0}")]
Certificate(String),
#[error("hardware key unavailable: {0}")]
Unavailable(String),
#[error("a call is live")]
InCall,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DeviceKeyId {
pub install_id: u64,
pub member_id: MemberId,
pub device_scope: String,
}
impl DeviceKeyId {
pub fn account(&self) -> String {
format!(
"{}:{}:{}",
self.install_id, self.member_id, self.device_scope
)
}
}
#[derive(Clone)]
pub struct DeviceKeyRecord {
pub key: Zeroizing<[u8; 32]>,
pub device: StoredDevice,
}
impl fmt::Debug for DeviceKeyRecord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DeviceKeyRecord")
.field("key", &"<redacted>")
.field("install_id", &self.device.install_id)
.field("member_id", &self.device.member_id)
.field("device_id", &self.device.device_id)
.finish()
}
}
pub trait DeviceKeyStore: Send + Sync + 'static {
fn load(&self, id: &DeviceKeyId) -> Result<Option<DeviceKeyRecord>, DeviceError>;
fn store(&self, id: &DeviceKeyId, record: &DeviceKeyRecord) -> Result<(), DeviceError>;
fn clear(&self, id: &DeviceKeyId) -> Result<(), DeviceError>;
}
#[derive(Default)]
pub struct MemoryDeviceKeyStore {
entries: std::sync::Mutex<std::collections::BTreeMap<DeviceKeyId, DeviceKeyRecord>>,
}
impl fmt::Debug for MemoryDeviceKeyStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("MemoryDeviceKeyStore(***)")
}
}
impl MemoryDeviceKeyStore {
pub fn new() -> MemoryDeviceKeyStore {
MemoryDeviceKeyStore::default()
}
pub fn len(&self) -> usize {
crate::e2ee::keys::lock(&self.entries).len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl DeviceKeyStore for MemoryDeviceKeyStore {
fn load(&self, id: &DeviceKeyId) -> Result<Option<DeviceKeyRecord>, DeviceError> {
Ok(crate::e2ee::keys::lock(&self.entries).get(id).cloned())
}
fn store(&self, id: &DeviceKeyId, record: &DeviceKeyRecord) -> Result<(), DeviceError> {
crate::e2ee::keys::lock(&self.entries).insert(id.clone(), record.clone());
Ok(())
}
fn clear(&self, id: &DeviceKeyId) -> Result<(), DeviceError> {
crate::e2ee::keys::lock(&self.entries).remove(id);
Ok(())
}
}
pub trait SecretStore: Send + Sync + 'static {
fn kind(&self) -> KeyStorage;
fn load(&self, account: &str) -> Result<Option<Zeroizing<[u8; 32]>>, DeviceError>;
fn save(&self, account: &str, scalar: &[u8; 32]) -> Result<(), DeviceError>;
fn delete(&self, account: &str) -> Result<(), DeviceError>;
}
#[derive(Default)]
pub struct MemorySecretStore {
keys: std::sync::Mutex<std::collections::BTreeMap<String, Zeroizing<[u8; 32]>>>,
}
impl fmt::Debug for MemorySecretStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("MemorySecretStore(***)")
}
}
impl MemorySecretStore {
pub fn new() -> MemorySecretStore {
MemorySecretStore::default()
}
}
impl SecretStore for MemorySecretStore {
fn kind(&self) -> KeyStorage {
KeyStorage::Memory
}
fn load(&self, account: &str) -> Result<Option<Zeroizing<[u8; 32]>>, DeviceError> {
Ok(crate::e2ee::keys::lock(&self.keys).get(account).cloned())
}
fn save(&self, account: &str, scalar: &[u8; 32]) -> Result<(), DeviceError> {
crate::e2ee::keys::lock(&self.keys).insert(account.to_owned(), Zeroizing::new(*scalar));
Ok(())
}
fn delete(&self, account: &str) -> Result<(), DeviceError> {
crate::e2ee::keys::lock(&self.keys).remove(account);
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct FileSecretStore {
dir: PathBuf,
}
impl FileSecretStore {
pub fn new(dir: impl Into<PathBuf>) -> FileSecretStore {
FileSecretStore { dir: dir.into() }
}
fn path(&self, account: &str) -> PathBuf {
let scope = account.rsplit(':').next().unwrap_or(account);
self.dir.join(format!("device-{}.key", sanitize(scope)))
}
}
impl SecretStore for FileSecretStore {
fn kind(&self) -> KeyStorage {
KeyStorage::File
}
fn load(&self, account: &str) -> Result<Option<Zeroizing<[u8; 32]>>, DeviceError> {
let p = self.path(account);
let text = match std::fs::read_to_string(&p) {
Ok(t) => Zeroizing::new(t),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(DeviceError::Store(format!("read key: {}", e.kind()))),
};
let mut out = Zeroizing::new([0u8; 32]);
match hex::decode_to_slice(text.trim(), out.as_mut()) {
Ok(()) => Ok(Some(out)),
Err(_) => Ok(None),
}
}
fn save(&self, account: &str, scalar: &[u8; 32]) -> Result<(), DeviceError> {
ensure_dir(&self.dir)?;
let text = Zeroizing::new(hex::encode(scalar));
write_atomic(&self.path(account), text.as_bytes())
}
fn delete(&self, account: &str) -> Result<(), DeviceError> {
match std::fs::remove_file(self.path(account)) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(DeviceError::Store(format!("delete key: {}", e.kind()))),
}
}
}
#[cfg(feature = "keyring-store")]
#[derive(Debug, Clone)]
pub struct OsSecretStore {
service: String,
}
#[cfg(feature = "keyring-store")]
impl OsSecretStore {
pub fn new(app_id: &str) -> OsSecretStore {
OsSecretStore {
service: format!("sew-voice.{app_id}"),
}
}
fn entry(&self, account: &str) -> Result<keyring::Entry, DeviceError> {
keyring::Entry::new(&self.service, account)
.map_err(|e| DeviceError::Store(format!("os store: {}", kind_of(&e))))
}
pub fn available(&self) -> bool {
let Ok(e) = self.entry("probe") else {
return false;
};
match e.get_secret() {
Ok(_) | Err(keyring::Error::NoEntry) => true,
Err(_) => false,
}
}
}
#[cfg(feature = "keyring-store")]
fn kind_of(e: &keyring::Error) -> &'static str {
match e {
keyring::Error::NoEntry => "no entry",
keyring::Error::NoStorageAccess(_) => "no storage access",
keyring::Error::PlatformFailure(_) => "platform failure",
keyring::Error::BadEncoding(_) => "bad encoding",
keyring::Error::TooLong(..) => "too long",
keyring::Error::Invalid(..) => "invalid",
keyring::Error::Ambiguous(_) => "ambiguous",
_ => "other",
}
}
#[cfg(feature = "keyring-store")]
impl SecretStore for OsSecretStore {
fn kind(&self) -> KeyStorage {
KeyStorage::Os
}
fn load(&self, account: &str) -> Result<Option<Zeroizing<[u8; 32]>>, DeviceError> {
match self.entry(account)?.get_secret() {
Ok(v) => {
let v = Zeroizing::new(v);
let a: Option<[u8; 32]> = v.as_slice().try_into().ok();
Ok(a.map(Zeroizing::new))
}
Err(keyring::Error::NoEntry) => Ok(None),
Err(e) => Err(DeviceError::Store(format!("os store: {}", kind_of(&e)))),
}
}
fn save(&self, account: &str, scalar: &[u8; 32]) -> Result<(), DeviceError> {
self.entry(account)?
.set_secret(scalar)
.map_err(|e| DeviceError::Store(format!("os store: {}", kind_of(&e))))
}
fn delete(&self, account: &str) -> Result<(), DeviceError> {
match self.entry(account)?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(DeviceError::Store(format!("os store: {}", kind_of(&e)))),
}
}
}
fn sanitize(s: &str) -> String {
s.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
.take(64)
.collect()
}
fn ensure_dir(dir: &Path) -> Result<(), DeviceError> {
std::fs::create_dir_all(dir).map_err(|e| DeviceError::Store(format!("mkdir: {}", e.kind())))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
.map_err(|e| DeviceError::Store(format!("chmod dir: {}", e.kind())))?;
}
Ok(())
}
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), DeviceError> {
let dir = path
.parent()
.ok_or_else(|| DeviceError::Store("no parent directory".to_owned()))?;
let name = path
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| DeviceError::Store("bad file name".to_owned()))?;
let tmp = dir.join(format!(".{name}.{:016x}.tmp", rand::random::<u64>()));
let io = |what: &str, e: std::io::Error| DeviceError::Store(format!("{what}: {}", e.kind()));
{
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt as _;
opts.mode(0o600);
}
let mut f = opts.open(&tmp).map_err(|e| io("create", e))?;
f.write_all(bytes).map_err(|e| io("write", e))?;
f.sync_all().map_err(|e| io("fsync", e))?;
}
if let Err(e) = std::fs::rename(&tmp, path) {
let _ = std::fs::remove_file(&tmp);
return Err(io("rename", e));
}
#[cfg(unix)]
if let Ok(d) = std::fs::File::open(dir) {
let _ = d.sync_all();
}
Ok(())
}
#[derive(Serialize, Deserialize, Default)]
struct FileData {
v: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
device: Option<DeviceWire>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pins: Option<PinsWire>,
}
#[derive(Serialize, Deserialize, Clone)]
struct DeviceWire {
member_id: MemberId,
device_id: MemberId,
pubkey: String,
cert: String,
}
#[derive(Serialize, Deserialize, Clone)]
struct PinsWire {
ca_public: String,
ds_public: String,
external_sender: String,
}
fn h<const N: usize>(s: &str) -> Option<[u8; N]> {
let mut out = [0u8; N];
hex::decode_to_slice(s, &mut out).ok()?;
Some(out)
}
pub struct DeviceFile {
path: PathBuf,
install_id: u64,
data: FileData,
existed: bool,
}
impl fmt::Debug for DeviceFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DeviceFile")
.field("install_id", &self.install_id)
.field("device", &self.data.device.is_some())
.field("pins", &self.data.pins.is_some())
.finish()
}
}
impl DeviceFile {
pub fn open(
dir: &Path,
install_id: u64,
device_scope: &str,
) -> Result<DeviceFile, DeviceError> {
let path = dir.join(format!("device-{}.json", sanitize(device_scope)));
let (data, existed) = match std::fs::read(&path) {
Ok(b) => (serde_json::from_slice(&b).unwrap_or_default(), true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (FileData::default(), false),
Err(e) => return Err(DeviceError::Store(format!("read: {}", e.kind()))),
};
Ok(DeviceFile {
path,
install_id,
data,
existed,
})
}
pub fn path(&self) -> &Path {
&self.path
}
fn flush(&self) -> Result<(), String> {
let dir = self.path.parent().ok_or("no parent directory")?;
ensure_dir(dir).map_err(|e| e.to_string())?;
let mut data = serde_json::to_vec_pretty(&FileData {
v: 1,
device: self.data.device.clone(),
pins: self.data.pins.clone(),
})
.map_err(|e| e.to_string())?;
data.push(b'\n');
write_atomic(&self.path, &data).map_err(|e| e.to_string())
}
pub fn forget_device(&mut self) -> Result<(), DeviceError> {
self.data.device = None;
self.flush().map_err(DeviceError::Store)
}
}
impl DeviceStore for DeviceFile {
fn load(&self, install_id: u64) -> Option<StoredDevice> {
if install_id != self.install_id {
return None;
}
let d = self.data.device.as_ref()?;
Some(StoredDevice {
install_id,
member_id: d.member_id,
device_id: d.device_id,
pubkey: h::<65>(&d.pubkey)?,
cert: hex::decode(&d.cert).ok()?,
})
}
fn save(&mut self, dev: &StoredDevice) -> Result<(), String> {
if dev.install_id != self.install_id {
return Err("another install".to_owned());
}
self.data.device = Some(DeviceWire {
member_id: dev.member_id,
device_id: dev.device_id,
pubkey: hex::encode(dev.pubkey),
cert: hex::encode(&dev.cert),
});
self.flush()
}
fn clear(&mut self, install_id: u64) {
if install_id == self.install_id {
self.data.device = None;
self.data.pins = None;
let _ = self.flush();
}
}
fn load_pins(&self, install_id: u64) -> Option<Pins> {
if install_id != self.install_id {
return None;
}
let p = self.data.pins.as_ref()?;
Some(Pins {
install_id,
ca_public: h::<32>(&p.ca_public)?,
ds_public: h::<32>(&p.ds_public)?,
external_sender: hex::decode(&p.external_sender).ok()?,
})
}
fn save_pins(&mut self, pins: &Pins) -> Result<(), String> {
if pins.install_id != self.install_id {
return Err("another install".to_owned());
}
self.data.pins = Some(PinsWire {
ca_public: hex::encode(pins.ca_public),
ds_public: hex::encode(pins.ds_public),
external_sender: hex::encode(&pins.external_sender),
});
self.flush()
}
}
#[derive(Clone, Default)]
#[non_exhaustive]
pub enum StoreChoice {
#[default]
Auto,
File,
Custom(Arc<dyn SecretStore>),
Host(Arc<dyn DeviceKeyStore>),
Hardware(Arc<dyn HardwareDeviceKey>),
}
impl fmt::Debug for StoreChoice {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StoreChoice::Auto => f.write_str("Auto"),
StoreChoice::File => f.write_str("File"),
StoreChoice::Custom(s) => write!(f, "Custom({:?})", s.kind()),
StoreChoice::Host(_) => f.write_str("Host"),
StoreChoice::Hardware(_) => f.write_str("Hardware"),
}
}
}
#[derive(Clone)]
enum Keys {
Local(Arc<dyn SecretStore>),
Host(Arc<dyn DeviceKeyStore>),
Hardware(Arc<dyn HardwareDeviceKey>),
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct VaultConfig {
pub data_dir: PathBuf,
pub app_id: String,
pub store: StoreChoice,
pub label: String,
pub platform: DevicePlatform,
}
impl VaultConfig {
pub fn new(
data_dir: impl Into<PathBuf>,
app_id: impl Into<String>,
label: impl Into<String>,
) -> VaultConfig {
VaultConfig {
data_dir: data_dir.into(),
app_id: app_id.into(),
store: StoreChoice::default(),
label: label.into(),
platform: default_platform(),
}
}
}
pub struct DeviceVault {
file: DeviceFile,
keys: Keys,
account: String,
id: DeviceKeyId,
label: String,
platform: DevicePlatform,
warnings: Vec<DeviceWarning>,
}
impl fmt::Debug for DeviceVault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DeviceVault")
.field("file", &self.file)
.field("storage", &self.storage())
.finish_non_exhaustive()
}
}
pub fn platform_name() -> &'static str {
match std::env::consts::OS {
"macos" => "macOS",
"windows" => "Windows",
"linux" => "Linux",
"ios" => "iOS",
"android" => "Android",
_ => "desktop",
}
}
impl DeviceVault {
pub fn open(
cfg: &VaultConfig,
install_id: u64,
member: MemberId,
device_scope: &str,
) -> Result<DeviceVault, DeviceError> {
let dir = cfg.data_dir.join("sew-voice").join(install_id.to_string());
let mut warnings = Vec::new();
let keys = match &cfg.store {
StoreChoice::Host(s) => Keys::Host(s.clone()),
StoreChoice::Custom(s) => Keys::Local(s.clone()),
StoreChoice::File => {
warnings.push(DeviceWarning::KeyStorageFile);
Keys::Local(Arc::new(FileSecretStore::new(dir.clone())))
}
StoreChoice::Auto => Keys::Local(auto_store(&cfg.app_id, &dir, &mut warnings)),
StoreChoice::Hardware(k) => Keys::Hardware(k.clone()),
};
let file = DeviceFile::open(&dir, install_id, device_scope)?;
let scope = sanitize(device_scope);
let account = format!("{install_id}:{scope}");
let id = DeviceKeyId {
install_id,
member_id: member,
device_scope: scope,
};
let survives = match &keys {
Keys::Local(s) => s.load(&account)?.is_some(),
Keys::Host(s) => s.load(&id)?.is_some(),
Keys::Hardware(_) => false,
};
if !file.existed && survives {
warnings.push(DeviceWarning::PinsReset);
}
Ok(DeviceVault {
file,
keys,
account,
id,
label: cfg.label.clone(),
platform: cfg.platform,
warnings,
})
}
pub async fn open_async(
cfg: &VaultConfig,
install_id: u64,
member: MemberId,
device_scope: &str,
) -> Result<DeviceVault, DeviceError> {
let (cfg2, scope) = (cfg.clone(), device_scope.to_owned());
let mut vault =
blocking(move || DeviceVault::open(&cfg2, install_id, member, &scope)).await?;
if let Keys::Hardware(k) = &vault.keys
&& !vault.file.existed
&& k.public_key(&vault.id).await?.is_some()
{
vault.warnings.push(DeviceWarning::PinsReset);
}
Ok(vault)
}
pub fn platform(&self) -> DevicePlatform {
self.platform
}
pub fn take_warnings(&mut self) -> Vec<DeviceWarning> {
std::mem::take(&mut self.warnings)
}
pub fn storage(&self) -> KeyStorage {
match &self.keys {
Keys::Local(s) => s.kind(),
Keys::Host(_) => KeyStorage::Host,
Keys::Hardware(_) => KeyStorage::Hardware,
}
}
pub fn id(&self) -> &DeviceKeyId {
&self.id
}
pub fn file_mut(&mut self) -> &mut DeviceFile {
&mut self.file
}
pub fn file(&self) -> &DeviceFile {
&self.file
}
pub async fn signer(&self) -> Result<Option<SoftwareSigner>, DeviceError> {
if matches!(self.keys, Keys::Hardware(_)) {
return Ok(None);
}
Ok(self.stored().await?.1.and_then(DeviceKey::into_software))
}
pub async fn device_key(&self) -> Result<Option<DeviceKey>, DeviceError> {
Ok(self.stored().await?.1)
}
async fn stored(&self) -> Result<(Option<StoredDevice>, Option<DeviceKey>), DeviceError> {
match &self.keys {
Keys::Local(s) => {
let (s, a) = (s.clone(), self.account.clone());
let signer =
blocking(move || Ok(s.load(&a)?.and_then(|k| SoftwareSigner::from_bytes(&k))))
.await?;
Ok((
self.file.load(self.file.install_id),
signer.map(DeviceKey::software),
))
}
Keys::Hardware(k) => {
let key = match k.public_key(&self.id).await? {
Some(public) => Some(DeviceKey::hardware(k.clone(), self.id.clone(), public)?),
None => None,
};
Ok((self.file.load(self.file.install_id), key))
}
Keys::Host(s) => {
let (s, id) = (s.clone(), self.id.clone());
let rec = blocking(move || s.load(&id)).await?;
Ok(match rec {
Some(r)
if r.device.install_id == self.id.install_id
&& r.device.member_id == self.id.member_id =>
{
let signer = SoftwareSigner::from_bytes(&r.key).map(DeviceKey::software);
(Some(r.device), signer)
}
_ => (None, None),
})
}
}
}
async fn save_device(
&mut self,
stored: &StoredDevice,
signer: &DeviceKey,
key_changed: bool,
) -> Result<(), DeviceError> {
let scalar = || {
signer
.software_bytes()
.ok_or_else(|| DeviceError::Store("a hardware key in a software store".to_owned()))
};
match &self.keys {
Keys::Local(s) => {
if key_changed {
let (s, a) = (s.clone(), self.account.clone());
let k = scalar()?;
blocking(move || s.save(&a, &k)).await?;
}
self.file.save(stored).map_err(DeviceError::Store)
}
Keys::Host(s) => {
let (s, id) = (s.clone(), self.id.clone());
let rec = DeviceKeyRecord {
key: scalar()?,
device: stored.clone(),
};
blocking(move || s.store(&id, &rec)).await
}
Keys::Hardware(_) => self.file.save(stored).map_err(DeviceError::Store),
}
}
async fn new_key(&self) -> Result<DeviceKey, DeviceError> {
match &self.keys {
Keys::Hardware(k) => {
let public = k.generate(&self.id).await?;
DeviceKey::hardware(k.clone(), self.id.clone(), public)
}
Keys::Local(_) | Keys::Host(_) => Ok(DeviceKey::software(SoftwareSigner::generate(
&mut rand::rngs::OsRng,
))),
}
}
async fn delete_key(&self) -> Result<(), DeviceError> {
match &self.keys {
Keys::Local(s) => {
let (s, a) = (s.clone(), self.account.clone());
blocking(move || s.delete(&a)).await
}
Keys::Host(s) => {
let (s, id) = (s.clone(), self.id.clone());
blocking(move || s.clear(&id)).await
}
Keys::Hardware(k) => k.delete(&self.id).await,
}
}
pub async fn forget_device(&mut self) -> Result<(), DeviceError> {
self.delete_key().await?;
match self.keys {
Keys::Local(_) | Keys::Hardware(_) => self.file.forget_device(),
Keys::Host(_) => Ok(()),
}
}
pub async fn reset(&mut self) -> Result<(), DeviceError> {
self.delete_key().await?;
let install = self.file.install_id;
self.file.clear(install);
Ok(())
}
pub async fn ensure_device(
&mut self,
http: &KeyTransport,
trust: &TrustAnchors,
me: MemberId,
now: u64,
) -> Result<(DeviceIdentity, DeviceKey), DeviceError> {
if let (Some(stored), Some(signer)) = self.stored().await? {
let key_matches = signer.public_key_sec1() == stored.pubkey;
match DeviceIdentity::from_stored(stored, trust, me, now) {
Ok(id) if key_matches => {
if !Enrollment::needs_renewal(&id, now) {
return Ok((id, signer));
}
match http.renew_device(id.device_id()).await {
Ok(resp) => {
let stored =
Enrollment::accept(resp, trust, me, &signer.public_key_sec1(), now)
.map_err(|e| DeviceError::Certificate(e.to_string()))?;
self.save_device(&stored, &signer, false).await?;
let id = DeviceIdentity::from_stored(stored, trust, me, now)
.map_err(|e| DeviceError::Certificate(e.to_string()))?;
return Ok((id, signer));
}
Err(f) if is_device_refused(&f) || f.status == 404 => {
tracing::info!(target: "sew_call_client::device", "device refused on renew; enrolling again");
}
Err(_) => return Ok((id, signer)),
}
}
_ => {
tracing::info!(target: "sew_call_client::device", "stored device unusable; enrolling again");
}
}
}
self.forget_device().await?;
self.enroll(http, trust, me, now).await
}
pub async fn enroll(
&mut self,
http: &KeyTransport,
trust: &TrustAnchors,
me: MemberId,
now: u64,
) -> Result<(DeviceIdentity, DeviceKey), DeviceError> {
let install = trust.install_id();
let mut retried = false;
loop {
let signer = self.new_key().await?;
let pubkey = signer.public_key_sec1();
let (draft, req) = Enrollment::begin(&pubkey, self.platform, &self.label, install, me);
let body = Enrollment::request(draft, signer.sign(&req.message).await?);
let resp = match http.enroll(&body).await {
Ok(r) => r,
Err(f) if !retried && f.status == 409 && f.is(reasons::DEVICE_KEY_IN_USE) => {
retried = true;
continue;
}
Err(f) => {
return Err(DeviceError::EnrollRefused {
status: f.status,
reason: f.reason,
});
}
};
let stored = Enrollment::accept(resp, trust, me, &pubkey, now)
.map_err(|e| DeviceError::Certificate(e.to_string()))?;
self.save_device(&stored, &signer, true).await?;
let id = DeviceIdentity::from_stored(stored, trust, me, now)
.map_err(|e| DeviceError::Certificate(e.to_string()))?;
return Ok((id, signer));
}
}
}
async fn blocking<T: Send + 'static>(
f: impl FnOnce() -> Result<T, DeviceError> + Send + 'static,
) -> Result<T, DeviceError> {
tokio::task::spawn_blocking(f)
.await
.map_err(|_| DeviceError::Store("blocking task failed".to_owned()))?
}
fn auto_store(app_id: &str, dir: &Path, warnings: &mut Vec<DeviceWarning>) -> Arc<dyn SecretStore> {
#[cfg(feature = "keyring-store")]
{
let os = OsSecretStore::new(app_id);
if os.available() {
return Arc::new(os);
}
}
#[cfg(not(feature = "keyring-store"))]
let _ = app_id;
warnings.push(DeviceWarning::KeyStorageFile);
Arc::new(FileSecretStore::new(dir.to_path_buf()))
}
pub fn known_device_keys(data_dir: &Path) -> Result<Vec<DeviceKeyId>, DeviceError> {
let root = data_dir.join("sew-voice");
let installs = match std::fs::read_dir(&root) {
Ok(d) => d,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(DeviceError::Store(format!("read dir: {}", e.kind()))),
};
let mut out = Vec::new();
for entry in installs {
let entry = entry.map_err(|e| DeviceError::Store(format!("read dir: {}", e.kind())))?;
let Some(install_id) = entry
.file_name()
.to_str()
.and_then(|n| n.parse::<u64>().ok())
else {
continue;
};
out.extend(
install_files(&entry.path(), install_id)?
.into_iter()
.filter_map(|(_, id)| id),
);
}
out.sort();
Ok(out)
}
fn install_files(
dir: &Path,
install_id: u64,
) -> Result<Vec<(PathBuf, Option<DeviceKeyId>)>, DeviceError> {
let io = |e: std::io::Error| DeviceError::Store(format!("read: {}", e.kind()));
let entries = match std::fs::read_dir(dir) {
Ok(d) => d,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(io(e)),
};
let mut out = Vec::new();
for entry in entries {
let entry = entry.map_err(io)?;
let name = entry.file_name();
let Some(scope) = name
.to_str()
.and_then(|n| n.strip_prefix("device-"))
.and_then(|n| n.strip_suffix(".json"))
else {
continue;
};
if scope.is_empty() || sanitize(scope) != scope {
continue;
}
let path = entry.path();
let bytes = match std::fs::read(&path) {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(io(e)),
};
let id = serde_json::from_slice::<FileData>(&bytes)
.ok()
.and_then(|d| d.device)
.map(|d| DeviceKeyId {
install_id,
member_id: d.member_id,
device_scope: scope.to_owned(),
});
out.push((path, id));
}
Ok(out)
}
pub async fn forget_install(
cfg: &VaultConfig,
install_id: u64,
) -> Result<Vec<DeviceKeyId>, DeviceError> {
let dir = cfg.data_dir.join("sew-voice").join(install_id.to_string());
let listed = dir.clone();
let files = blocking(move || install_files(&listed, install_id)).await?;
let mut removed = Vec::new();
for (path, id) in files {
if let Some(id) = id {
let mut vault =
DeviceVault::open_async(cfg, install_id, id.member_id, &id.device_scope).await?;
vault.reset().await?;
removed.push(id);
}
blocking(move || match std::fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(DeviceError::Store(format!("remove: {}", e.kind()))),
})
.await?;
}
let _ = std::fs::remove_dir(&dir);
removed.sort();
Ok(removed)
}
pub fn is_device_refused(f: &sew_e2ee::ApiFailure) -> bool {
use reasons::key_package_check as kc;
(f.status == 422 && f.is(reasons::DEVICE_REVOKED))
|| (f.status == 422
&& f.is(reasons::E2EE_KEY_PACKAGE_INVALID)
&& matches!(f.detail.as_deref(), Some(d) if d == kc::DEVICE_CERT || d == kc::DEVICE_SIG))
}