Functional Weave
Code in Rust

auth.bearer-token@1.0.0

impl/rust.rs

1,277 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

fn is_token_char(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'+' | b'/')
}

/// The token from `Authorization: Bearer <token>` (RFC 6750 section 2.1),
/// or `None`. Never panics: a malformed header is an answer (401), not an
/// error.
pub fn parse_bearer_token(authorization: Option<&str>) -> Option<String> {
    let value = authorization?.trim_matches(|c| c == ' ' || c == '\t');
    let b = value.as_bytes();
    if b.len() < 7 || !b[..6].eq_ignore_ascii_case(b"bearer") || b[6] != b' ' {
        return None;
    }
    let mut i = 6;
    while i < b.len() && b[i] == b' ' {
        i += 1;
    }
    let token = &b[i..];
    let mut j = 0;
    while j < token.len() && is_token_char(token[j]) {
        j += 1;
    }
    if j == 0 {
        return None;
    }
    while j < token.len() && token[j] == b'=' {
        j += 1;
    }
    if j == token.len() {
        Some(value[i..].to_string())
    } else {
        None
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    let header = match &args[0] {
        Value::Str(s) => Some(s.as_str()),
        _ => None,
    };
    match parse_bearer_token(header) {
        Some(token) => Value::Str(token),
        None => Value::Null,
    }
}