noosphere-ns 0.3.1

A P2P name system for Noosphere
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
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
use crate::utils::generate_capability;
use anyhow::{anyhow, Error};
use cid::Cid;
use noosphere_core::authority::SPHERE_SEMANTICS;
use noosphere_storage::{SphereDb, Storage};
use serde_json::Value;
use std::{convert::TryFrom, str, str::FromStr};
use ucan::{chain::ProofChain, crypto::did::DidParser, Ucan};

/// An [NSRecord] is the internal representation of a mapping from a
/// sphere's identity (DID key) to a sphere's revision as a
/// content address ([Cid]). The record wraps a [Ucan] token,
/// providing de/serialization for transmitting in the NS network,
/// and validates data ensuring the sphere's owner authorized the publishing
/// of a new content address.
///
/// When transmitting through the distributed NS network, the record is
/// represented as the base64 encoded UCAN token.
///
/// # Ucan Semantics
///
/// An [NSRecord] is a small interface over a [Ucan] token,
/// with the following semantics:
///
/// ```json
/// {
///   // The identity (DID) of the Principal that signed the token
///   "iss": "did:key:z6MkoE19WHXJzpLqkxbGP7uXdJX38sWZNUWwyjcuCmjhPpUP",
///   // The identity (DID) of the sphere this record maps.
///   "aud": "did:key:z6MkkVfktAC5rVNRmmTjkKPapT3bAyVkYH8ZVCF1UBNUfazp",
///   // Attenuation must contain a capability with a resource "sphere:{AUD}"
///   // and action "sphere/publish".
///   "att": [{
///     "with": "sphere:did:key:z6MkkVfktAC5rVNRmmTjkKPapT3bAyVkYH8ZVCF1UBNUfazp",
///     "can": "sphere/publish"
///   }],
///   // Additional UCAN proofs needed to validate.
///   "prf": [],
///   // Facts contain a single entry with an "address" field containing
///   // the content address of a sphere revision (CID) associated with
///   // the sphere this record maps to.
///   "fct": [{
///     "address": "bafy2bzacec4p5h37mjk2n6qi6zukwyzkruebvwdzqpdxzutu4sgoiuhqwne72"
///   }]
/// }
/// ```
#[derive(Debug, Clone)]
pub struct NSRecord {
    /// The wrapped UCAN token describing this record.
    pub(crate) token: Ucan,
    /// The resolved sphere revision this record maps to.
    pub(crate) address: Option<Cid>,
}

impl NSRecord {
    /// Creates a new [NSRecord].
    pub fn new(token: Ucan) -> Self {
        // Cache the revision address if "fct" contains an entry matching
        // the following object without any authority validation:
        // `{ "address": "{VALID_CID}" }`
        let mut address = None;
        for ref fact in token.facts() {
            if let Value::Object(map) = fact {
                if let Some(Value::String(addr)) = map.get(&String::from("address")) {
                    if let Ok(cid) = Cid::from_str(addr) {
                        address = Some(cid);
                        break;
                    }
                }
            }
        }

        Self { token, address }
    }

    /// Validates the underlying [Ucan] token, ensuring that
    /// the sphere's owner authorized the publishing of a new
    /// content address. Returns an `Err` if validation fails.
    pub async fn validate<S: Storage>(
        &self,
        store: &SphereDb<S>,
        did_parser: &mut DidParser,
    ) -> Result<(), Error> {
        if self.is_expired() {
            return Err(anyhow!("Token is expired."));
        }

        let identity = self.identity();

        let desired_capability = generate_capability(identity);
        let proof = ProofChain::from_ucan(self.token.clone(), did_parser, store).await?;

        let mut has_capability = false;
        for capability_info in proof.reduce_capabilities(&SPHERE_SEMANTICS) {
            let capability = capability_info.capability;
            if capability_info.originators.contains(identity)
                && capability.enables(&desired_capability)
            {
                has_capability = true;
                break;
            }
        }

        if !has_capability {
            return Err(anyhow!("Token is not authorized to publish this sphere."));
        }

        if self.address.is_none() {
            return Err(anyhow!(
                "Missing a valid fact entry with record sphere revision. {} {:?}",
                identity,
                self.token.facts()
            ));
        }

        self.token.check_signature(did_parser).await?;
        Ok(())
    }

    /// The DID key of the sphere that this record maps.
    pub fn identity(&self) -> &str {
        self.token.audience()
    }

    /// The sphere revision ([Cid]) that the sphere's identity maps to.
    pub fn address(&self) -> Option<&Cid> {
        self.address.as_ref()
    }

    /// Returns true if the [Ucan] token is past its expiration.
    pub fn is_expired(&self) -> bool {
        self.token.is_expired()
    }
}

/// Create a new [NSRecord] taking a [Ucan] token.
impl From<Ucan> for NSRecord {
    fn from(ucan: Ucan) -> Self {
        Self::new(ucan)
    }
}

/// Deserialize an encoded UCAN token byte vec into a [NSRecord].
impl TryFrom<Vec<u8>> for NSRecord {
    type Error = anyhow::Error;

    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
        NSRecord::try_from(&bytes[..])
    }
}

/// Serialize a [NSRecord] into an encoded UCAN token byte vec.
impl TryFrom<NSRecord> for Vec<u8> {
    type Error = anyhow::Error;

    fn try_from(record: NSRecord) -> Result<Self, Self::Error> {
        Vec::try_from(&record)
    }
}

/// Serialize a [NSRecord] reference into an encoded UCAN token byte vec.
impl TryFrom<&NSRecord> for Vec<u8> {
    type Error = anyhow::Error;

    fn try_from(record: &NSRecord) -> Result<Vec<u8>, Self::Error> {
        Ok(Vec::from(record.token.encode()?))
    }
}

/// Deserialize an encoded UCAN token byte vec reference into a [NSRecord].
impl TryFrom<&[u8]> for NSRecord {
    type Error = anyhow::Error;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        NSRecord::try_from(str::from_utf8(bytes)?)
    }
}

/// Deserialize an encoded UCAN token string reference into a [NSRecord].
impl<'a> TryFrom<&'a str> for NSRecord {
    type Error = anyhow::Error;

    fn try_from(ucan_token: &str) -> Result<Self, Self::Error> {
        NSRecord::from_str(ucan_token)
    }
}

/// Deserialize an encoded UCAN token string into a [NSRecord].
impl TryFrom<String> for NSRecord {
    type Error = anyhow::Error;

    fn try_from(ucan_token: String) -> Result<Self, Self::Error> {
        NSRecord::from_str(ucan_token.as_str())
    }
}

/// Deserialize an encoded UCAN token string reference into a [NSRecord].
impl FromStr for NSRecord {
    type Err = anyhow::Error;

    fn from_str(ucan_token: &str) -> Result<Self, Self::Err> {
        // Wait for next release of `ucan` which includes traits and
        // removes `try_from_token_string`:
        // https://github.com/ucan-wg/rs-ucan/commit/75e9afdb9da60c3d5d8c65b6704e412f0ef8189b
        Ok(NSRecord::new(Ucan::from_str(ucan_token)?))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use noosphere_core::authority::{generate_ed25519_key, SUPPORTED_KEYS};
    use noosphere_storage::{MemoryStorage, SphereDb};
    use serde_json::json;
    use std::str::FromStr;

    use ucan::{
        builder::UcanBuilder, crypto::did::DidParser, crypto::KeyMaterial, store::UcanJwtStore,
    };

    async fn expect_failure(
        message: &str,
        store: &SphereDb<MemoryStorage>,
        did_parser: &mut DidParser,
        ucan: Ucan,
    ) {
        assert!(
            NSRecord::new(ucan)
                .validate(store, did_parser)
                .await
                .is_err(),
            "{}",
            message
        );
    }

    #[tokio::test]
    async fn test_nsrecord_self_signed() -> Result<(), Error> {
        let sphere_key = generate_ed25519_key();
        let sphere_identity = sphere_key.get_did().await?;
        let mut did_parser = DidParser::new(SUPPORTED_KEYS);
        let capability = generate_capability(&sphere_identity);
        let cid_address = "bafy2bzacec4p5h37mjk2n6qi6zukwyzkruebvwdzqpdxzutu4sgoiuhqwne72";
        let fact = json!({ "address": cid_address });
        let store = SphereDb::new(&MemoryStorage::default()).await.unwrap();

        let record = NSRecord::new(
            UcanBuilder::default()
                .issued_by(&sphere_key)
                .for_audience(&sphere_identity)
                .with_lifetime(1000)
                .claiming_capability(&capability)
                .with_fact(fact)
                .build()?
                .sign()
                .await?,
        );

        assert_eq!(record.identity(), &sphere_identity);
        assert_eq!(record.address(), Some(&Cid::from_str(cid_address).unwrap()));
        record.validate(&store, &mut did_parser).await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_nsrecord_delegated() -> Result<(), Error> {
        let owner_key = generate_ed25519_key();
        let owner_identity = owner_key.get_did().await?;
        let sphere_key = generate_ed25519_key();
        let sphere_identity = sphere_key.get_did().await?;
        let mut did_parser = DidParser::new(SUPPORTED_KEYS);
        let capability = generate_capability(&sphere_identity);
        let cid_address = "bafy2bzacec4p5h37mjk2n6qi6zukwyzkruebvwdzqpdxzutu4sgoiuhqwne72";
        let fact = json!({ "address": cid_address });
        let mut store = SphereDb::new(&MemoryStorage::default()).await.unwrap();

        // First verify that `owner` cannot publish for `sphere`
        // without delegation.
        let record = NSRecord::new(
            UcanBuilder::default()
                .issued_by(&owner_key)
                .for_audience(&sphere_identity)
                .with_lifetime(1000)
                .claiming_capability(&capability)
                .with_fact(fact.clone())
                .build()?
                .sign()
                .await?,
        );

        assert_eq!(record.identity(), &sphere_identity);
        assert_eq!(record.address(), Some(&Cid::from_str(cid_address).unwrap()));
        if record.validate(&store, &mut did_parser).await.is_ok() {
            panic!("Owner should not have authorization to publish record")
        }

        // Delegate `sphere_key`'s publishing authority to `owner_key`
        let delegate_capability = generate_capability(&sphere_identity);
        let delegate_ucan = UcanBuilder::default()
            .issued_by(&sphere_key)
            .for_audience(&owner_identity)
            .with_lifetime(1000)
            .claiming_capability(&delegate_capability)
            .build()?
            .sign()
            .await?;
        let _ = store.write_token(&delegate_ucan.encode()?).await?;

        // Attempt `owner` publishing `sphere` with the proper authorization
        let record = NSRecord::new(
            UcanBuilder::default()
                .issued_by(&owner_key)
                .for_audience(&sphere_identity)
                .with_lifetime(1000)
                .claiming_capability(&capability)
                .witnessed_by(&delegate_ucan)
                .with_fact(fact.clone())
                .build()?
                .sign()
                .await?,
        );
        assert_eq!(record.identity(), &sphere_identity);
        assert_eq!(record.address(), Some(&Cid::from_str(cid_address).unwrap()));
        record.validate(&store, &mut did_parser).await?;

        Ok(())
    }

    #[tokio::test]
    async fn test_nsrecord_failures() -> Result<(), Error> {
        let sphere_key = generate_ed25519_key();
        let sphere_identity = sphere_key.get_did().await?;
        let mut did_parser = DidParser::new(SUPPORTED_KEYS);
        let cid_address = "bafy2bzacec4p5h37mjk2n6qi6zukwyzkruebvwdzqpdxzutu4sgoiuhqwne72";
        let store = SphereDb::new(&MemoryStorage::default()).await.unwrap();

        let sphere_capability = generate_capability(&sphere_identity);
        expect_failure(
            "fails when expect `fact` is missing",
            &store,
            &mut did_parser,
            UcanBuilder::default()
                .issued_by(&sphere_key)
                .for_audience(&sphere_identity)
                .with_lifetime(1000)
                .claiming_capability(&sphere_capability)
                .with_fact(json!({ "invalid_fact": cid_address }))
                .build()?
                .sign()
                .await?,
        )
        .await;

        let capability = generate_capability(&generate_ed25519_key().get_did().await?);
        expect_failure(
            "fails when capability resource does not match sphere identity",
            &store,
            &mut did_parser,
            UcanBuilder::default()
                .issued_by(&sphere_key)
                .for_audience(&sphere_identity)
                .with_lifetime(1000)
                .claiming_capability(&capability)
                .with_fact(json!({ "address": cid_address }))
                .build()?
                .sign()
                .await?,
        )
        .await;

        let non_auth_key = generate_ed25519_key();
        expect_failure(
            "fails when a non-authorized key signs the record",
            &store,
            &mut did_parser,
            UcanBuilder::default()
                .issued_by(&non_auth_key)
                .for_audience(&sphere_identity)
                .with_lifetime(1000)
                .claiming_capability(&sphere_capability)
                .with_fact(json!({ "address": cid_address }))
                .build()?
                .sign()
                .await?,
        )
        .await;

        Ok(())
    }

    #[tokio::test]
    async fn test_nsrecord_convert() -> Result<(), Error> {
        let sphere_key = generate_ed25519_key();
        let sphere_identity = sphere_key.get_did().await?;
        let capability = generate_capability(&sphere_identity);
        let cid_address = "bafy2bzacec4p5h37mjk2n6qi6zukwyzkruebvwdzqpdxzutu4sgoiuhqwne72";
        let fact = json!({ "address": cid_address });

        let ucan = UcanBuilder::default()
            .issued_by(&sphere_key)
            .for_audience(&sphere_identity)
            .with_lifetime(1000)
            .claiming_capability(&capability)
            .with_fact(fact)
            .build()?
            .sign()
            .await?;

        let base = NSRecord::new(ucan.clone());
        let encoded = ucan.encode()?;
        let bytes = Vec::from(encoded.clone());

        // NSRecord::try_from::<Vec<u8>>()
        let record = NSRecord::try_from(bytes.clone())?;
        assert_eq!(base.identity(), record.identity(), "try_from::<Vec<u8>>()");
        assert_eq!(base.address(), record.address(), "try_from::<Vec<u8>>()");

        // NSRecord::try_into::<Vec<u8>>()
        let rec_bytes: Vec<u8> = base.clone().try_into()?;
        assert_eq!(bytes, rec_bytes, "try_into::<Vec<u8>>()");

        // NSRecord::try_from::<&[u8]>()
        let record = NSRecord::try_from(&bytes[..])?;
        assert_eq!(base.identity(), record.identity(), "try_from::<&[u8]>()");
        assert_eq!(base.address(), record.address(), "try_from::<&[u8]>()");

        // &NSRecord::try_into::<Vec<u8>>()
        let rec_bytes: Vec<u8> = (&base).try_into()?;
        assert_eq!(bytes, rec_bytes, "&NSRecord::try_into::<Vec<u8>>()");

        // NSRecord::from::<Ucan>()
        let record = NSRecord::from(ucan);
        assert_eq!(base.identity(), record.identity(), "from::<Ucan>()");
        assert_eq!(base.address(), record.address(), "from::<Ucan>()");

        // NSRecord::try_from::<&str>()
        let record = NSRecord::try_from(encoded.as_str())?;
        assert_eq!(base.identity(), record.identity(), "try_from::<&str>()");
        assert_eq!(base.address(), record.address(), "try_from::<&str>()");

        // NSRecord::try_from::<String>()
        let record = NSRecord::try_from(encoded.clone())?;
        assert_eq!(base.identity(), record.identity(), "try_from::<String>()");
        assert_eq!(base.address(), record.address(), "try_from::<String>()");

        // NSRecord::from_str()
        let record = NSRecord::from_str(encoded.as_str())?;
        assert_eq!(base.identity(), record.identity(), "from_str()");
        assert_eq!(base.address(), record.address(), "from_str()");

        Ok(())
    }
}