cortexkit-bus-client 0.1.7

Seedless ck-bus credentials and local NATS connections for Rust modules
Documentation
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
use std::{
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use async_trait::async_trait;
use base64::{engine::general_purpose::STANDARD, Engine};
use cortexkit_bus_naming::federation::{module_deliver_prefix, BoxId};
use serde::Deserialize;
use serde_json::{json, Value};
use tokio::sync::{watch, Mutex, RwLock};

use crate::{Error, Result};

pub(crate) struct SubcTransport {
    consumer: Arc<subc_client_rs::SubcConsumer>,
    module: String,
    timeout: Duration,
}

impl SubcTransport {
    pub fn new(
        consumer: Arc<subc_client_rs::SubcConsumer>,
        module: &str,
        timeout: Duration,
    ) -> Self {
        Self {
            consumer,
            module: module.into(),
            timeout,
        }
    }
}

#[async_trait]
impl CredentialTransport for SubcTransport {
    async fn call(&self, method: &str, params: Value) -> Result<Value> {
        let body = self
            .consumer
            .call(
                subc_protocol::RouteTarget::ManagementSurface {
                    module_id: "ckbus".into(),
                },
                subc_protocol::BindIdentity::new("bus-client", &self.module),
                serde_json::to_vec(&json!({"method": method, "params": params}))
                    .map_err(|_| Error::Reply("request could not be encoded"))?,
                subc_client_rs::CallOptions {
                    timeout: self.timeout,
                    ..Default::default()
                },
            )
            .await
            .map_err(|error| match error {
                subc_client_rs::CallError::Module(body) => Error::Refused(body.code),
                other => Error::Transport(other.to_string()),
            })?;
        let value: Value =
            serde_json::from_slice(&body).map_err(|_| Error::Reply("response is not JSON"))?;
        value
            .get("result")
            .filter(|value| value.is_object())
            .cloned()
            .ok_or(Error::Reply("missing result object"))
    }
}

#[async_trait]
pub(crate) trait CredentialTransport: Send + Sync {
    async fn call(&self, method: &str, params: Value) -> Result<Value>;
}

#[derive(Clone, Deserialize)]
pub(crate) struct Credential {
    pub jwt: String,
    pub exp: u64,
    pub credential_public: String,
    pub acct: String,
    pub server_url: String,
    pub inbox_prefix: String,
}

impl Credential {
    fn parse(value: Value) -> Result<Self> {
        let credential: Self =
            serde_json::from_value(value).map_err(|_| Error::Reply("missing credential fields"))?;
        let config = cortexkit_bus_nats::ConnectConfig::new(&credential.credential_public)?;
        let deliver_prefix = credential
            .inbox_prefix
            .rsplit_once('.')
            .and_then(|(_, module)| module_deliver_prefix(&box_id(&credential.acct)?, module).ok());
        if config.inbox_prefix() != credential.inbox_prefix
            && deliver_prefix.as_deref() != Some(credential.inbox_prefix.as_str())
        {
            return Err(Error::Reply(
                "credential inbox prefix does not match its key",
            ));
        }
        cortexkit_bus_naming::AccountNames::derive(&credential.acct)?;
        let port = credential
            .server_url
            .strip_prefix("nats://127.0.0.1:")
            .and_then(|port| port.parse::<u16>().ok());
        if !port.is_some_and(|port| port != 0) {
            return Err(Error::Reply("expected a plaintext loopback NATS URL"));
        }
        Ok(credential)
    }
}

pub(crate) struct CredentialManager {
    transport: Arc<dyn CredentialTransport>,
    current: RwLock<Credential>,
    // Serializing issue and renewal prevents replies for an old key from
    // replacing the current credential.
    flight: Mutex<()>,
    revisions: watch::Sender<u64>,
}

impl CredentialManager {
    pub async fn start(transport: Arc<dyn CredentialTransport>) -> Result<Arc<Self>> {
        let credential = Self::issue(&*transport).await?;
        let (revisions, _) = watch::channel(0);
        Ok(Arc::new(Self {
            transport,
            current: RwLock::new(credential),
            flight: Mutex::new(()),
            revisions,
        }))
    }

    pub async fn credential(&self) -> Credential {
        self.current.read().await.clone()
    }

    pub fn revisions(&self) -> watch::Receiver<u64> {
        self.revisions.subscribe()
    }

    async fn issue(transport: &dyn CredentialTransport) -> Result<Credential> {
        let mut backoff = Duration::from_millis(250);
        loop {
            match transport.call("ckbus.credential", json!({})).await {
                Ok(value) => return Credential::parse(value),
                Err(error) if transient(&error) => {
                    tokio::time::sleep(backoff).await;
                    backoff = (backoff * 2).min(Duration::from_secs(30));
                }
                Err(error) => return Err(error),
            }
        }
    }

    /// Every refusal names the observed key. A waiter must not replace the key
    /// that another waiter has just issued, because issuance revokes that key.
    pub async fn reissue(&self, observed_public: &str) -> Result<()> {
        let _flight = self.flight.lock().await;
        if self.current.read().await.credential_public != observed_public {
            return Ok(());
        }
        let credential = Self::issue(&*self.transport).await?;
        let mut current = self.current.write().await;
        if credential.acct != current.acct {
            return Err(Error::Reply("re-issue changed the account"));
        }
        *current = credential;
        self.revisions.send_modify(|revision| *revision += 1);
        Ok(())
    }

    pub async fn sign(&self, public: &str, nonce: Vec<u8>) -> Result<Vec<u8>> {
        if self.current.read().await.credential_public != public {
            return Err(Error::Reply("connection credential was replaced"));
        }
        match self
            .transport
            .call(
                "ckbus.nonce_sign",
                json!({
                    "credential_public": public,
                    "nonce_b64": STANDARD.encode(nonce),
                }),
            )
            .await
        {
            Ok(value) => STANDARD
                .decode(
                    value["signature_b64"]
                        .as_str()
                        .ok_or(Error::Reply("missing nonce signature"))?,
                )
                .map_err(|_| Error::Reply("invalid base64 nonce signature")),
            Err(error) if needs_reissue(&error) => {
                self.reissue(public).await?;
                // This connection still uses the old credential. Only a replacement
                // connection may authenticate with the newly issued key.
                Err(Error::Reply("connection credential was replaced"))
            }
            Err(error) => Err(error),
        }
    }

    pub async fn renew(&self) -> Result<()> {
        let observed = self.credential().await;
        let _flight = self.flight.lock().await;
        if self.current.read().await.credential_public != observed.credential_public {
            return Ok(());
        }
        let value = self
            .transport
            .call(
                "ckbus.credential_renew",
                json!({
                    "credential_public": observed.credential_public,
                }),
            )
            .await;
        match value {
            Ok(value) => {
                #[derive(Deserialize)]
                struct Renewal {
                    jwt: String,
                    exp: u64,
                    credential_public: String,
                    inbox_prefix: Option<String>,
                }
                let renewal: Renewal = serde_json::from_value(value)
                    .map_err(|_| Error::Reply("missing renewal fields"))?;
                if renewal.credential_public != observed.credential_public {
                    return Err(Error::Reply("renewal changed the credential key"));
                }
                if renewal
                    .inbox_prefix
                    .is_some_and(|prefix| prefix != observed.inbox_prefix)
                {
                    return Err(Error::Reply("renewal changed the inbox prefix"));
                }
                let mut current = self.current.write().await;
                current.jwt = renewal.jwt;
                current.exp = renewal.exp;
                Ok(())
            }
            Err(error) if needs_reissue(&error) => {
                drop(_flight);
                self.reissue(&observed.credential_public).await
            }
            Err(error) => Err(error),
        }
    }
}

pub(crate) fn box_id(acct: &str) -> Option<BoxId> {
    BoxId::parse(acct.strip_prefix("box_")?).ok()
}

fn needs_reissue(error: &Error) -> bool {
    matches!(error, Error::Refused(code) if matches!(code.as_str(),
        "ckbus_credential_superseded" | "ckbus_credential_revoked"))
}

pub(crate) fn transient(error: &Error) -> bool {
    matches!(error, Error::Refused(code) if matches!(code.as_str(),
        "ckbus_census_unavailable" | "ckbus_not_ready" |
        "ckbus_spawn_snapshot_unavailable" | "ckbus_signing_failed"))
}

pub(crate) fn renewal_delay(exp: u64) -> Duration {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    // Renew about ten minutes into a fifteen-minute lease. Process id supplies
    // a stable, small jitter.
    let jitter = u64::from(std::process::id() % 7);
    Duration::from_secs(exp.saturating_sub(300 + jitter)).saturating_sub(now)
}

#[cfg(test)]
mod tests {
    use super::*;

    const BOX: &str = "0123456789abcdef0123456789abcdef";
    const DELIVER: &str = "ckdel.0123456789abcdef0123456789abcdef.example-module_2";

    fn reply(prefix: &str, acct: &str) -> Value {
        json!({"jwt":"jwt", "exp":1234, "credential_public":"UKEY0",
            "acct":acct, "server_url":"nats://127.0.0.1:4222", "inbox_prefix":prefix})
    }

    #[test]
    fn inbox_prefix_accepts_credential_and_box_module_forms() {
        for prefix in ["_INBOX.UKEY0", DELIVER] {
            let credential = Credential::parse(reply(prefix, &format!("box_{BOX}"))).unwrap();
            assert_eq!(credential.inbox_prefix, prefix);
            assert_eq!(box_id(&credential.acct).unwrap().as_str(), BOX);
        }
        for acct in ["box_test", "another_account"] {
            let credential = Credential::parse(reply("_INBOX.UKEY0", acct)).unwrap();
            assert_eq!(box_id(&credential.acct), None);
        }
    }

    #[test]
    fn inbox_prefix_refuses_unrelated_or_malformed_deliver_subjects() {
        for prefix in [
            "_INBOX.UKEY1",
            "ckdel.fedcba9876543210fedcba9876543210.example-module_2",
            "ckdel.0123456789abcdef0123456789abcdef.*",
            "ckdel.0123456789abcdef0123456789abcdef.>",
            "ckdel.0123456789abcdef0123456789abcdef.example.module",
            "ckdel.0123456789abcdef0123456789abcdef.",
            "ckdel.0123456789abcdef0123456789abcdef",
            "ckdel.0123456789abcdef0123456789abcdef.Example",
            "ckdel.0123456789abcdef0123456789abcdef.module name",
        ] {
            assert!(
                matches!(
                    Credential::parse(reply(prefix, &format!("box_{BOX}"))),
                    Err(Error::Reply(
                        "credential inbox prefix does not match its key"
                    ))
                ),
                "{prefix}"
            );
        }
        for acct in [
            "box_test",
            "another_account",
            "box_0123456789ABCDEF0123456789ABCDEF",
        ] {
            assert!(
                matches!(
                    Credential::parse(reply(DELIVER, acct)),
                    Err(Error::Reply(
                        "credential inbox prefix does not match its key"
                    ))
                ),
                "{acct}"
            );
        }
    }

    struct PrefixTransport {
        initial: &'static str,
        renewed: Option<&'static str>,
    }

    #[async_trait]
    impl CredentialTransport for PrefixTransport {
        async fn call(&self, method: &str, _: Value) -> Result<Value> {
            match method {
                "ckbus.credential" => Ok(reply(self.initial, &format!("box_{BOX}"))),
                "ckbus.credential_renew" => {
                    let mut value =
                        json!({"jwt":"renewed", "exp":5678, "credential_public":"UKEY0"});
                    if let Some(prefix) = self.renewed {
                        value["inbox_prefix"] = prefix.into();
                    }
                    Ok(value)
                }
                _ => panic!("unexpected method {method}"),
            }
        }
    }

    #[tokio::test]
    async fn inbox_prefix_renewal_accepts_omitted_or_unchanged_prefix() {
        for initial in ["_INBOX.UKEY0", DELIVER] {
            for renewed in [None, Some(initial)] {
                let manager =
                    CredentialManager::start(Arc::new(PrefixTransport { initial, renewed }))
                        .await
                        .unwrap();
                let revisions = manager.revisions();
                manager.renew().await.unwrap();
                let credential = manager.credential().await;
                assert_eq!(credential.jwt, "renewed");
                assert_eq!(credential.inbox_prefix, initial);
                assert!(!revisions.has_changed().unwrap());
            }
        }
    }

    #[tokio::test]
    async fn inbox_prefix_renewal_refuses_changed_form_or_module() {
        for (initial, renewed) in [
            ("_INBOX.UKEY0", DELIVER),
            (DELIVER, "_INBOX.UKEY0"),
            (
                DELIVER,
                "ckdel.0123456789abcdef0123456789abcdef.other-module",
            ),
        ] {
            let manager = CredentialManager::start(Arc::new(PrefixTransport {
                initial,
                renewed: Some(renewed),
            }))
            .await
            .unwrap();
            assert!(matches!(
                manager.renew().await,
                Err(Error::Reply("renewal changed the inbox prefix"))
            ));
            let credential = manager.credential().await;
            assert_eq!(credential.jwt, "jwt");
            assert_eq!(credential.inbox_prefix, initial);
        }
    }
}