1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use std::{
collections::{BTreeSet, HashMap},
time::{SystemTime, UNIX_EPOCH},
};
#[cfg(feature = "datalog-macro")]
use quote::{quote, ToTokens};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Term {
Variable(String),
Integer(i64),
Str(String),
Date(u64),
Bytes(Vec<u8>),
Bool(bool),
Set(BTreeSet<Term>),
Parameter(String),
}
impl From<&Term> for Term {
fn from(i: &Term) -> Self {
match i {
Term::Variable(ref v) => Term::Variable(v.clone()),
Term::Integer(ref i) => Term::Integer(*i),
Term::Str(ref s) => Term::Str(s.clone()),
Term::Date(ref d) => Term::Date(*d),
Term::Bytes(ref s) => Term::Bytes(s.clone()),
Term::Bool(b) => Term::Bool(*b),
Term::Set(ref s) => Term::Set(s.clone()),
Term::Parameter(ref p) => Term::Parameter(p.clone()),
}
}
}
impl AsRef<Term> for Term {
fn as_ref(&self) -> &Term {
self
}
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Term {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
tokens.extend(match self {
Term::Variable(v) => quote! { ::biscuit_auth::builder::Term::Variable(#v.to_string()) },
Term::Integer(v) => quote! { ::biscuit_auth::builder::Term::Integer(#v) },
Term::Str(v) => quote! { ::biscuit_auth::builder::Term::Str(#v.to_string()) },
Term::Date(v) => quote! { ::biscuit_auth::builder::Term::Date(#v) },
Term::Bool(v) => quote! { ::biscuit_auth::builder::Term::Bool(#v) },
Term::Parameter(v) => quote! { ::biscuit_auth::builder::Term::Parameter(#v.to_string()) },
Term::Bytes(v) => quote! { ::biscuit_auth::builder::Term::Bytes(<[u8]>::into_vec(Box::new([ #(#v),*]))) },
Term::Set(v) => {
quote! {{
use std::iter::FromIterator;
::biscuit_auth::builder::Term::Set(::std::collections::BTreeSet::from_iter(<[::biscuit_auth::builder::Term]>::into_vec(Box::new([ #(#v),*]))))
}}
}
})
}
}
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum Scope {
Authority,
Previous,
PublicKey(PublicKey),
Parameter(String),
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Scope {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
tokens.extend(match self {
Scope::Authority => quote! { ::biscuit_auth::builder::Scope::Authority},
Scope::Previous => quote! { ::biscuit_auth::builder::Scope::Previous},
Scope::PublicKey(pk) => {
let bytes = pk.iter();
quote! { ::biscuit_auth::builder::Scope::PublicKey(
::biscuit_auth::PublicKey::from_bytes(&[#(#bytes),*]).unwrap()
)}
}
Scope::Parameter(v) => {
quote! { ::biscuit_auth::builder::Scope::Parameter(#v.to_string())}
}
})
}
}
#[derive(Debug, Clone, PartialEq, Hash, Eq)]
pub struct Predicate {
pub name: String,
pub terms: Vec<Term>,
}
impl Predicate {
pub fn new<T: Into<Vec<Term>>>(name: String, terms: T) -> Predicate {
Predicate {
name,
terms: terms.into(),
}
}
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Predicate {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let name = &self.name;
let terms = self.terms.iter();
tokens.extend(quote! {
::biscuit_auth::builder::Predicate::new(
#name.to_string(),
<[::biscuit_auth::builder::Term]>::into_vec(Box::new([#(#terms),*]))
)
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fact {
pub predicate: Predicate,
pub parameters: Option<HashMap<String, Option<Term>>>,
}
impl Fact {
pub fn new<T: Into<Vec<Term>>>(name: String, terms: T) -> Fact {
let mut parameters = HashMap::new();
let terms: Vec<Term> = terms.into();
for term in &terms {
if let Term::Parameter(name) = &term {
parameters.insert(name.to_string(), None);
}
}
Fact {
predicate: Predicate::new(name, terms),
parameters: Some(parameters),
}
}
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Fact {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let name = &self.predicate.name;
let terms = self.predicate.terms.iter();
tokens.extend(quote! {
::biscuit_auth::builder::Fact::new(
#name.to_string(),
<[::biscuit_auth::builder::Term]>::into_vec(Box::new([#(#terms),*]))
)
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Expression {
pub ops: Vec<Op>,
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Expression {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let ops = self.ops.iter();
tokens.extend(quote! {
::biscuit_auth::builder::Expression {
ops: <[::biscuit_auth::builder::Op]>::into_vec(Box::new([#(#ops),*]))
}
});
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Op {
Value(Term),
Unary(Unary),
Binary(Binary),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unary {
Negate,
Parens,
Length,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Binary {
LessThan,
GreaterThan,
LessOrEqual,
GreaterOrEqual,
Equal,
Contains,
Prefix,
Suffix,
Regex,
Add,
Sub,
Mul,
Div,
And,
Or,
Intersection,
Union,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Op {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
tokens.extend(match self {
Op::Value(t) => quote! { ::biscuit_auth::builder::Op::Value(#t) },
Op::Unary(u) => quote! { ::biscuit_auth::builder::Op::Unary(#u) },
Op::Binary(b) => quote! { ::biscuit_auth::builder::Op::Binary(#b) },
});
}
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Unary {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
tokens.extend(match self {
Unary::Negate => quote! {::biscuit_auth::datalog::Unary::Negate },
Unary::Parens => quote! {::biscuit_auth::datalog::Unary::Parens },
Unary::Length => quote! {::biscuit_auth::datalog::Unary::Length },
});
}
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Binary {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
tokens.extend(match self {
Binary::LessThan => quote! { ::biscuit_auth::datalog::Binary::LessThan },
Binary::GreaterThan => quote! { ::biscuit_auth::datalog::Binary::GreaterThan },
Binary::LessOrEqual => quote! { ::biscuit_auth::datalog::Binary::LessOrEqual },
Binary::GreaterOrEqual => quote! { ::biscuit_auth::datalog::Binary::GreaterOrEqual },
Binary::Equal => quote! { ::biscuit_auth::datalog::Binary::Equal },
Binary::Contains => quote! { ::biscuit_auth::datalog::Binary::Contains },
Binary::Prefix => quote! { ::biscuit_auth::datalog::Binary::Prefix },
Binary::Suffix => quote! { ::biscuit_auth::datalog::Binary::Suffix },
Binary::Regex => quote! { ::biscuit_auth::datalog::Binary::Regex },
Binary::Add => quote! { ::biscuit_auth::datalog::Binary::Add },
Binary::Sub => quote! { ::biscuit_auth::datalog::Binary::Sub },
Binary::Mul => quote! { ::biscuit_auth::datalog::Binary::Mul },
Binary::Div => quote! { ::biscuit_auth::datalog::Binary::Div },
Binary::And => quote! { ::biscuit_auth::datalog::Binary::And },
Binary::Or => quote! { ::biscuit_auth::datalog::Binary::Or },
Binary::Intersection => quote! { ::biscuit_auth::datalog::Binary::Intersection },
Binary::Union => quote! { ::biscuit_auth::datalog::Binary::Union },
Binary::BitwiseAnd => quote! { ::biscuit_auth::datalog::Binary::BitwiseAnd },
Binary::BitwiseOr => quote! { ::biscuit_auth::datalog::Binary::BitwiseOr },
Binary::BitwiseXor => quote! { ::biscuit_auth::datalog::Binary::BitwiseXor },
});
}
}
pub type PublicKey = Vec<u8>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rule {
pub head: Predicate,
pub body: Vec<Predicate>,
pub expressions: Vec<Expression>,
pub parameters: Option<HashMap<String, Option<Term>>>,
pub scopes: Vec<Scope>,
pub scope_parameters: Option<HashMap<String, Option<PublicKey>>>,
}
impl Rule {
pub fn new(
head: Predicate,
body: Vec<Predicate>,
expressions: Vec<Expression>,
scopes: Vec<Scope>,
) -> Rule {
let mut parameters = HashMap::new();
let mut scope_parameters = HashMap::new();
for term in &head.terms {
if let Term::Parameter(name) = &term {
parameters.insert(name.to_string(), None);
}
}
for predicate in &body {
for term in &predicate.terms {
if let Term::Parameter(name) = &term {
parameters.insert(name.to_string(), None);
}
}
}
for expression in &expressions {
for op in &expression.ops {
if let Op::Value(Term::Parameter(name)) = &op {
parameters.insert(name.to_string(), None);
}
}
}
for scope in &scopes {
if let Scope::Parameter(name) = &scope {
scope_parameters.insert(name.to_string(), None);
}
}
Rule {
head,
body,
expressions,
parameters: Some(parameters),
scopes,
scope_parameters: Some(scope_parameters),
}
}
pub fn validate_variables(&self) -> Result<(), String> {
let mut head_variables: std::collections::HashSet<String> = self
.head
.terms
.iter()
.filter_map(|term| match term {
Term::Variable(s) => Some(s.to_string()),
_ => None,
})
.collect();
for predicate in self.body.iter() {
for term in predicate.terms.iter() {
if let Term::Variable(v) = term {
head_variables.remove(v);
if head_variables.is_empty() {
return Ok(());
}
}
}
}
if head_variables.is_empty() {
Ok(())
} else {
Err(format!(
"rule head contains variables that are not used in predicates of the rule's body: {}",
head_variables
.iter()
.map(|s| format!("${}", s))
.collect::<Vec<_>>()
.join(", ")
))
}
}
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Rule {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let head = &self.head;
let body = self.body.iter();
let expressions = self.expressions.iter();
let scopes = self.scopes.iter();
tokens.extend(quote! {
::biscuit_auth::builder::Rule::new(
#head,
<[::biscuit_auth::builder::Predicate]>::into_vec(Box::new([#(#body),*])),
<[::biscuit_auth::builder::Expression]>::into_vec(Box::new([#(#expressions),*])),
<[::biscuit_auth::builder::Scope]>::into_vec(Box::new([#(#scopes),*]))
)
});
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Check {
pub queries: Vec<Rule>,
pub kind: CheckKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CheckKind {
One,
All,
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Check {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let queries = self.queries.iter();
let kind = &self.kind;
tokens.extend(quote! {
::biscuit_auth::builder::Check {
queries: <[::biscuit_auth::builder::Rule]>::into_vec(Box::new([#(#queries),*])),
kind: #kind,
}
});
}
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for CheckKind {
fn to_tokens(&self, tokens: &mut quote::__private::TokenStream) {
tokens.extend(match self {
CheckKind::One => quote! {
::biscuit_auth::builder::CheckKind::One
},
CheckKind::All => quote! {
::biscuit_auth::builder::CheckKind::All
},
});
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PolicyKind {
Allow,
Deny,
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for PolicyKind {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
tokens.extend(match self {
PolicyKind::Allow => quote! {
::biscuit_auth::builder::PolicyKind::Allow
},
PolicyKind::Deny => quote! {
::biscuit_auth::builder::PolicyKind::Deny
},
});
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Policy {
pub queries: Vec<Rule>,
pub kind: PolicyKind,
}
#[cfg(feature = "datalog-macro")]
impl ToTokens for Policy {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let queries = self.queries.iter();
let kind = &self.kind;
tokens.extend(quote! {
::biscuit_auth::builder::Policy{
kind: #kind,
queries: <[::biscuit_auth::builder::Rule]>::into_vec(Box::new([#(#queries),*])),
}
});
}
}
pub fn fact<I: AsRef<Term>>(name: &str, terms: &[I]) -> Fact {
let pred = pred(name, terms);
Fact::new(pred.name, pred.terms)
}
pub fn pred<I: AsRef<Term>>(name: &str, terms: &[I]) -> Predicate {
Predicate {
name: name.to_string(),
terms: terms.iter().map(|term| term.as_ref().clone()).collect(),
}
}
pub fn rule<T: AsRef<Term>, P: AsRef<Predicate>>(
head_name: &str,
head_terms: &[T],
predicates: &[P],
) -> Rule {
Rule::new(
pred(head_name, head_terms),
predicates.iter().map(|p| p.as_ref().clone()).collect(),
Vec::new(),
vec![],
)
}
pub fn constrained_rule<T: AsRef<Term>, P: AsRef<Predicate>, E: AsRef<Expression>>(
head_name: &str,
head_terms: &[T],
predicates: &[P],
expressions: &[E],
) -> Rule {
Rule::new(
pred(head_name, head_terms),
predicates.iter().map(|p| p.as_ref().clone()).collect(),
expressions.iter().map(|c| c.as_ref().clone()).collect(),
vec![],
)
}
pub fn check<P: AsRef<Predicate>>(predicates: &[P], kind: CheckKind) -> Check {
let empty_terms: &[Term] = &[];
Check {
queries: vec![Rule::new(
pred("query", empty_terms),
predicates.iter().map(|p| p.as_ref().clone()).collect(),
vec![],
vec![],
)],
kind,
}
}
pub fn int(i: i64) -> Term {
Term::Integer(i)
}
pub fn string(s: &str) -> Term {
Term::Str(s.to_string())
}
pub fn date(t: &SystemTime) -> Term {
let dur = t.duration_since(UNIX_EPOCH).unwrap();
Term::Date(dur.as_secs())
}
pub fn var(s: &str) -> Term {
Term::Variable(s.to_string())
}
pub fn variable(s: &str) -> Term {
Term::Variable(s.to_string())
}
pub fn bytes(s: &[u8]) -> Term {
Term::Bytes(s.to_vec())
}
pub fn boolean(b: bool) -> Term {
Term::Bool(b)
}
pub fn set(s: BTreeSet<Term>) -> Term {
Term::Set(s)
}
pub fn parameter(p: &str) -> Term {
Term::Parameter(p.to_string())
}