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
use biscuit_auth as biscuit;
use wasm_bindgen::prelude::*;

#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

/// a Biscuit token
///
/// it can produce an attenuated or sealed token, or be used
/// in an authorizer along with Datalog policies
#[wasm_bindgen]
pub struct Biscuit(biscuit::Biscuit);

#[wasm_bindgen]
impl Biscuit {
    /// Creates a BiscuitBuilder
    ///
    /// the builder can then create a new token with a root key
    pub fn builder() -> BiscuitBuilder {
        BiscuitBuilder::new()
    }

    /// Creates a BlockBuilder to prepare for attenuation
    ///
    /// the bulder can then be given to the token's append method to create an attenuated token
    pub fn create_block(&self) -> BlockBuilder {
        BlockBuilder(self.0.create_block())
    }

    /// Creates an attenuated token by adding the block generated by the BlockBuilder
    pub fn append(&self, block: BlockBuilder) -> Result<Biscuit, JsValue> {
        Ok(Biscuit(
            self.0
                .append(block.0)
                .map_err(|e| JsValue::from_serde(&e).unwrap())?,
        ))
    }

    /// Creates an authorizer from the token
    pub fn authorizer(&self) -> Result<Authorizer, JsValue> {
        Ok(Authorizer {
            token: Some(self.0.clone()),
            ..Authorizer::default()
        })
    }

    /// Seals the token
    ///
    /// A sealed token cannot be attenuated
    pub fn seal(&self) -> Result<Biscuit, JsValue> {
        Ok(Biscuit(
            self.0
                .seal()
                .map_err(|e| JsValue::from_serde(&e).unwrap())?,
        ))
    }

    /// Deserializes a token from raw data
    ///
    /// This will check the signature using the root key
    pub fn from_bytes(data: &[u8], root: &PublicKey) -> Result<Biscuit, JsValue> {
        Ok(Biscuit(
            biscuit::Biscuit::from(data, |_| root.0)
                .map_err(|e| JsValue::from_serde(&e).unwrap())?,
        ))
    }

    /// Deserializes a token from URL safe base 64 data
    ///
    /// This will check the signature using the root key
    pub fn from_base64(data: &str, root: &PublicKey) -> Result<Biscuit, JsValue> {
        Ok(Biscuit(
            biscuit::Biscuit::from_base64(data, |_| root.0)
                .map_err(|e| JsValue::from_serde(&e).unwrap())?,
        ))
    }

    /// Serializes to raw data
    pub fn to_bytes(&self) -> Result<Box<[u8]>, JsValue> {
        Ok(self
            .0
            .to_vec()
            .map_err(|e| JsValue::from_serde(&e).unwrap())?
            .into_boxed_slice())
    }

    /// Serializes to URL safe base 64 data
    pub fn to_base64(&self) -> Result<String, JsValue> {
        Ok(self
            .0
            .to_base64()
            .map_err(|e| JsValue::from_serde(&e).unwrap())?)
    }

    /// Returns the list of revocation identifiers, encoded as URL safe base 64
    pub fn revocation_identifiers(&self) -> Box<[JsValue]> {
        let ids: Vec<_> = self
            .0
            .revocation_identifiers()
            .into_iter()
            .map(|id| base64::encode_config(id, base64::URL_SAFE).into())
            .collect();
        ids.into_boxed_slice()
    }

    /// Returns the number of blocks in the token
    pub fn block_count(&self) -> usize {
        self.0.block_count()
    }

    /// Prints a block's content as Datalog code
    pub fn block_source(&self, index: usize) -> Option<String> {
        self.0.print_block_source(index)
    }
}

/// The Authorizer verifies a request according to its policies and the provided token
#[wasm_bindgen]
#[derive(Default)]
pub struct Authorizer {
    token: Option<biscuit::Biscuit>,
    facts: Vec<biscuit::builder::Fact>,
    rules: Vec<biscuit::builder::Rule>,
    checks: Vec<biscuit::builder::Check>,
    policies: Vec<biscuit::builder::Policy>,
}

#[wasm_bindgen]
impl Authorizer {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Authorizer {
        Authorizer::default()
    }

    pub fn add_token(&mut self, token: Biscuit) {
        self.token = Some(token.0);
    }

    /// Adds a Datalog fact
    pub fn add_fact(&mut self, fact: Fact) -> Result<(), JsValue> {
        self.facts.push(fact.0);
        Ok(())
    }

    /// Adds a Datalog rule
    pub fn add_rule(&mut self, rule: Rule) -> Result<(), JsValue> {
        self.rules.push(rule.0);
        Ok(())
    }

    /// Adds a check
    ///
    /// All checks, from authorizer and token, must be validated to authorize the request
    pub fn add_check(&mut self, check: Check) -> Result<(), JsValue> {
        self.checks.push(check.0);
        Ok(())
    }

    /// Adds a policy
    ///
    /// The authorizer will test all policies in order of addition and stop at the first one that
    /// matches. If it is a "deny" policy, the request fails, while with an "allow" policy, it will
    /// succeed
    pub fn add_policy(&mut self, policy: Policy) -> Result<(), JsValue> {
        self.policies.push(policy.0);
        Ok(())
    }

    /// Adds facts, rules, checks and policies as one code block
    pub fn add_code(&mut self, source: &str) -> Result<(), JsValue> {
        let source_result = biscuit::parser::parse_source(source).map_err(|e| {
            let e: biscuit::error::Token = e.into();
            JsValue::from_serde(&e).unwrap()
        })?;

        for (_, fact) in source_result.facts.into_iter() {
            self.facts.push(fact);
        }

        for (_, rule) in source_result.rules.into_iter() {
            self.rules.push(rule);
        }

        for (_, check) in source_result.checks.into_iter() {
            self.checks.push(check);
        }

        for (_, policy) in source_result.policies.into_iter() {
            self.policies.push(policy);
        }

        Ok(())
    }

    /// Runs the authorization checks and policies
    ///
    /// Returns the index of the matching allow policy, or an error containing the matching deny
    /// policy or a list of the failing checks
    pub fn authorize(&self) -> Result<usize, JsValue> {
        let mut authorizer = match &self.token {
            Some(token) => token
                .authorizer()
                .map_err(|e| JsValue::from_serde(&e).unwrap())?,
            None => biscuit::Authorizer::new().map_err(|e| JsValue::from_serde(&e).unwrap())?,
        };

        for fact in self.facts.iter() {
            authorizer
                .add_fact(fact.clone())
                .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        }
        for rule in self.rules.iter() {
            authorizer
                .add_rule(rule.clone())
                .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        }
        for check in self.checks.iter() {
            authorizer
                .add_check(check.clone())
                .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        }
        for policy in self.policies.iter() {
            authorizer
                .add_policy(policy.clone())
                .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        }

        Ok(authorizer
            .authorize()
            .map_err(|e| JsValue::from_serde(&e).unwrap())?)
    }
}

/// Creates a token
#[wasm_bindgen]
pub struct BiscuitBuilder {
    facts: Vec<biscuit::builder::Fact>,
    rules: Vec<biscuit::builder::Rule>,
    checks: Vec<biscuit::builder::Check>,
}

#[wasm_bindgen]
impl BiscuitBuilder {
    fn new() -> BiscuitBuilder {
        BiscuitBuilder {
            facts: Vec::new(),
            rules: Vec::new(),
            checks: Vec::new(),
        }
    }

    pub fn build(self, root: &PrivateKey) -> Result<Biscuit, JsValue> {
        let keypair = biscuit_auth::KeyPair::from(root.0.clone());
        let mut builder = biscuit_auth::Biscuit::builder(&keypair);
        for fact in self.facts.into_iter() {
            builder
                .add_authority_fact(fact)
                .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        }
        for rule in self.rules.into_iter() {
            builder
                .add_authority_rule(rule)
                .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        }
        for check in self.checks.into_iter() {
            builder
                .add_authority_check(check)
                .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        }

        Ok(Biscuit(
            builder
                .build()
                .map_err(|e| JsValue::from_serde(&e).unwrap())?,
        ))
    }

    /// Adds a Datalog fact
    pub fn add_authority_fact(&mut self, fact: Fact) -> Result<(), JsValue> {
        self.facts.push(fact.0);
        Ok(())
    }

    /// Adds a Datalog rule
    pub fn add_authority_rule(&mut self, rule: Rule) -> Result<(), JsValue> {
        self.rules.push(rule.0);
        Ok(())
    }

    /// Adds a check
    ///
    /// All checks, from authorizer and token, must be validated to authorize the request
    pub fn add_authority_check(&mut self, check: Check) -> Result<(), JsValue> {
        self.checks.push(check.0);
        Ok(())
    }
}

/// Creates a block to attenuate a token
#[wasm_bindgen]
pub struct BlockBuilder(biscuit::builder::BlockBuilder);

#[wasm_bindgen]
impl BlockBuilder {
    /// Adds a Datalog fact
    pub fn add_fact(&mut self, fact: Fact) -> Result<(), JsValue> {
        Ok(self
            .0
            .add_fact(fact.0)
            .map_err(|e| JsValue::from_serde(&e).unwrap())?)
    }

    /// Adds a Datalog rule
    pub fn add_rule(&mut self, rule: Rule) -> Result<(), JsValue> {
        Ok(self
            .0
            .add_rule(rule.0)
            .map_err(|e| JsValue::from_serde(&e).unwrap())?)
    }

    /// Adds a check
    ///
    /// All checks, from authorizer and token, must be validated to authorize the request
    pub fn add_check(&mut self, check: Check) -> Result<(), JsValue> {
        Ok(self
            .0
            .add_check(check.0)
            .map_err(|e| JsValue::from_serde(&e).unwrap())?)
    }

    /// Adds facts, rules, checks and policies as one code block
    pub fn add_code(&mut self, source: &str) -> Result<(), JsValue> {
        self.0
            .add_code(source)
            .map_err(|e| JsValue::from_serde(&e).unwrap())
    }
}

#[wasm_bindgen]
pub struct Fact(biscuit::builder::Fact);

#[wasm_bindgen]
impl Fact {
    pub fn from_str(source: &str) -> Result<Fact, JsValue> {
        source
            .try_into()
            .map(Fact)
            .map_err(|e| JsValue::from_serde(&e).unwrap())
    }

    pub fn set(&mut self, name: &str, value: JsValue) -> Result<(), JsValue> {
        let value = js_to_term(value)?;

        self.0
            .set(name, value)
            .map_err(|e| JsValue::from_serde(&e).unwrap())
    }
}

#[wasm_bindgen]
pub struct Rule(biscuit::builder::Rule);

#[wasm_bindgen]
impl Rule {
    pub fn from_str(source: &str) -> Result<Rule, JsValue> {
        source
            .try_into()
            .map(Rule)
            .map_err(|e| JsValue::from_serde(&e).unwrap())
    }

    pub fn set(&mut self, name: &str, value: JsValue) -> Result<(), JsValue> {
        let value = js_to_term(value)?;

        self.0
            .set(name, value)
            .map_err(|e| JsValue::from_serde(&e).unwrap())
    }
}

#[wasm_bindgen]
pub struct Check(biscuit::builder::Check);

#[wasm_bindgen]
impl Check {
    pub fn from_str(source: &str) -> Result<Check, JsValue> {
        source
            .try_into()
            .map(Check)
            .map_err(|e| JsValue::from_serde(&e).unwrap())
    }

    pub fn set(&mut self, name: &str, value: JsValue) -> Result<(), JsValue> {
        let value = js_to_term(value)?;

        self.0
            .set(name, value)
            .map_err(|e| JsValue::from_serde(&e).unwrap())
    }
}

#[wasm_bindgen]
pub struct Policy(biscuit::builder::Policy);

#[wasm_bindgen]
impl Policy {
    pub fn from_str(source: &str) -> Result<Policy, JsValue> {
        source
            .try_into()
            .map(Policy)
            .map_err(|e| JsValue::from_serde(&e).unwrap())
    }

    pub fn set(&mut self, name: &str, value: JsValue) -> Result<(), JsValue> {
        let value = js_to_term(value)?;

        self.0
            .set(name, value)
            .map_err(|e| JsValue::from_serde(&e).unwrap())
    }
}

fn js_to_term(value: JsValue) -> Result<biscuit::builder::Term, JsValue> {
    if let Some(b) = value.as_bool() {
        Ok(biscuit::builder::Term::Bool(b))
    } else if let Some(f) = value.as_f64() {
        Ok(biscuit::builder::Term::Integer(f as i64))
    } else if let Some(s) = value.as_string() {
        Ok(biscuit::builder::Term::Str(s))
    } else {
        Err(JsValue::from_serde("unexpected value").unwrap())
    }
}

/// A pair of public and private key
#[wasm_bindgen]
pub struct KeyPair(biscuit::KeyPair);

#[wasm_bindgen]
impl KeyPair {
    #[wasm_bindgen(constructor)]
    pub fn new() -> KeyPair {
        KeyPair(biscuit::KeyPair::new())
    }

    pub fn from(key: PrivateKey) -> Self {
        KeyPair(biscuit::KeyPair::from(key.0))
    }

    pub fn public(&self) -> PublicKey {
        PublicKey(self.0.public())
    }

    pub fn private(&self) -> PrivateKey {
        PrivateKey(self.0.private())
    }
}

/// Public key
#[wasm_bindgen]
pub struct PublicKey(biscuit::PublicKey);

#[wasm_bindgen]
impl PublicKey {
    /// Serializes a public key to raw bytes
    pub fn to_bytes(&self, out: &mut [u8]) -> Result<(), JsValue> {
        if out.len() != 32 {
            return Err(JsValue::from_serde(&biscuit::error::Token::Format(
                biscuit::error::Format::InvalidKeySize(out.len()),
            ))
            .unwrap());
        }

        out.copy_from_slice(&self.0.to_bytes());
        Ok(())
    }

    /// Serializes a public key to a hexadecimal string
    pub fn to_hex(&self) -> String {
        hex::encode(&self.0.to_bytes())
    }

    /// Deserializes a public key from raw bytes
    pub fn from_bytes(data: &[u8]) -> Result<PublicKey, JsValue> {
        let key = biscuit_auth::PublicKey::from_bytes(data)
            .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        Ok(PublicKey(key))
    }

    /// Deserializes a public key from a hexadecimal string
    pub fn from_hex(data: &str) -> Result<PublicKey, JsValue> {
        let data = hex::decode(data).map_err(|e| {
            JsValue::from_serde(&biscuit::error::Token::Format(
                biscuit::error::Format::InvalidKey(format!(
                    "could not deserialize hex encoded key: {}",
                    e
                )),
            ))
            .unwrap()
        })?;
        let key = biscuit_auth::PublicKey::from_bytes(&data)
            .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        Ok(PublicKey(key))
    }
}
#[wasm_bindgen]
pub struct PrivateKey(biscuit::PrivateKey);

#[wasm_bindgen]
impl PrivateKey {
    /// Serializes a private key to raw bytes
    pub fn to_bytes(&self, out: &mut [u8]) -> Result<(), JsValue> {
        if out.len() != 32 {
            return Err(JsValue::from_serde(&biscuit::error::Token::Format(
                biscuit::error::Format::InvalidKeySize(out.len()),
            ))
            .unwrap());
        }

        out.copy_from_slice(&self.0.to_bytes());
        Ok(())
    }

    /// Serializes a private key to a hexadecimal string
    pub fn to_hex(&self) -> String {
        hex::encode(&self.0.to_bytes())
    }

    /// Deserializes a private key from raw bytes
    pub fn from_bytes(data: &[u8]) -> Result<PrivateKey, JsValue> {
        let key = biscuit_auth::PrivateKey::from_bytes(data)
            .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        Ok(PrivateKey(key))
    }

    /// Deserializes a private key from a hexadecimal string
    pub fn from_hex(data: &str) -> Result<PrivateKey, JsValue> {
        let data = hex::decode(data).map_err(|e| {
            JsValue::from_serde(&biscuit::error::Token::Format(
                biscuit::error::Format::InvalidKey(format!(
                    "could not deserialize hex encoded key: {}",
                    e
                )),
            ))
            .unwrap()
        })?;
        let key = biscuit_auth::PrivateKey::from_bytes(&data)
            .map_err(|e| JsValue::from_serde(&e).unwrap())?;
        Ok(PrivateKey(key))
    }
}

#[wasm_bindgen]
extern "C" {
    // Use `js_namespace` here to bind `console.log(..)` instead of just
    // `log(..)`
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
}

#[wasm_bindgen(start)]
pub fn init() {
    wasm_logger::init(wasm_logger::Config::default());
    std::panic::set_hook(Box::new(console_error_panic_hook::hook));

    log("biscuit-wasm loading")
}