tuwunel_service/integrity/
readreceiptid_readreceipt.rs1use std::{fmt, mem::replace, str::from_utf8};
8
9use futures::Stream;
10use ruma::{RoomId, UserId};
11use tuwunel_core::{
12 Result,
13 smallstr::SmallString,
14 utils::{ReadyExt, TryReadyExt},
15};
16use tuwunel_database::{KeyBuf, SEP};
17
18use super::{Check, Report, ScanExt, tally};
19use crate::Services;
20
21type Id = SmallString<[u8; 48]>;
22type Holder = (Id, Id);
23type Row<'a> = (&'a RoomId, &'a UserId, bool);
24
25const COUNT: usize = size_of::<u64>();
26
27pub(super) static CHECK: Check = Check {
28 name: "read-receipts",
29 about: "Receipt keys read back, and none lacking a thread kind repeats the holder before it",
30 quiescent: false,
31 walk: |services, limit| tally(scan(services), limit),
32};
33
34pub enum Finding {
39 Repeated {
41 key: KeyBuf,
43
44 room_id: Id,
46
47 user_id: Id,
49 },
50
51 Unparsable {
53 key: KeyBuf,
55 },
56}
57
58#[tracing::instrument(level = "trace", skip_all)]
66pub fn scan(services: &Services) -> impl Stream<Item = Result<Finding>> + Send + '_ {
67 services.db["readreceiptid_readreceipt"]
68 .raw_scan()
69 .scanned(&services.server)
70 .ready_scan(None, |last, row| {
71 row.map(|(key, _)| {
72 let row = parse(key);
73 let repeated = advance(last, row);
74
75 finding(key, row, repeated)
76 })
77 .into()
78 })
79 .ready_try_filter_map(Ok)
80}
81
82impl Report for Finding {
83 fn kind(&self) -> &'static str {
84 match self {
85 | Self::Repeated { .. } => "repeated-receipt",
86 | Self::Unparsable { .. } => "unparsable-key",
87 }
88 }
89}
90
91impl fmt::Display for Finding {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 match self {
94 | Self::Repeated { room_id, user_id, .. } => {
95 write!(f, "repeated receipt of {user_id} in {room_id}")
96 },
97 | Self::Unparsable { key } => write!(f, "key cannot be read: {}", key.escape_ascii()),
98 }
99 }
100}
101
102fn parse(key: &[u8]) -> Option<Row<'_>> {
108 let (room_id, rest) = split(key)?;
109 let (_count, rest) = rest.split_first_chunk::<COUNT>()?;
110 let rest = rest.strip_prefix(&[SEP])?;
111 let (user_id, kind) =
112 split(rest).map_or((rest, None), |(user_id, kind)| (user_id, Some(kind)));
113
114 let room_id = from_utf8(room_id).ok()?.try_into().ok()?;
115 let user_id = from_utf8(user_id).ok()?.try_into().ok()?;
116
117 kind.is_none_or(readable)
118 .then_some((room_id, user_id, kind.is_some()))
119}
120
121fn split(bytes: &[u8]) -> Option<(&[u8], &[u8])> {
122 let at = bytes.iter().position(|&byte| byte == SEP)?;
123 let (head, tail) = bytes.split_at(at);
124
125 Some((head, tail.strip_prefix(&[SEP])?))
126}
127
128fn readable(kind: &[u8]) -> bool { from_utf8(kind.strip_suffix(&[SEP]).unwrap_or(kind)).is_ok() }
132
133fn advance(last: &mut Option<Holder>, row: Option<Row<'_>>) -> bool {
137 let previous = replace(last, row.map(holder));
138
139 previous.is_some_and(|previous| last.as_ref().eq(&Some(&previous)))
140}
141
142fn holder((room_id, user_id, _): Row<'_>) -> Holder {
143 (room_id.as_str().into(), user_id.as_str().into())
144}
145
146fn finding(key: &[u8], row: Option<Row<'_>>, repeated: bool) -> Option<Finding> {
147 match row {
148 | None => Some(Finding::Unparsable { key: KeyBuf::from_slice(key) }),
149 | Some((room_id, user_id, false)) if repeated => Some(Finding::Repeated {
150 key: KeyBuf::from_slice(key),
151 room_id: room_id.as_str().into(),
152 user_id: user_id.as_str().into(),
153 }),
154 | Some(_) => None,
155 }
156}