Skip to main content

oxabl_cache_crypto/
join.rs

1//! Join requests: the nonce that binds a device to a sign-in, and an owner's own check of it.
2
3use oxabl_cache_format::{CacheId, Role};
4
5use crate::id_token::{self, KeySet, SignedIn};
6use crate::identity_string;
7use crate::roster_member::MemberEntry;
8
9/// Oldest sign-in a join request may rest on, in seconds.
10pub const MAX_SIGN_IN_AGE_SECS: i64 = 14 * 24 * 60 * 60;
11const NONCE_DOMAIN: &[u8] = b"oxabl-cache v1 join";
12
13/// The join nonce of `descriptor` for the cache: hex BLAKE3 of the domain, the cache id's bytes
14/// and the descriptor text.
15pub fn join_nonce(cache: &CacheId, descriptor: &str) -> String {
16    let mut hasher = blake3::Hasher::new();
17    hasher.update(NONCE_DOMAIN);
18    hasher.update(&cache.0);
19    hasher.update(descriptor.as_bytes());
20    hasher.finalize().to_hex().to_string()
21}
22
23/// Checks a join request without trusting the server that relayed it: the descriptor parses,
24/// the ID token verifies against `keys` for `issuer` and the `audience` the owner pinned,
25/// the sign-in is at most [`MAX_SIGN_IN_AGE_SECS`] old, and its `nonce` binds this descriptor
26/// to this cache. Every refusal is a short reason.
27pub fn check_join_request(
28    id_token: &str,
29    descriptor: &str,
30    keys: &KeySet,
31    issuer: &str,
32    audience: &str,
33    cache: &CacheId,
34    now: i64,
35) -> Result<SignedIn, &'static str> {
36    if identity_string::parse_descriptor(descriptor).is_err() {
37        return Err("not a member descriptor");
38    }
39    let person = id_token::verify(id_token, keys, issuer, audience, now, MAX_SIGN_IN_AGE_SECS)?;
40    if person.claim("nonce") == Some(join_nonce(cache, descriptor).as_str()) {
41        Ok(person)
42    } else {
43        Err("the sign-in does not bind this device")
44    }
45}
46
47/// Requests decided in one pass at most.
48pub const MAX_PER_PASS: usize = 64;
49/// Suffixes tried to make a joining person's label unique.
50const MAX_LABEL_SUFFIX: u32 = 99;
51const MAX_LABEL_BYTES: usize = 128;
52
53/// A pending join request as the server lists it. Nothing in it is trusted until checked.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct JoinRequest {
56    pub id: String,
57    pub label: String,
58    pub descriptor: String,
59    pub id_token: String,
60}
61
62/// Joining people whose verified token carries `value` in `claim` get `role`.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct ApprovalRule {
65    pub claim: String,
66    pub value: String,
67    pub role: Role,
68}
69
70/// What a pass did with one request.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum JoinDecision {
73    /// Added to the roster under `label`, or already a member under it.
74    Approved { label: String, role: Role },
75    /// Verified, but neither a rule nor the owner admitted it: it waits.
76    Waiting,
77    /// Its proof did not verify; the server is told to reject it.
78    Rejected(&'static str),
79}
80
81/// One request and what became of it.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct JoinOutcome {
84    pub id: String,
85    pub label: String,
86    pub decision: JoinDecision,
87}
88
89/// What an approval pass decided: the outcomes, and the members to add in one roster version.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Admissions {
92    pub outcomes: Vec<JoinOutcome>,
93    pub added: Vec<MemberEntry>,
94}
95
96/// Where the requests must have signed in (the issuer and the audience the owner pinned), and
97/// the cache they ask to join.
98#[derive(Debug, Clone, Copy)]
99pub struct JoinScope<'a> {
100    pub keys: &'a KeySet,
101    pub issuer: &'a str,
102    pub audience: &'a str,
103    pub cache: &'a CacheId,
104    pub now: i64,
105}
106
107fn label_ok(label: &str) -> bool {
108    !label.is_empty() && label.len() <= MAX_LABEL_BYTES && !label.chars().any(char::is_control)
109}
110
111fn free_label(wanted: &str, members: &[MemberEntry], added: &[MemberEntry]) -> Option<String> {
112    let held = |label: &str| members.iter().chain(added).any(|m| m.label == label);
113    if !held(wanted) {
114        return Some(wanted.to_owned());
115    }
116    (2..=MAX_LABEL_SUFFIX)
117        .map(|n| format!("{wanted}-{n}"))
118        .find(|label| label_ok(label) && !held(label))
119}
120
121/// Decides each request on its own proof: it must pass [`check_join_request`] in `scope`. A
122/// verified device is admitted with the role the owner `chose` for its request id, else the
123/// role of the first rule its token matches; else it waits. Only `developer` and `reader` are
124/// ever admitted. A device already in `members` counts as approved and is not added again.
125/// At most [`MAX_PER_PASS`] requests are read.
126pub fn plan_admissions(
127    members: &[MemberEntry],
128    requests: &[JoinRequest],
129    scope: JoinScope<'_>,
130    rules: &[ApprovalRule],
131    chosen: &[(String, Role)],
132) -> Admissions {
133    let mut outcomes = Vec::with_capacity(requests.len().min(MAX_PER_PASS));
134    let mut added: Vec<MemberEntry> = Vec::new();
135    for request in requests.iter().take(MAX_PER_PASS) {
136        let mut decision = decide(members, &added, request, scope, rules, chosen);
137        if let JoinDecision::Approved { label, role } = &decision
138            && !members.iter().any(|m| &m.label == label)
139        {
140            match identity_string::parse_descriptor(&request.descriptor)
141                .and_then(|descriptor| MemberEntry::from_descriptor(label, *role, &descriptor))
142            {
143                Ok(entry) => added.push(entry),
144                Err(_) => decision = JoinDecision::Rejected("not a member descriptor"),
145            }
146        }
147        outcomes.push(JoinOutcome {
148            id: request.id.clone(),
149            label: request.label.clone(),
150            decision,
151        });
152    }
153    Admissions { outcomes, added }
154}
155
156fn decide(
157    members: &[MemberEntry],
158    added: &[MemberEntry],
159    request: &JoinRequest,
160    scope: JoinScope<'_>,
161    rules: &[ApprovalRule],
162    chosen: &[(String, Role)],
163) -> JoinDecision {
164    let person = match check_join_request(
165        &request.id_token,
166        &request.descriptor,
167        scope.keys,
168        scope.issuer,
169        scope.audience,
170        scope.cache,
171        scope.now,
172    ) {
173        Ok(person) => person,
174        Err(why) => return JoinDecision::Rejected(why),
175    };
176    let Ok(descriptor) = identity_string::parse_descriptor(&request.descriptor) else {
177        return JoinDecision::Rejected("not a member descriptor");
178    };
179    let key = descriptor.ed25519_public;
180    if let Some(member) = members.iter().find(|m| m.sign_keys.contains(&key)) {
181        return JoinDecision::Approved {
182            label: member.label.clone(),
183            role: member.role,
184        };
185    }
186    if added.iter().any(|m| m.sign_keys.contains(&key)) {
187        return JoinDecision::Rejected("the device asked twice");
188    }
189    let role = chosen
190        .iter()
191        .find(|(id, _)| id == &request.id)
192        .map(|(_, role)| *role)
193        .or_else(|| {
194            rules
195                .iter()
196                .find(|rule| person.holds(&rule.claim, &rule.value))
197                .map(|rule| rule.role)
198        });
199    let label = label_ok(&request.label)
200        .then(|| free_label(&request.label, members, added))
201        .flatten();
202    match (role, label) {
203        (Some(role @ (Role::Developer | Role::Reader)), Some(label)) => {
204            JoinDecision::Approved { label, role }
205        }
206        _ => JoinDecision::Waiting,
207    }
208}