tuwunel_service/integrity/
useridprofilekey_value.rs1use std::{fmt, str::from_utf8};
6
7use futures::Stream;
8use serde::de::IgnoredAny;
9use tuwunel_core::{Result, smallstr::SmallString, utils::TryReadyExt};
10use tuwunel_database::{KeyBuf, keyval::Buffer};
11
12use super::{Check, Report, ScanExt, tally};
13use crate::Services;
14
15type Text = SmallString<[u8; 48]>;
16type Value = Buffer<48>;
17
18pub(super) static CHECK: Check = Check {
19 name: "profile-values",
20 about: "Every useridprofilekey_value value is JSON",
21 quiescent: false,
22 walk: |services, limit| tally(scan(services), limit),
23};
24
25pub enum Finding {
30 Bare {
32 key: KeyBuf,
34
35 text: Text,
37 },
38
39 Opaque {
41 key: KeyBuf,
43
44 value: Value,
46 },
47}
48
49#[tracing::instrument(level = "trace", skip_all)]
55pub fn scan(services: &Services) -> impl Stream<Item = Result<Finding>> + Send + '_ {
56 services.db["useridprofilekey_value"]
57 .raw_scan()
58 .scanned(&services.server)
59 .ready_try_filter_map(|(key, value)| Ok(classify(key, value)))
60}
61
62pub(crate) fn classify(key: &[u8], value: &[u8]) -> Option<Finding> {
67 serde_json::from_slice::<IgnoredAny>(value)
68 .is_err()
69 .then(|| match from_utf8(value) {
70 | Ok(text) => Finding::Bare {
71 key: KeyBuf::from_slice(key),
72 text: text.into(),
73 },
74 | Err(_) => Finding::Opaque {
75 key: KeyBuf::from_slice(key),
76 value: Value::from_slice(value),
77 },
78 })
79}
80
81impl Report for Finding {
82 fn kind(&self) -> &'static str {
83 match self {
84 | Self::Bare { .. } => "bare-text",
85 | Self::Opaque { .. } => "not-text",
86 }
87 }
88}
89
90impl fmt::Display for Finding {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 match self {
93 | Self::Bare { key, .. } => {
94 write!(f, "value of {} is text, not JSON", key.escape_ascii())
95 },
96 | Self::Opaque { key, .. } => {
97 write!(f, "value of {} is neither JSON nor text", key.escape_ascii())
98 },
99 }
100 }
101}