wascap/
lib.rs

1//! A library for managing signed JWT (JSON Web Tokens) in WebAssembly modules. These
2//! are designed to be used with the [wasmCloud](https://github.com/wasmCloud) host, but can be
3//! used for any WebAssembly module, as the embedding technique used is compliant with
4//! the WebAssembly standard.
5//!
6//! This library can be used for embedding, extracting, and validating capabilities claims
7//! in WebAssembly modules. While there are some standard, well-known claims already defined
8//! for use with *wasmCloud*, you can add custom claims in your own namespaces if you like.
9//!
10//! The following example illustrates embedding a new set of claims
11//! into a WebAssembly module, then extracting, validating, and examining those claims.
12//! ```rust
13//!use wascap::prelude::*;
14//!
15//!# fn read_unsigned_wasm() -> Vec<u8> {
16//!#   include_bytes!("../examples/loop.wasm").to_vec()
17//!# }
18//!# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
19//! let unsigned = read_unsigned_wasm(); // Read a Wasm file into a byte vector
20//! let issuer = KeyPair::new_account(); // Create an Ed25519 key pair to sign the module
21//! let module = KeyPair::new_module(); // Create a key pair for the module itself
22//!
23//! // Set the name on the component
24//! let claims = ClaimsBuilder::<Component>::new()
25//!     .issuer(&issuer.public_key())
26//!     .subject(&module.public_key())
27//!     .with_metadata(Component{
28//!         name: Some("test".to_string()),
29//!         .. Default::default()
30//!      })
31//!     .build();
32//!
33//! // Sign the JWT and embed it into the WebAssembly module, returning the signed bytes
34//! let embedded = wasm::embed_claims(&unsigned, &claims, &issuer)?;
35//!
36//! // Extract a signed JWT from a WebAssembly module's bytes (performs a check on
37//! // the signed module hash)
38//! let extracted = wasm::extract_claims(&embedded)?.unwrap();
39//!
40//! // Validate dates, signature, JWT structure, etc.
41//! let v = validate_token::<Component>(&extracted.jwt)?;
42//!
43//! assert_eq!(v.expired, false);
44//! assert_eq!(v.cannot_use_yet, false);
45//! assert_eq!(v.expires_human, "never");
46//! assert_eq!(v.not_before_human, "immediately");
47//! assert_eq!(extracted.claims.issuer, issuer.public_key());
48//!
49//!# Ok(())
50//!# }
51//! ```
52//!
53//! The `Ed25519` key functionality is provided by the [nkeys](https://docs.rs/nkeys) crate.
54
55/// Wascap-specific result type
56pub type Result<T> = std::result::Result<T, errors::Error>;
57pub use errors::Error;
58
59mod errors;
60pub mod jwt;
61pub mod wasm;
62
63pub mod prelude {
64    //! Public re-exports of the most commonly used wascap types
65    pub use super::{Error as WascapError, Result as WascapResult};
66    pub use crate::{
67        jwt::{validate_token, Account, Claims, ClaimsBuilder, Component, Invocation, Operator},
68        wasm,
69    };
70    pub use nkeys::KeyPair;
71}