Skip to main content

cortexkit_bus_testkit/
trust.rs

1//! Throwaway operator, system-account and account signing keys.
2
3use crate::signer::HarnessSigner;
4use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
5use nkeys::KeyPair;
6use serde_json::{json, Value};
7use sha2::{Digest, Sha256};
8use std::time::{SystemTime, UNIX_EPOCH};
9
10pub fn unix_now() -> i64 {
11    SystemTime::now()
12        .duration_since(UNIX_EPOCH)
13        .expect("clock after epoch")
14        .as_secs() as i64
15}
16
17/// The credential id the operator minted `signing:<provider>:1` under.
18pub fn root_id(provider: &str) -> String {
19    format!("signing:{provider}:1")
20}
21
22pub fn box_root_id() -> String {
23    root_id("ck-bus-account")
24}
25
26pub fn system_root_id() -> String {
27    root_id("ck-bus-sysaccount")
28}
29
30pub fn signer_root_id() -> String {
31    root_id("ck-bus-operator-signer")
32}
33
34pub(crate) fn encode_jwt(
35    signer: &KeyPair,
36    subject: &str,
37    name: &str,
38    iat: i64,
39    nats: Value,
40) -> String {
41    encode_jwt_with_expiration(signer, subject, name, iat, nats, None)
42}
43
44fn encode_jwt_with_expiration(
45    signer: &KeyPair,
46    subject: &str,
47    name: &str,
48    iat: i64,
49    nats: Value,
50    expires_at: Option<i64>,
51) -> String {
52    let mut claims = json!({
53        "jti": "",
54        "iat": iat,
55        "iss": signer.public_key(),
56        "name": name,
57        "sub": subject,
58        "nats": nats,
59    });
60    if let Some(exp) = expires_at {
61        claims["exp"] = json!(exp);
62    }
63    let digest = Sha256::digest(claims.to_string().as_bytes());
64    claims["jti"] = Value::String(super::signer::hex(&digest).to_uppercase());
65    let input = format!(
66        "{}.{}",
67        URL_SAFE_NO_PAD.encode(br#"{"alg":"ed25519-nkey","typ":"JWT"}"#),
68        URL_SAFE_NO_PAD.encode(claims.to_string().as_bytes())
69    );
70    let signature = signer
71        .sign(input.as_bytes())
72        .expect("fixture keys hold seeds");
73    format!("{input}.{}", URL_SAFE_NO_PAD.encode(signature))
74}
75
76/// A decoded JWT's claims.
77pub fn claims(jwt: &str) -> Value {
78    let part = jwt.trim().split('.').nth(1).expect("a JWT has claims");
79    serde_json::from_slice(&URL_SAFE_NO_PAD.decode(part).expect("claims are base64url"))
80        .expect("claims are JSON")
81}
82
83/// The fixture trust chain.
84#[derive(Clone)]
85pub struct TrustChain {
86    pub signer: HarnessSigner,
87    pub(crate) operator_root: KeyPair,
88    /// The system account's public nkey. Its private identity key is discarded;
89    /// user JWTs are signed with a separate throwaway signing key.
90    pub system_account: String,
91}
92
93impl TrustChain {
94    pub fn generate() -> Self {
95        let signer = HarnessSigner::from_pairs([
96            (signer_root_id(), KeyPair::new_operator()),
97            (system_root_id(), KeyPair::new_account()),
98            (box_root_id(), KeyPair::new_account()),
99        ]);
100        Self {
101            signer,
102            operator_root: KeyPair::new_operator(),
103            system_account: KeyPair::new_account().public_key(),
104        }
105    }
106
107    /// The operator signer as the operator JWT lists it (`O...`).
108    pub fn signer_public(&self) -> String {
109        self.signer.root(&signer_root_id()).account_public()
110    }
111
112    /// The public nkey (`A...`) trusted to sign users of the box account.
113    /// The box account JWT lists this key in `signing_keys`.
114    pub fn box_root_public(&self) -> String {
115        self.signer.root(&box_root_id()).account_public()
116    }
117
118    pub fn operator_jwt(&self) -> String {
119        encode_jwt(
120            &self.operator_root,
121            &self.operator_root.public_key(),
122            "ckbus-harness-operator",
123            unix_now() - 120,
124            json!({
125                "type": "operator",
126                "version": 2,
127                "system_account": self.system_account,
128                "signing_keys": [self.signer_public()],
129                "strict_signing_key_usage": false,
130            }),
131        )
132    }
133
134    pub fn system_account_jwt(&self) -> String {
135        encode_jwt(
136            &self.operator_root,
137            &self.system_account,
138            "SYS",
139            unix_now() - 120,
140            json!({
141                "type": "account",
142                "version": 2,
143                "limits": {
144                    "subs": -1, "data": -1, "payload": -1, "imports": -1, "exports": -1,
145                    "wildcards": true, "conn": -1, "leaf": -1,
146                },
147                "signing_keys": [self.signer.root(&system_root_id()).account_public()],
148                "default_permissions": {"pub": {}, "sub": {}},
149            }),
150        )
151    }
152
153    /// A harness user in `account_public`, signed by the root the account lists, with no
154    /// permission restriction.
155    pub fn user_jwt(
156        &self,
157        root_id: &str,
158        account_public: &str,
159        user: &KeyPair,
160        iat: i64,
161    ) -> String {
162        self.user_jwt_for_subject(root_id, account_public, &user.public_key(), iat)
163    }
164
165    /// `user_jwt` for a user key given by its public half only.
166    pub fn user_jwt_for_subject(
167        &self,
168        root_id: &str,
169        account_public: &str,
170        subject: &str,
171        iat: i64,
172    ) -> String {
173        self.sign_user_jwt(root_id, account_public, subject, iat, None)
174    }
175
176    /// Issues a fixture user JWT with `exp` set to `expires_at` (Unix seconds).
177    /// The same user key can sign nonces for a later JWT.
178    pub fn expiring_user_jwt(
179        &self,
180        root_id: &str,
181        account_public: &str,
182        user: &KeyPair,
183        expires_at: i64,
184    ) -> String {
185        self.sign_user_jwt(
186            root_id,
187            account_public,
188            &user.public_key(),
189            unix_now(),
190            Some(expires_at),
191        )
192    }
193
194    fn sign_user_jwt(
195        &self,
196        root_id: &str,
197        account_public: &str,
198        subject: &str,
199        iat: i64,
200        expires_at: Option<i64>,
201    ) -> String {
202        encode_jwt_with_expiration(
203            &self.signer.root(root_id).pair,
204            subject,
205            "harness-user",
206            iat,
207            json!({
208                "type": "user", "version": 2, "issuer_account": account_public,
209                "pub": {}, "sub": {}, "subs": -1, "data": -1, "payload": -1,
210            }),
211            expires_at,
212        )
213    }
214}