Struct Biscuit

Source
pub struct Biscuit { /* private fields */ }
Expand description

This structure represents a valid Biscuit token

It contains multiple Block elements, the associated symbol table, and a serialized version of this data

extern crate biscuit_auth as biscuit;

use biscuit::{KeyPair, Biscuit, builder::*, builder_ext::*};

fn main() -> Result<(), biscuit::error::Token> {
  let root = KeyPair::new();

  // first we define the authority block for global data,
  // like access rights
  // data from the authority block cannot be created in any other block
  let token1 = Biscuit::builder()
      .fact(fact("right", &[string("/a/file1.txt"), string("read")]))?

      // facts and rules can also be parsed from a string
      .fact("right(\"/a/file1.txt\", \"read\")")?
      .build(&root)?;

  // we can create a new block builder from that token
  let builder2 = BlockBuilder::new()
      .check_operation("read");

  let token2 = token1.append(builder2)?;

  Ok(())
}

Implementations§

Source§

impl Biscuit

Source

pub fn builder() -> BiscuitBuilder

create the first block’s builder

call builder::BiscuitBuilder::build to create the token

Source

pub fn from<T, KP>(slice: T, key_provider: KP) -> Result<Biscuit, Token>
where T: AsRef<[u8]>, KP: RootKeyProvider,

deserializes a token and validates the signature using the root public key

Source

pub fn from_base64<T, KP>(slice: T, key_provider: KP) -> Result<Biscuit, Token>
where T: AsRef<[u8]>, KP: RootKeyProvider,

deserializes a token and validates the signature using the root public key

Source

pub fn unsafe_deprecated_deserialize<T, KP>( slice: T, key_provider: KP, ) -> Result<Biscuit, Token>
where T: AsRef<[u8]>, KP: RootKeyProvider,

deserializes a token and validates the signature using the root public key

This allows the deprecated 3rd party block format

Source

pub fn to_vec(&self) -> Result<Vec<u8>, Token>

serializes the token

Examples found in repository?
examples/token_verification.rs (line 107)
92fn generate_example_token(keypair: Arc<KeyPair>) -> Result<String, TokenError> {
93    // Create a simple test biscuit with authorization rules
94    let biscuit_builder = biscuit!(
95        r#"
96            // Grant rights to alice for resource1
97            right("alice", "resource1", "read");
98            right("alice", "resource1", "write");
99        "#
100    );
101
102    // Build and serialize the token
103    let biscuit = biscuit_builder
104        .build(&keypair)
105        .map_err(TokenError::biscuit_error)?;
106
107    let token_bytes = biscuit.to_vec().map_err(TokenError::biscuit_error)?;
108
109    // Encode to base64 for transmission
110    Ok(encode_token(&token_bytes))
111}
112
113/// Generate a token with service chain attestations
114fn generate_service_chain_token(
115    root_keypair: Arc<KeyPair>,
116    service1_public_key: String,
117    service2_public_key: String,
118) -> Result<String, TokenError> {
119    // Create a biscuit with service chain authorization
120    let biscuit_builder = biscuit!(
121        r#"
122            // Basic rights
123            right("alice", "resource1", "read");
124            right("alice", "resource1", "write");
125            
126            // Service nodes
127            node($s, "node1") <- service($s) trusting authority, {node1_public_key};
128            node($s, "node2") <- service($s) trusting authority, {node2_public_key};
129        "#,
130        node1_public_key = biscuit_key_from_string(service1_public_key)?,
131        node2_public_key = biscuit_key_from_string(service2_public_key)?,
132    );
133
134    // Build and serialize the token
135    let biscuit = biscuit_builder
136        .build(&root_keypair)
137        .map_err(TokenError::biscuit_error)?;
138
139    let token_bytes = biscuit.to_vec().map_err(TokenError::biscuit_error)?;
140
141    // Encode to base64
142    Ok(encode_token(&token_bytes))
143}
More examples
Hide additional examples
examples/token_attenuation.rs (line 77)
59fn generate_example_token() -> Result<(String, KeyPair), TokenError> {
60    // Create a test keypair
61    let keypair = KeyPair::new();
62
63    // Create a simple test biscuit with authorization rules
64    let biscuit_builder = biscuit!(
65        r#"
66            // Grant rights to alice for resource1
67            right("alice", "resource1", "read");
68            right("alice", "resource1", "write");
69        "#
70    );
71
72    // Build and serialize the token
73    let biscuit = biscuit_builder
74        .build(&keypair)
75        .map_err(TokenError::biscuit_error)?;
76
77    let token_bytes = biscuit.to_vec().map_err(TokenError::biscuit_error)?;
78
79    // Encode to base64 for transmission
80    Ok((encode_token(&token_bytes), keypair))
81}
Source

pub fn to_base64(&self) -> Result<String, Token>

serializes the token and encode it to a (URL safe) base64 string

Source

pub fn serialized_size(&self) -> Result<usize, Token>

serializes the token

Source

pub fn seal(&self) -> Result<Biscuit, Token>

creates a sealed version of the token

sealed tokens cannot be attenuated

Source

pub fn authorizer(&self) -> Result<Authorizer, Token>

creates an authorizer from this token

Source

pub fn append(&self, block_builder: BlockBuilder) -> Result<Biscuit, Token>

adds a new block to the token

since the public key is integrated into the token, the keypair can be discarded right after calling this function

Source

pub fn context(&self) -> Vec<Option<String>>

returns the list of context elements of each block

the context is a free form text field in which application specific data can be stored

Source

pub fn root_key_id(&self) -> Option<u32>

returns an (optional) root key identifier. It provides a hint for public key selection during verification

Source

pub fn revocation_identifiers(&self) -> Vec<Vec<u8>>

returns a list of revocation identifiers for each block, in order

revocation identifiers are unique: tokens generated separately with the same contents will have different revocation ids

Source

pub fn external_public_keys(&self) -> Vec<Option<PublicKey>>

returns a list of external key for each block, in order

Blocks carrying an external public key are third-party blocks and their contents can be trusted as coming from the holder of the corresponding private key

Source

pub fn print(&self) -> String

pretty printer for this token

Source

pub fn print_block_source(&self, index: usize) -> Result<String, Token>

prints the content of a block as Datalog source code

Source

pub fn block_version(&self, index: usize) -> Result<u32, Token>

gets the datalog version for a given block

Source

pub fn container(&self) -> &SerializedBiscuit

returns the internal representation of the token

Source

pub fn append_with_keypair( &self, keypair: &KeyPair, block_builder: BlockBuilder, ) -> Result<Biscuit, Token>

adds a new block to the token, using the provided CSPRNG

since the public key is integrated into the token, the keypair can be discarded right after calling this function

Source

pub fn third_party_request(&self) -> Result<ThirdPartyRequest, Token>

Source

pub fn append_third_party( &self, external_key: PublicKey, response: ThirdPartyBlock, ) -> Result<Biscuit, Token>

Source

pub fn append_third_party_with_keypair( &self, external_key: PublicKey, response: ThirdPartyBlock, next_keypair: KeyPair, ) -> Result<Biscuit, Token>

Source

pub fn block_symbols(&self, index: usize) -> Result<Vec<String>, Token>

gets the list of symbols from a block

Source

pub fn block_public_keys(&self, index: usize) -> Result<PublicKeys, Token>

gets the list of public keys from a block

Source

pub fn block_external_key( &self, index: usize, ) -> Result<Option<PublicKey>, Token>

gets the list of public keys from a block

Source

pub fn block_count(&self) -> usize

returns the number of blocks (at least 1)

Trait Implementations§

Source§

impl Clone for Biscuit

Source§

fn clone(&self) -> Biscuit

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Biscuit

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Display for Biscuit

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V