hessra_token/
attenuate.rs

1extern crate biscuit_auth as biscuit;
2
3use biscuit::macros::block;
4use biscuit::{Biscuit, KeyPair, PublicKey};
5
6use crate::error::TokenError;
7
8/// Add a service node attestation to a token
9///
10/// This function adds a third-party block to a token that attests
11/// that the token has passed through the specified service node.
12///
13/// # Arguments
14///
15/// * `token` - The binary token data
16/// * `public_key` - The public key to verify the token
17/// * `service` - The service identifier
18/// * `node_name` - The name of the node attesting
19/// * `node_key` - The public key of the node attesting
20/// * `node_private_key` - Optional private key for signing, if not provided a test key will be generated
21///
22/// # Returns
23///
24/// The attenuated token binary data
25pub fn add_service_node_attenuation(
26    token: Vec<u8>,
27    public_key: PublicKey,
28    service: &str,
29    node_key: &KeyPair,
30) -> Result<Vec<u8>, TokenError> {
31    let biscuit = Biscuit::from(&token, public_key).map_err(TokenError::biscuit_error)?;
32
33    // Create a third-party request
34    let third_party_request = biscuit
35        .third_party_request()
36        .map_err(TokenError::biscuit_error)?;
37    let service_name = service.to_string();
38
39    // Create a block for the service attestation
40    let third_party_block = block!(
41        r#"
42            service({service_name});
43        "#
44    );
45
46    // Create the third-party block and sign it
47    let third_party_block = third_party_request
48        .create_block(&node_key.private(), third_party_block)
49        .map_err(TokenError::biscuit_error)?;
50
51    // Append the third-party block to the token
52    let attenuated_biscuit = biscuit
53        .append_third_party(node_key.public(), third_party_block)
54        .map_err(TokenError::biscuit_error)?;
55
56    // Serialize the token
57    let attenuated_token = attenuated_biscuit
58        .to_vec()
59        .map_err(TokenError::biscuit_error)?;
60
61    Ok(attenuated_token)
62}