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
use cid::Cid;
use serde::{Deserialize, Serialize};

use super::Did;

/// The root of the sphere, containing pointers to public details such as names
/// and links, as well as "sealed" (private) data. While public details are accessible
/// to all, sealed data is encrypted at rest and only accessible to the user who
/// owns the sphere.
#[derive(Default, Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct SphereIpld {
    /// A DID that is the identity of the originating key that owns the sphere
    pub identity: Did,

    /// The public links for the sphere
    pub links: Option<Cid>,

    /// The public pet names for the sphere
    pub names: Option<Cid>,

    /// The non-public content of the sphere
    pub sealed: Option<Cid>,

    /// Authorization and revocation state for non-owner keys
    pub authorization: Option<Cid>,
}

impl SphereIpld {}

#[cfg(test)]
mod tests {
    use ed25519_zebra::{SigningKey as Ed25519PrivateKey, VerificationKey as Ed25519PublicKey};
    use libipld_cbor::DagCborCodec;
    use ucan::{
        builder::UcanBuilder,
        capability::{Capability, Resource, With},
        crypto::{did::DidParser, KeyMaterial},
        store::UcanJwtStore,
    };
    use ucan_key_support::ed25519::Ed25519KeyMaterial;
    #[cfg(target_arch = "wasm32")]
    use wasm_bindgen_test::wasm_bindgen_test;

    use crate::{
        authority::{
            verify_sphere_cid, Authorization, SphereAction, SphereReference, SUPPORTED_KEYS,
        },
        data::{ContentType, Did, Header, MemoIpld, SphereIpld},
    };

    use noosphere_storage::{BlockStore, MemoryStorage, SphereDb};

    fn generate_credential() -> Ed25519KeyMaterial {
        let private_key = Ed25519PrivateKey::new(rand::thread_rng());
        let public_key = Ed25519PublicKey::from(&private_key);
        Ed25519KeyMaterial(public_key, Some(private_key))
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
    async fn it_can_be_signed_by_identity_key_and_verified() {
        let identity_credential = generate_credential();
        let identity_did = Did(identity_credential.get_did().await.unwrap());

        let mut store = SphereDb::new(&MemoryStorage::default()).await.unwrap();

        let sphere = SphereIpld {
            identity: identity_did.clone(),
            links: None,
            names: None,
            sealed: None,
            authorization: None,
        };

        let sphere_cid = store.save::<DagCborCodec, _>(&sphere).await.unwrap();

        let mut memo = MemoIpld {
            parent: None,
            headers: vec![(
                Header::ContentType.to_string(),
                ContentType::Sphere.to_string(),
            )],
            body: sphere_cid,
        };

        let capability: Capability<SphereReference, SphereAction> = Capability {
            with: With::Resource {
                kind: Resource::Scoped(SphereReference {
                    did: identity_did.to_string(),
                }),
            },
            can: SphereAction::Authorize,
        };

        let authorization = Authorization::Ucan(
            UcanBuilder::default()
                .issued_by(&identity_credential)
                .for_audience(&identity_did)
                .with_lifetime(100)
                .claiming_capability(&capability)
                .build()
                .unwrap()
                .sign()
                .await
                .unwrap(),
        );

        memo.sign(&identity_credential, Some(&authorization))
            .await
            .unwrap();

        store
            .write_token(
                &authorization
                    .resolve_ucan(&store)
                    .await
                    .unwrap()
                    .encode()
                    .unwrap(),
            )
            .await
            .unwrap();

        let memo_cid = store.save::<DagCborCodec, _>(&memo).await.unwrap();

        let mut did_parser = DidParser::new(SUPPORTED_KEYS);

        verify_sphere_cid(&memo_cid, &store, &mut did_parser)
            .await
            .unwrap();
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
    #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
    async fn it_can_be_signed_by_an_authorized_key_and_verified() {
        let identity_credential = generate_credential();
        let authorized_credential = generate_credential();

        let identity_did = Did(identity_credential.get_did().await.unwrap());
        let authorized_did = Did(authorized_credential.get_did().await.unwrap());

        let mut store = SphereDb::new(&MemoryStorage::default()).await.unwrap();

        let sphere = SphereIpld {
            identity: identity_did.clone(),
            links: None,
            names: None,
            sealed: None,
            authorization: None,
        };

        let sphere_cid = store.save::<DagCborCodec, _>(&sphere).await.unwrap();

        let mut memo = MemoIpld {
            parent: None,
            headers: vec![(
                Header::ContentType.to_string(),
                ContentType::Sphere.to_string(),
            )],
            body: sphere_cid,
        };

        let capability: Capability<SphereReference, SphereAction> = Capability {
            with: With::Resource {
                kind: Resource::Scoped(SphereReference {
                    did: identity_did.to_string(),
                }),
            },
            can: SphereAction::Authorize,
        };

        let authorization = Authorization::Ucan(
            UcanBuilder::default()
                .issued_by(&identity_credential)
                .for_audience(&authorized_did)
                .with_lifetime(100)
                .claiming_capability(&capability)
                .build()
                .unwrap()
                .sign()
                .await
                .unwrap(),
        );

        memo.sign(&authorized_credential, Some(&authorization))
            .await
            .unwrap();

        store
            .write_token(
                &authorization
                    .resolve_ucan(&store)
                    .await
                    .unwrap()
                    .encode()
                    .unwrap(),
            )
            .await
            .unwrap();

        let memo_cid = store.save::<DagCborCodec, _>(&memo).await.unwrap();

        let mut did_parser = DidParser::new(SUPPORTED_KEYS);

        verify_sphere_cid(&memo_cid, &store, &mut did_parser)
            .await
            .unwrap();
    }
}