1use super::sequence_invites::{
12 decode_request, kept_until, seconds, Expected, Opened, RequestChecks,
13};
14use super::{SequenceSync, Session};
15use crate::sequence_sync::OperationState;
16use crate::{AddDevice, AddDeviceEnd, AddDeviceId, AddDeviceRequest, AddDeviceStatus, SyncError};
17use coven_crypto::{InviteSecret, MemberIdentity, SecretText};
18use coven_database::{
19 operation_kind, DbError, Journal, NewOperation, OperationId, OperationRecord, SqlContext,
20};
21use coven_format::{codes::PairingCode, handover::Handover};
22use coven_foundation::id_source::{DeviceId, IdSource, InviteId, MemberId};
23use coven_storage::{CloudProvider, ObjectPath, RestoreStorage, S3Credentials, StorageFailure};
24use serde::{Deserialize, Serialize};
25use std::time::{Duration, SystemTime};
26
27pub(crate) const LIFETIME: Duration = Duration::from_secs(30 * 60);
30
31#[derive(Debug, Serialize, Deserialize)]
33pub(crate) enum PairingState {
34 Waiting { request: Option<Vec<u8>> },
37 Approving { request: Vec<u8>, handover: Vec<u8> },
40 HandedOver { request: Vec<u8> },
43 Ending { how: AddDeviceEnd },
46 Forgetting,
49 Ended { how: AddDeviceEnd },
52}
53
54#[derive(Debug, Serialize, Deserialize)]
56pub(crate) struct PairingWork {
57 id: InviteId,
58 device: DeviceId,
62 member: MemberId,
64 secret: SecretText,
65 expires_at: SystemTime,
66 qr_code: SecretText,
69 shared_code: SecretText,
70 state: PairingState,
71}
72
73impl OperationState for PairingWork {}
74
75impl PairingWork {
76 pub(crate) fn read(record: &OperationRecord) -> Result<Self, SyncError> {
77 Ok(serde_json::from_slice(&record.data)?)
78 }
79
80 fn secret(&self) -> Result<InviteSecret, SyncError> {
81 Ok(InviteSecret::from_bytes(serde_json::from_str(self.secret.as_str())?))
82 }
83
84 fn path(&self, store: coven_foundation::id_source::StoreId) -> ObjectPath {
85 ObjectPath::join_request(store, self.device, self.id)
86 }
87
88 fn expires(&self) -> bool {
91 matches!(
92 self.state,
93 PairingState::Waiting { .. }
94 | PairingState::Approving { .. }
95 | PairingState::HandedOver { .. }
96 )
97 }
98
99 pub(crate) fn expired(&self, now: SystemTime) -> bool {
100 self.expires() && now >= self.expires_at
101 }
102
103 fn end(&mut self, how: AddDeviceEnd) {
105 self.state = PairingState::Ending { how };
106 }
107
108 pub(crate) fn forget(&mut self) {
111 self.state = PairingState::Forgetting;
112 }
113
114 pub(crate) fn expiry(&self) -> Option<SystemTime> {
116 self.expires().then_some(self.expires_at)
117 }
118
119 pub(crate) fn expire(&mut self) {
121 self.end(AddDeviceEnd::Expired);
122 }
123}
124
125pub(crate) fn make_pairing(
133 sql: &SqlContext<'_, '_>,
134 device: DeviceId,
135 held: &MemberIdentity,
136 ids: &dyn IdSource,
137 now: SystemTime,
138 location: &coven_storage::StorageConfig,
139 key: Option<S3Credentials>,
140) -> Result<AddDevice, SyncError> {
141 let expires_at = now.checked_add(LIFETIME).ok_or(
142 StorageFailure::InvalidConfiguration
143 .with_source("the clock cannot represent the pairing's expiry"),
144 )?;
145 let secret = InviteSecret::generate()?;
146 let secret = SecretText::new(serde_json::to_string(secret.to_secret_bytes().as_bytes())?);
147 let id = InviteId(ids.new_id());
148 sql.journal_step(|journal| {
149 let applied = journal.store_state()?;
150 let member = crate::sequence_sync::registered(&applied, device, held)?;
151 let store = applied.store.as_ref().ok_or(SyncError::NoStorage)?;
152 let code = |storage: RestoreStorage| -> Result<SecretText, SyncError> {
153 let text = PairingCode {
154 store: store.id,
155 expires_at: seconds(expires_at)?,
156 pairing: id,
157 member,
158 secret: InviteSecret::from_bytes(serde_json::from_str(secret.as_str())?),
159 showing: device,
160 storage: storage.encode()?,
161 }
162 .to_text()?;
163 Ok(SecretText::new(text.to_string()))
164 };
165 let shared_code = code(RestoreStorage::location_only(location.clone()))?;
166 let qr_code = if location.provider() == CloudProvider::S3 {
167 let key = key.ok_or_else(|| {
168 StorageFailure::InvalidConfiguration
169 .with_source("this device holds no S3 key to give")
170 })?;
171 code(RestoreStorage { location: location.clone(), s3_key: Some(key) })?
172 } else {
173 SecretText::new(shared_code.as_str().to_owned())
174 };
175 let work = PairingWork {
176 id,
177 device,
178 member,
179 secret: SecretText::new(secret.as_str().to_owned()),
180 expires_at,
181 qr_code: SecretText::new(qr_code.as_str().to_owned()),
182 shared_code: SecretText::new(shared_code.as_str().to_owned()),
183 state: PairingState::Waiting { request: None },
184 };
185 journal.start_operation(&NewOperation {
186 kind: operation_kind::PAIRING.into(),
187 data: serde_json::to_vec(&work)?,
188 started_by: "add_device".into(),
189 pauses_writes: false,
190 })?;
191 Ok(AddDevice {
192 id: id.into(),
193 qr_code: qr_code.as_str().to_owned(),
194 shared_code: shared_code.as_str().to_owned(),
195 expires_at,
196 })
197 })
198}
199
200pub(crate) fn approve_request(
210 sql: &SqlContext<'_, '_>,
211 store: coven_foundation::id_source::StoreId,
212 now: SystemTime,
213 held: &MemberIdentity,
214 request: &AddDeviceRequest,
215) -> Result<OperationId, SyncError> {
216 sql.journal_step(|journal| {
217 let (record, mut work) = pairing_record(journal, request.pairing.into())?;
218 if work.expired(now) {
219 return Err(SyncError::InvitationChanged);
220 }
221 let PairingState::Waiting { request: Some(stored) } = &work.state else {
222 return Err(SyncError::InvitationChanged);
223 };
224 if *stored != request.record {
225 return Err(SyncError::InvitationChanged);
226 }
227 let stored = stored.clone();
228 let applied = journal.store_state()?;
229 let current = applied
230 .active_member(&work.member)
231 .ok_or(SyncError::Removed(coven_database::Removal::Member))?
232 .keys;
233 let selected =
234 held.activate(¤t).ok_or(SyncError::MemberKeysReplaced { member: work.member })?;
235 let sealing = decode_request(&stored)?.keys.sealing;
236 let handover =
237 Handover::seal(work.member, selected.keys(), &sealing, &work.path(store))?.encode();
238 work.state = PairingState::Approving { request: stored, handover };
239 journal.advance_operation(&work.update(&record)?)?;
240 Ok(record.id)
241 })
242}
243
244pub(crate) fn decline_request(
249 sql: &SqlContext<'_, '_>,
250 now: SystemTime,
251 request: &AddDeviceRequest,
252) -> Result<OperationId, SyncError> {
253 sql.journal_step(|journal| {
254 let (record, mut work) = pairing_record(journal, request.pairing.into())?;
255 if work.expired(now) {
256 return Err(SyncError::InvitationChanged);
257 }
258 match &work.state {
259 PairingState::Waiting { request: Some(stored) } if *stored == request.record => (),
260 _ => return Err(SyncError::InvitationChanged),
261 }
262 work.end(AddDeviceEnd::Declined);
263 journal.advance_operation(&work.update(&record)?)?;
264 Ok(record.id)
265 })
266}
267
268pub(crate) fn end_add_device(
273 sql: &SqlContext<'_, '_>,
274 pairing: AddDeviceId,
275) -> Result<Option<OperationId>, SyncError> {
276 sql.journal_step(|journal| {
277 let (record, mut work) = match pairing_record(journal, pairing.into()) {
278 Ok(found) => found,
279 Err(SyncError::InvitationChanged) => return Ok(None),
280 Err(error) => return Err(error),
281 };
282 match work.state {
283 PairingState::Forgetting => return Ok(None),
284 PairingState::Ended { .. } => journal.finish_operation(record.id)?,
286 _ => {
287 work.state = PairingState::Forgetting;
288 journal.advance_operation(&work.update(&record)?)?;
289 }
290 }
291 Ok(Some(record.id))
292 })
293}
294
295fn pairing_record(
298 journal: &Journal<'_>,
299 pairing: InviteId,
300) -> Result<(OperationRecord, PairingWork), SyncError> {
301 for record in journal.operations(operation_kind::PAIRING)? {
302 let work = PairingWork::read(&record)?;
303 if work.id == pairing {
304 return Ok((record, work));
305 }
306 }
307 Err(SyncError::InvitationChanged)
308}
309
310impl PairingWork {
311 fn status(&self) -> Result<Option<AddDeviceStatus>, SyncError> {
314 let present = |bytes: &[u8]| -> Result<AddDeviceRequest, SyncError> {
315 let request = decode_request(bytes)?;
316 Ok(AddDeviceRequest {
317 pairing: self.id.into(),
318 device_name: request.device_name,
319 confirmation: coven_crypto::ConfirmationNumber::of(self.id, &request.keys),
320 record: bytes.to_vec(),
321 })
322 };
323 Ok(Some(match &self.state {
324 PairingState::Waiting { request } => {
325 AddDeviceStatus::Waiting { request: request.as_deref().map(present).transpose()? }
326 }
327 PairingState::Approving { request, .. } | PairingState::HandedOver { request } => {
328 AddDeviceStatus::Approved { request: present(request)? }
329 }
330 PairingState::Ending { how } | PairingState::Ended { how } => {
331 AddDeviceStatus::Ended(how.clone())
332 }
333 PairingState::Forgetting => return Ok(None),
334 }))
335 }
336}
337
338#[expect(
342 clippy::map_err_ignore,
343 reason = "a stored request that does not decode is a damaged journal row, whichever field failed"
344)]
345pub fn pairing_status(
346 records: &[OperationRecord],
347 pairing: AddDeviceId,
348) -> Result<Option<AddDeviceStatus>, DbError> {
349 for record in records {
350 let work: PairingWork =
351 serde_json::from_slice(&record.data).map_err(DbError::StateEncoding)?;
352 if work.id == InviteId::from(pairing) {
353 return work.status().map_err(|_| DbError::DamagedDatabase);
354 }
355 }
356 Ok(None)
357}
358
359pub async fn pairings_opened(database: &coven_database::StoreDatabase) -> Result<(), DbError> {
364 database
365 .settle_operations(operation_kind::PAIRING, |records| {
366 let mut updates = Vec::new();
367 let mut finished = Vec::new();
368 for record in records {
369 let mut work: PairingWork =
370 serde_json::from_slice(&record.data).map_err(DbError::StateEncoding)?;
371 match work.state {
372 PairingState::Forgetting => (),
373 PairingState::Ended { .. } => finished.push(record.id),
374 _ => {
375 work.state = PairingState::Forgetting;
376 updates.push(record.next_step(
377 serde_json::to_vec(&work).map_err(DbError::StateEncoding)?,
378 )?);
379 }
380 }
381 }
382 Ok((updates, finished, ()))
383 })
384 .await
385}
386
387impl SequenceSync {
388 pub(crate) async fn resume_pairings(&self, session: &Session) -> Result<(), SyncError> {
393 for record in self.database.operations().await? {
394 if record.kind != operation_kind::PAIRING {
395 continue;
396 }
397 self.run_pairing(session, record.id).await?;
398 self.state.check()?;
399 }
400 Ok(())
401 }
402
403 async fn run_pairing(&self, session: &Session, id: OperationId) -> Result<(), SyncError> {
409 let mut step = None;
410 let Err(error) = self.advance_pairing(session, id, &mut step).await else {
411 return Ok(());
412 };
413 let Some(step) = step else { return Err(error) };
414 match self.database.operation(id).await? {
415 Some(row) if row.last_step == step => self.record_pairing_error(id, step, &error).await,
416 _ => Ok(()),
417 }
418 }
419
420 async fn advance_pairing(
423 &self,
424 session: &Session,
425 id: OperationId,
426 step: &mut Option<u32>,
427 ) -> Result<(), SyncError> {
428 loop {
429 let record = self
430 .database
431 .operation(id)
432 .await?
433 .ok_or(coven_database::DbError::OperationChanged(id))?;
434 *step = Some(record.last_step);
435 let mut work = PairingWork::read(&record)?;
436 let path = work.path(self.store());
437 if work.expired(self.clock.now()) {
438 work.expire();
439 self.database.advance_operation(work.update(&record)?).await?;
440 continue;
441 }
442 match &work.state {
443 PairingState::Waiting { request: None } => {
444 let bytes = match self.storage.read(&path).await {
445 Ok(bytes) => bytes,
446 Err(error) if error.failure() == StorageFailure::NotFound => {
447 return self.found_nothing(id, record.last_step).await;
448 }
449 Err(error) => return Err(error.into()),
450 };
451 let secret = work.secret()?;
452 let checks = RequestChecks {
453 path: &path,
454 secret: &secret,
455 id: work.id,
456 member: work.member,
457 expected: Expected::OwnDevice,
458 };
459 match checks.open(&session.history.state, &bytes)? {
460 Opened::Checked(request) => {
463 work.state = PairingState::Waiting { request: Some(request) };
464 self.database.advance_operation(work.update(&record)?).await?;
465 return Ok(());
466 }
467 Opened::Refused(refusal) => {
471 tracing::warn!(?id, %refusal, "a pairing's request failed its checks");
472 work.end(AddDeviceEnd::Refused);
473 self.database.advance_operation(work.update(&record)?).await?;
474 }
475 }
476 }
477 PairingState::Waiting { request: Some(_) } => {
478 return self.found_nothing(id, record.last_step).await;
479 }
480 PairingState::Approving { request, handover } => {
481 self.place_handover(&path, handover).await?;
482 let request = request.clone();
483 work.state = PairingState::HandedOver { request };
484 self.database.advance_operation(work.update(&record)?).await?;
485 }
486 PairingState::HandedOver { request } => {
487 let request = decode_request(request)?;
491 let registered = session
492 .history
493 .state
494 .devices
495 .get(&request.device)
496 .is_some_and(|device| device.member == work.member);
497 if !registered {
498 return self.found_nothing(id, record.last_step).await;
499 }
500 work.end(AddDeviceEnd::Added {
501 device: request.device,
502 name: request.device_name,
503 });
504 self.database.advance_operation(work.update(&record)?).await?;
505 }
506 PairingState::Ending { .. } | PairingState::Forgetting => {
507 let kept_until = kept_until(seconds(work.expires_at)?)?;
510 self.put_marker(&path, kept_until).await?;
511 let removal = coven_database::ObjectRemoval {
512 path: path.as_str().to_owned(),
513 after: kept_until,
514 };
515 match work.state {
516 PairingState::Ending { how } => {
517 work.state = PairingState::Ended { how };
518 self.database
519 .advance_operation_with_removal(work.update(&record)?, removal)
520 .await?;
521 }
522 _ => {
523 self.database
524 .finish_operation_with_removal(id, Vec::new(), removal, None)
525 .await?;
526 }
527 }
528 return Ok(());
529 }
530 PairingState::Ended { .. } => return Ok(()),
531 }
532 }
533 }
534
535 async fn found_nothing(&self, id: OperationId, step: u32) -> Result<(), SyncError> {
538 self.database.clear_operation_pending_at(id, step).await?;
539 Ok(())
540 }
541
542 async fn place_handover(&self, path: &ObjectPath, handover: &[u8]) -> Result<(), SyncError> {
547 loop {
548 match self.storage.read(path).await {
549 Ok(found) if found == handover => return Ok(()),
550 Ok(_) => self.storage.delete_if_present(path).await?,
551 Err(error) if error.failure() == StorageFailure::NotFound => {
552 match self.storage.create(path, handover).await {
553 Ok(_) => return Ok(()),
554 Err(error) if error.failure() == StorageFailure::AlreadyExists => (),
555 Err(error) => return Err(error.into()),
556 }
557 }
558 Err(error) => return Err(error.into()),
559 }
560 }
561 }
562}
563
564#[cfg(test)]
565#[path = "sequence_pairings_tests.rs"]
566mod tests;