Functional Weave
Code in Python

auth.email-token@1.0.0

impl/rust/check_email_token.rs

4,275 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::auth_email_token_hash_email_token::{check_email_token_purpose, hash_email_token};  ← hashEmailToken, another function of this group · built into the same file, even by a slim install
use super::crypto_constant_time_equal::constant_time_equal;  ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
use super::encoding_hex_hex_decode::hex_decode;

fn is_hash(h: &str) -> bool {
    h.len() == 64 && h.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// Where a token's record is among records, and its outcome now: None when unknown.
pub fn find_email_token(
    records: &[EmailTokenRecord],
    token: &str,
    purpose: &str,
    now: i64,
) -> (Option<usize>, EmailTokenCheck) {
    check_email_token_purpose(purpose);
    if records.iter().any(|r| !is_hash(&r.token_hash)) {
        panic!("tokenHash must be 64 lowercase hex characters");
    }
    let unknown = EmailTokenCheck { outcome: "unknown".to_string(), record: None };
    if token.is_empty() {
        return (None, unknown);
    }
    let attempt = hex_decode(&hash_email_token(token, purpose));
    let mut index: Option<usize> = None;
    for (i, r) in records.iter().enumerate() {
        // Every record is compared, with no early exit.
        let same = constant_time_equal(&attempt, &hex_decode(&r.token_hash));
        if same && index.is_none() {
            index = Some(i);
        }
    }
    let found = match index {
        Some(i) if records[i].purpose == purpose => i,
        _ => return (None, unknown),
    };
    let record = records[found].clone();
    let outcome = if record.used_at.is_some() {
        "used"
    } else if now >= record.expires_at {
        "expired"
    } else {
        "ok"
    };
    (Some(found), EmailTokenCheck { outcome: outcome.to_string(), record: Some(record) })
}

/// What a token from a link is worth now, without using it up.
///
/// # Panics
/// Panics on a malformed purpose or a stored tokenHash that is not 64
/// lowercase hex characters.
pub fn check_email_token(records: &[EmailTokenRecord], token: &str, purpose: &str, now: i64) -> EmailTokenCheck {
    find_email_token(records, token, purpose, now).1
}

pub fn email_token_record_from_value(value: &Value) -> EmailTokenRecord {
    let text = |key: &str| match value.get(key) {
        Value::Str(s) => s.clone(),
        _ => panic!("tokenHash must be 64 lowercase hex characters"),
    };
    EmailTokenRecord {
        token_hash: text("tokenHash"),
        purpose: text("purpose"),
        subject: text("subject"),
        expires_at: match value.get("expiresAt") {
            Value::Int(i) => *i,
            _ => panic!("expiresAt must be a whole number of Unix seconds"),
        },
        used_at: match value.get("usedAt") {
            Value::Int(i) => Some(*i),
            _ => None,
        },
    }
}

pub fn email_token_record_to_value(r: &EmailTokenRecord) -> Value {
    Value::obj(vec![
        ("tokenHash", Value::str(&r.token_hash)),
        ("purpose", Value::str(&r.purpose)),
        ("subject", Value::str(&r.subject)),
        ("expiresAt", Value::Int(r.expires_at)),
        ("usedAt", match r.used_at {
            Some(i) => Value::Int(i),
            None => Value::Null,
        }),
    ])
}

pub fn email_token_args(args: &[Value]) -> (Vec<EmailTokenRecord>, String, String, i64) {
    let records: Vec<EmailTokenRecord> = match &args[0] {
        Value::Arr(items) => items.iter().map(email_token_record_from_value).collect(),
        _ => panic!("records must be a list of EmailTokenRecord"),
    };
    let token = match &args[1] {
        Value::Str(s) => s.clone(),
        _ => panic!("token must be a string"),
    };
    let purpose = match &args[2] {
        Value::Str(s) => s.clone(),
        _ => panic!("purpose must be 1 to 40 characters of a-z, 0-9 and -"),
    };
    let now = match &args[3] {
        Value::Int(i) => *i,
        _ => panic!("now must be a whole number of Unix seconds"),
    };
    (records, token, purpose, now)
}

pub fn fune_vector(args: &[Value]) -> Value {
    let (records, token, purpose, now) = email_token_args(args);
    let check = check_email_token(&records, &token, &purpose, now);
    Value::obj(vec![
        ("outcome", Value::str(&check.outcome)),
        ("record", match &check.record {
            Some(r) => email_token_record_to_value(r),
            None => Value::Null,
        }),
    ])
}