oxabl-cache-crypto 0.4.0

Client-side cryptography for the oxabl-cache remote compile cache: key hierarchy, seal and open, signatures.
Documentation
//! Join requests: the nonce that binds a device to a sign-in, and an owner's own check of it.

use oxabl_cache_format::{CacheId, Role};

use crate::id_token::{self, KeySet, SignedIn};
use crate::identity_string;
use crate::roster_member::MemberEntry;

/// Oldest sign-in a join request may rest on, in seconds.
pub const MAX_SIGN_IN_AGE_SECS: i64 = 14 * 24 * 60 * 60;
const NONCE_DOMAIN: &[u8] = b"oxabl-cache v1 join";

/// The join nonce of `descriptor` for the cache: hex BLAKE3 of the domain, the cache id's bytes
/// and the descriptor text.
pub fn join_nonce(cache: &CacheId, descriptor: &str) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(NONCE_DOMAIN);
    hasher.update(&cache.0);
    hasher.update(descriptor.as_bytes());
    hasher.finalize().to_hex().to_string()
}

/// Checks a join request without trusting the server that relayed it: the descriptor parses,
/// the ID token verifies against `keys` for `issuer` and the `audience` the owner pinned,
/// the sign-in is at most [`MAX_SIGN_IN_AGE_SECS`] old, and its `nonce` binds this descriptor
/// to this cache. Every refusal is a short reason.
pub fn check_join_request(
    id_token: &str,
    descriptor: &str,
    keys: &KeySet,
    issuer: &str,
    audience: &str,
    cache: &CacheId,
    now: i64,
) -> Result<SignedIn, &'static str> {
    if identity_string::parse_descriptor(descriptor).is_err() {
        return Err("not a member descriptor");
    }
    let person = id_token::verify(id_token, keys, issuer, audience, now, MAX_SIGN_IN_AGE_SECS)?;
    if person.claim("nonce") == Some(join_nonce(cache, descriptor).as_str()) {
        Ok(person)
    } else {
        Err("the sign-in does not bind this device")
    }
}

/// Requests decided in one pass at most.
pub const MAX_PER_PASS: usize = 64;
/// Suffixes tried to make a joining person's label unique.
const MAX_LABEL_SUFFIX: u32 = 99;
const MAX_LABEL_BYTES: usize = 128;

/// A pending join request as the server lists it. Nothing in it is trusted until checked.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JoinRequest {
    pub id: String,
    pub label: String,
    pub descriptor: String,
    pub id_token: String,
}

/// Joining people whose verified token carries `value` in `claim` get `role`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApprovalRule {
    pub claim: String,
    pub value: String,
    pub role: Role,
}

/// What a pass did with one request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JoinDecision {
    /// Added to the roster under `label`, or already a member under it.
    Approved { label: String, role: Role },
    /// Verified, but neither a rule nor the owner admitted it: it waits.
    Waiting,
    /// Its proof did not verify; the server is told to reject it.
    Rejected(&'static str),
}

/// One request and what became of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JoinOutcome {
    pub id: String,
    pub label: String,
    pub decision: JoinDecision,
}

/// What an approval pass decided: the outcomes, and the members to add in one roster version.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Admissions {
    pub outcomes: Vec<JoinOutcome>,
    pub added: Vec<MemberEntry>,
}

/// Where the requests must have signed in (the issuer and the audience the owner pinned), and
/// the cache they ask to join.
#[derive(Debug, Clone, Copy)]
pub struct JoinScope<'a> {
    pub keys: &'a KeySet,
    pub issuer: &'a str,
    pub audience: &'a str,
    pub cache: &'a CacheId,
    pub now: i64,
}

fn label_ok(label: &str) -> bool {
    !label.is_empty() && label.len() <= MAX_LABEL_BYTES && !label.chars().any(char::is_control)
}

fn free_label(wanted: &str, members: &[MemberEntry], added: &[MemberEntry]) -> Option<String> {
    let held = |label: &str| members.iter().chain(added).any(|m| m.label == label);
    if !held(wanted) {
        return Some(wanted.to_owned());
    }
    (2..=MAX_LABEL_SUFFIX)
        .map(|n| format!("{wanted}-{n}"))
        .find(|label| label_ok(label) && !held(label))
}

/// Decides each request on its own proof: it must pass [`check_join_request`] in `scope`. A
/// verified device is admitted with the role the owner `chose` for its request id, else the
/// role of the first rule its token matches; else it waits. Only `developer` and `reader` are
/// ever admitted. A device already in `members` counts as approved and is not added again.
/// At most [`MAX_PER_PASS`] requests are read.
pub fn plan_admissions(
    members: &[MemberEntry],
    requests: &[JoinRequest],
    scope: JoinScope<'_>,
    rules: &[ApprovalRule],
    chosen: &[(String, Role)],
) -> Admissions {
    let mut outcomes = Vec::with_capacity(requests.len().min(MAX_PER_PASS));
    let mut added: Vec<MemberEntry> = Vec::new();
    for request in requests.iter().take(MAX_PER_PASS) {
        let mut decision = decide(members, &added, request, scope, rules, chosen);
        if let JoinDecision::Approved { label, role } = &decision
            && !members.iter().any(|m| &m.label == label)
        {
            match identity_string::parse_descriptor(&request.descriptor)
                .and_then(|descriptor| MemberEntry::from_descriptor(label, *role, &descriptor))
            {
                Ok(entry) => added.push(entry),
                Err(_) => decision = JoinDecision::Rejected("not a member descriptor"),
            }
        }
        outcomes.push(JoinOutcome {
            id: request.id.clone(),
            label: request.label.clone(),
            decision,
        });
    }
    Admissions { outcomes, added }
}

fn decide(
    members: &[MemberEntry],
    added: &[MemberEntry],
    request: &JoinRequest,
    scope: JoinScope<'_>,
    rules: &[ApprovalRule],
    chosen: &[(String, Role)],
) -> JoinDecision {
    let person = match check_join_request(
        &request.id_token,
        &request.descriptor,
        scope.keys,
        scope.issuer,
        scope.audience,
        scope.cache,
        scope.now,
    ) {
        Ok(person) => person,
        Err(why) => return JoinDecision::Rejected(why),
    };
    let Ok(descriptor) = identity_string::parse_descriptor(&request.descriptor) else {
        return JoinDecision::Rejected("not a member descriptor");
    };
    let key = descriptor.ed25519_public;
    if let Some(member) = members.iter().find(|m| m.sign_keys.contains(&key)) {
        return JoinDecision::Approved {
            label: member.label.clone(),
            role: member.role,
        };
    }
    if added.iter().any(|m| m.sign_keys.contains(&key)) {
        return JoinDecision::Rejected("the device asked twice");
    }
    let role = chosen
        .iter()
        .find(|(id, _)| id == &request.id)
        .map(|(_, role)| *role)
        .or_else(|| {
            rules
                .iter()
                .find(|rule| person.holds(&rule.claim, &rule.value))
                .map(|rule| rule.role)
        });
    let label = label_ok(&request.label)
        .then(|| free_label(&request.label, members, added))
        .flatten();
    match (role, label) {
        (Some(role @ (Role::Developer | Role::Reader)), Some(label)) => {
            JoinDecision::Approved { label, role }
        }
        _ => JoinDecision::Waiting,
    }
}