Skip to content

Commit

Permalink
Add sample for FFI calls
Browse files Browse the repository at this point in the history
  • Loading branch information
divarvel committed Nov 12, 2024
1 parent 0fce85c commit af5f890
Show file tree
Hide file tree
Showing 4 changed files with 157 additions and 1 deletion.
69 changes: 68 additions & 1 deletion biscuit-auth/examples/testcases.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@ use biscuit::macros::*;
use biscuit::Authorizer;
use biscuit::{builder::*, builder_ext::*, Biscuit};
use biscuit::{KeyPair, PrivateKey, PublicKey};
use biscuit_auth::builder;
use biscuit_auth::datalog::ExternFunc;
use biscuit_auth::datalog::RunLimits;
use prost::Message;
use rand::prelude::*;
use serde::Serialize;
use std::collections::HashMap;
use std::sync::Arc;
use std::{
collections::{BTreeMap, BTreeSet},
fs::File,
Expand Down Expand Up @@ -157,6 +162,9 @@ fn run(target: String, root_key: Option<String>, test: bool, json: bool) {
add_test_result(&mut results, type_of(&target, &root, test));

add_test_result(&mut results, array_map(&target, &root, test));

add_test_result(&mut results, ffi(&target, &root, test));

if json {
let s = serde_json::to_string_pretty(&TestCases {
root_private_key: hex::encode(root.private().to_bytes()),
Expand Down Expand Up @@ -297,6 +305,15 @@ enum AuthorizerResult {
}

fn validate_token(root: &KeyPair, data: &[u8], authorizer_code: &str) -> Validation {
validate_token_with_limits(root, data, authorizer_code, RunLimits::default())
}

fn validate_token_with_limits(
root: &KeyPair,
data: &[u8],
authorizer_code: &str,
run_limits: RunLimits,
) -> Validation {
let token = match Biscuit::from(&data[..], &root.public()) {
Ok(t) => t,
Err(e) => {
Expand Down Expand Up @@ -331,7 +348,7 @@ fn validate_token(root: &KeyPair, data: &[u8], authorizer_code: &str) -> Validat
}
};

let res = authorizer.authorize();
let res = authorizer.authorize_with_limits(run_limits);
//println!("authorizer world:\n{}", authorizer.print_world());
let (_, _, _, policies) = authorizer.dump();
let snapshot = authorizer.snapshot().unwrap();
Expand Down Expand Up @@ -2269,6 +2286,56 @@ fn array_map(target: &str, root: &KeyPair, test: bool) -> TestResult {
}
}

fn ffi(target: &str, root: &KeyPair, test: bool) -> TestResult {
let mut rng: StdRng = SeedableRng::seed_from_u64(1234);
let title = "test ffi calls (v6 blocks)".to_string();
let filename = "test035_ffi".to_string();
let token;

let biscuit =
biscuit!(r#"check if true.extern::test(), "a".extern::test("a") == "equal strings""#)
.build_with_rng(&root, SymbolTable::default(), &mut rng)
.unwrap();
token = print_blocks(&biscuit);

let data = write_or_load_testcase(target, &filename, root, &biscuit, test);

let mut validations = BTreeMap::new();
validations.insert(
"".to_string(),
validate_token_with_limits(
root,
&data[..],
"allow if true",
RunLimits {
extern_funcs: HashMap::from([(
"test".to_string(),
ExternFunc::new(Arc::new(|left, right| match (left, right) {
(t, None) => Ok(t),
(builder::Term::Str(left), Some(builder::Term::Str(right)))
if left == right =>
{
Ok(builder::Term::Str("equal strings".to_string()))
}
(builder::Term::Str(_), Some(builder::Term::Str(_))) => {
Ok(builder::Term::Str("different strings".to_string()))

Check warning on line 2321 in biscuit-auth/examples/testcases.rs

View check run for this annotation

Codecov / codecov/patch

biscuit-auth/examples/testcases.rs#L2321

Added line #L2321 was not covered by tests
}
_ => Err("unsupported operands".to_string()),

Check warning on line 2323 in biscuit-auth/examples/testcases.rs

View check run for this annotation

Codecov / codecov/patch

biscuit-auth/examples/testcases.rs#L2323

Added line #L2323 was not covered by tests
})),
)]),
..Default::default()
},
),
);

TestResult {
title,
filename,
token,
validations,
}
}

fn print_blocks(token: &Biscuit) -> Vec<BlockContent> {
let mut v = Vec::new();

Expand Down
48 changes: 48 additions & 0 deletions biscuit-auth/samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3139,3 +3139,51 @@ World {

result: `Ok(0)`


------------------------------

## test ffi calls (v6 blocks): test035_ffi.bc
### token

authority:
symbols: ["a", "equal strings"]

public keys: []

```
check if true.extern::test(), "a".extern::test("a") == "equal strings";
```

### validation

authorizer code:
```
allow if true;
```

revocation ids:
- `b1696fd9f9ec456d65a863df034cb132dc7dca076d16f5bc3e73986a4cc88cc4e7902dc8519cb60961e3f33799c147f874c7e0d7e12ef1b461e361e0c0aa580b`

authorizer world:
```
World {
facts: []
rules: []
checks: [
Checks {
origin: Some(
0,
),
checks: [
"check if true.extern::test(), \"a\".extern::test(\"a\") == \"equal strings\"",
],
},
]
policies: [
"allow if true",
]
}
```

result: `Ok(0)`

41 changes: 41 additions & 0 deletions biscuit-auth/samples/samples.json
Original file line number Diff line number Diff line change
Expand Up @@ -2913,6 +2913,47 @@
]
}
}
},
{
"title": "test ffi calls (v6 blocks)",
"filename": "test035_ffi.bc",
"token": [
{
"symbols": [
"a",
"equal strings"
],
"public_keys": [],
"external_key": null,
"code": "check if true.extern::test(), \"a\".extern::test(\"a\") == \"equal strings\";\n"
}
],
"validations": {
"": {
"world": {
"facts": [],
"rules": [],
"checks": [
{
"origin": 0,
"checks": [
"check if true.extern::test(), \"a\".extern::test(\"a\") == \"equal strings\""
]
}
],
"policies": [
"allow if true"
]
},
"result": {
"Ok": 0
},
"authorizer_code": "allow if true;\n",
"revocation_ids": [
"b1696fd9f9ec456d65a863df034cb132dc7dca076d16f5bc3e73986a4cc88cc4e7902dc8519cb60961e3f33799c147f874c7e0d7e12ef1b461e361e0c0aa580b"
]
}
}
}
]
}
Binary file added biscuit-auth/samples/test035_ffi.bc
Binary file not shown.

0 comments on commit af5f890

Please sign in to comment.