Skip to main content

weirdnet_update/
target.rs

1//! On-device targeting rules.
2//!
3//! A rule is a small boolean expression over device attributes, signed inside the manifest
4//! and evaluated on the device, so attributes never leave it. Built-in attribute names are
5//! listed in [`BUILTIN_ATTRS`]; app-defined attributes start with `custom.`.
6//! A comparison on an attribute the device doesn't have is false (so `Not` of it is true).
7
8use crate::ids::{MAX_ID, check_id};
9use crate::{Error, Result, Timestamp};
10use semver::Version;
11use serde::{Deserialize, Serialize};
12use std::collections::{BTreeMap, BTreeSet};
13use std::fmt;
14
15/// Deepest nesting allowed.
16pub const MAX_DEPTH: usize = 16;
17/// Most nodes in one rule.
18pub const MAX_NODES: usize = 256;
19/// Most values in one `In` list.
20pub const MAX_IN: usize = 64;
21/// Rollout buckets run from 0 to `BUCKETS - 1` (basis points).
22pub const BUCKETS: u16 = 10_000;
23
24/// Attribute names the platform layer fills in.
25pub const BUILTIN_ATTRS: &[&str] = &[
26    "app_version",
27    "base_release",
28    "channel",
29    "platform",
30    "os",
31    "os_version",
32    "arch",
33    "package_type",
34    "store",
35    "device_class",
36    "form_factor",
37    "locale",
38    "region",
39];
40
41/// Prefix for app-defined attributes.
42pub const CUSTOM_PREFIX: &str = "custom.";
43
44/// An attribute value.
45#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(rename_all = "kebab-case")]
47pub enum Value {
48    /// Text.
49    Str(String),
50    /// Integer.
51    Int(i64),
52    /// Boolean.
53    Bool(bool),
54    /// Semantic version.
55    Version(Version),
56}
57
58impl From<&str> for Value {
59    fn from(s: &str) -> Self {
60        Self::Str(s.to_owned())
61    }
62}
63
64impl From<String> for Value {
65    fn from(s: String) -> Self {
66        Self::Str(s)
67    }
68}
69
70impl From<i64> for Value {
71    fn from(n: i64) -> Self {
72        Self::Int(n)
73    }
74}
75
76impl From<bool> for Value {
77    fn from(b: bool) -> Self {
78        Self::Bool(b)
79    }
80}
81
82impl From<Version> for Value {
83    fn from(v: Version) -> Self {
84        Self::Version(v)
85    }
86}
87
88/// Ordering comparisons (integers and versions only).
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "kebab-case")]
91#[allow(missing_docs)]
92pub enum CmpOp {
93    Lt,
94    Le,
95    Gt,
96    Ge,
97}
98
99/// A targeting rule.
100#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "kebab-case")]
102pub enum Rule {
103    /// Always true.
104    True,
105    /// Every sub-rule is true (empty: true).
106    All(Vec<Rule>),
107    /// Some sub-rule is true (empty: false).
108    Any(Vec<Rule>),
109    /// Negation.
110    Not(Box<Rule>),
111    /// Attribute equals value.
112    Eq {
113        /// Attribute name.
114        attr: String,
115        /// Value.
116        value: Value,
117    },
118    /// Attribute is one of the values.
119    In {
120        /// Attribute name.
121        attr: String,
122        /// Values.
123        values: Vec<Value>,
124    },
125    /// Ordered comparison; both sides must be integers or both versions.
126    Cmp {
127        /// Attribute name.
128        attr: String,
129        /// Operator.
130        op: CmpOp,
131        /// Right-hand side.
132        value: Value,
133    },
134    /// String attribute starts with a prefix (e.g. `locale` starts with `de`).
135    StartsWith {
136        /// Attribute name.
137        attr: String,
138        /// Prefix.
139        prefix: String,
140    },
141    /// The user installed a signed cohort token with this name (e.g. beta testers).
142    Cohort(String),
143    /// Only between two times (UTC).
144    Window {
145        /// Start, inclusive.
146        from: Timestamp,
147        /// End, exclusive.
148        until: Timestamp,
149    },
150}
151
152fn check_attr(attr: &str) -> Result<()> {
153    let ok =
154        BUILTIN_ATTRS.contains(&attr) || (attr.len() > CUSTOM_PREFIX.len() && attr.starts_with(CUSTOM_PREFIX) && check_id("attribute", attr).is_ok());
155    if !ok {
156        return Err(Error::Rule(format!("unknown attribute {attr:?}; custom attributes start with {CUSTOM_PREFIX:?}")));
157    }
158    Ok(())
159}
160
161fn check_value(v: &Value) -> Result<()> {
162    if let Value::Str(s) = v
163        && s.len() > MAX_ID * 2
164    {
165        return Err(Error::Rule("string value too long".into()));
166    }
167    Ok(())
168}
169
170impl Rule {
171    /// Checks size limits, attribute names and value types.
172    pub fn validate(&self) -> Result<()> {
173        let mut nodes = 0;
174        self.validate_at(1, &mut nodes)
175    }
176
177    fn validate_at(&self, depth: usize, nodes: &mut usize) -> Result<()> {
178        *nodes += 1;
179        if depth > MAX_DEPTH {
180            return Err(Error::Rule(format!("nested deeper than {MAX_DEPTH}")));
181        }
182        if *nodes > MAX_NODES {
183            return Err(Error::Rule(format!("more than {MAX_NODES} nodes")));
184        }
185        match self {
186            Self::True => {}
187            Self::All(rules) | Self::Any(rules) => {
188                for r in rules {
189                    r.validate_at(depth + 1, nodes)?;
190                }
191            }
192            Self::Not(r) => r.validate_at(depth + 1, nodes)?,
193            Self::Eq { attr, value } => {
194                check_attr(attr)?;
195                check_value(value)?;
196            }
197            Self::In { attr, values } => {
198                check_attr(attr)?;
199                if values.is_empty() || values.len() > MAX_IN {
200                    return Err(Error::Rule(format!("`in` needs 1..={MAX_IN} values")));
201                }
202                values.iter().try_for_each(check_value)?;
203            }
204            Self::Cmp { attr, value, .. } => {
205                check_attr(attr)?;
206                if !matches!(value, Value::Int(_) | Value::Version(_)) {
207                    return Err(Error::Rule("ordered comparisons take an integer or a version".into()));
208                }
209            }
210            Self::StartsWith { attr, prefix } => {
211                check_attr(attr)?;
212                check_value(&Value::Str(prefix.clone()))?;
213            }
214            Self::Cohort(name) => check_id("cohort", name).map_err(|e| Error::Rule(e.to_string()))?,
215            Self::Window { from, until } => {
216                if from >= until {
217                    return Err(Error::Rule("window must end after it starts".into()));
218                }
219            }
220        }
221        Ok(())
222    }
223
224    /// Evaluates the rule against a device.
225    pub fn evaluate(&self, device: &Device) -> bool {
226        match self {
227            Self::True => true,
228            Self::All(rules) => rules.iter().all(|r| r.evaluate(device)),
229            Self::Any(rules) => rules.iter().any(|r| r.evaluate(device)),
230            Self::Not(r) => !r.evaluate(device),
231            Self::Eq { attr, value } => device.attr(attr).is_some_and(|v| v == value),
232            Self::In { attr, values } => device.attr(attr).is_some_and(|v| values.contains(v)),
233            Self::Cmp { attr, op, value } => {
234                let ord = match (device.attr(attr), value) {
235                    (Some(Value::Int(a)), Value::Int(b)) => a.cmp(b),
236                    (Some(Value::Version(a)), Value::Version(b)) => a.cmp(b),
237                    _ => return false,
238                };
239                match op {
240                    CmpOp::Lt => ord.is_lt(),
241                    CmpOp::Le => ord.is_le(),
242                    CmpOp::Gt => ord.is_gt(),
243                    CmpOp::Ge => ord.is_ge(),
244                }
245            }
246            Self::StartsWith { attr, prefix } => matches!(device.attr(attr), Some(Value::Str(s)) if s.starts_with(prefix.as_str())),
247            Self::Cohort(name) => device.cohorts.contains(name),
248            Self::Window { from, until } => *from <= device.now && device.now < *until,
249        }
250    }
251}
252
253/// What the device knows about itself. Never sent anywhere.
254#[derive(Clone)]
255pub struct Device {
256    attrs: BTreeMap<String, Value>,
257    cohorts: BTreeSet<String>,
258    bucket_secret: [u8; 32],
259    /// The current time.
260    pub now: Timestamp,
261}
262
263impl Device {
264    /// A device with a local random secret used only for rollout buckets. Create the secret
265    /// once per install and keep it on the device.
266    pub fn new(bucket_secret: [u8; 32], now: Timestamp) -> Self {
267        Self { attrs: BTreeMap::new(), cohorts: BTreeSet::new(), bucket_secret, now }
268    }
269
270    /// Sets an attribute (built-in or `custom.*`).
271    pub fn set(&mut self, attr: &str, value: impl Into<Value>) -> Result<&mut Self> {
272        check_attr(attr)?;
273        self.attrs.insert(attr.to_owned(), value.into());
274        Ok(self)
275    }
276
277    /// Adds a cohort whose signed token the user installed. Token checks are the caller's.
278    pub fn join_cohort(&mut self, name: &str) -> &mut Self {
279        self.cohorts.insert(name.to_owned());
280        self
281    }
282
283    /// Reads an attribute.
284    pub fn attr(&self, attr: &str) -> Option<&Value> {
285        self.attrs.get(attr)
286    }
287
288    /// This device's rollout bucket for one update, 0..[`BUCKETS`]. Keyed by the local secret
289    /// so no one else can compute it, and per update so a device isn't always first.
290    pub fn bucket(&self, update_id: &str) -> u16 {
291        let mut h = blake3::Hasher::new_keyed(&self.bucket_secret);
292        h.update(b"weirdnet-update/v1/bucket\0");
293        h.update(update_id.as_bytes());
294        let out = h.finalize();
295        let mut first = [0u8; 8];
296        first.copy_from_slice(&out.as_bytes()[..8]);
297        (u64::from_le_bytes(first) % u64::from(BUCKETS)) as u16
298    }
299}
300
301impl fmt::Debug for Device {
302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303        f.debug_struct("Device")
304            .field("attrs", &self.attrs)
305            .field("cohorts", &self.cohorts)
306            .field("bucket_secret", &"<redacted>")
307            .field("now", &self.now)
308            .finish()
309    }
310}