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
use std::convert::TryFrom;

use anyhow::{anyhow, Result};
use cid::Cid;
use noosphere_core::{
    authority::{SphereAction, SphereReference},
    data::{CidKey, DelegationIpld, RevocationIpld},
    view::{Sphere, SphereMutation, SPHERE_LIFETIME},
};
use serde_json::{json, Value};
use ucan::{
    builder::UcanBuilder,
    capability::{Capability, Resource, With},
    crypto::KeyMaterial,
    store::UcanJwtStore,
    Ucan,
};

use tokio_stream::StreamExt;

use crate::native::workspace::Workspace;

pub async fn auth_add(did: &str, name: Option<String>, workspace: &Workspace) -> Result<()> {
    workspace.expect_local_directories()?;

    let mut db = workspace.get_local_db().await?;
    let sphere_did = workspace.get_local_identity().await?;
    let latest_sphere_cid = db.require_version(&sphere_did).await?;
    let sphere = Sphere::at(&latest_sphere_cid, &db);

    let authority = sphere.try_get_authority().await?;
    let allowed_ucans = authority.try_get_allowed_ucans().await?;
    let mut allowed_stream = allowed_ucans.stream().await?;

    while let Some((CidKey(cid), delegation)) = allowed_stream.try_next().await? {
        let ucan = delegation.resolve_ucan(&db).await?;
        let authorized_did = ucan.audience();

        if authorized_did == did {
            return Err(anyhow!(
                r#"{} is already authorized to access the sphere
Here is the identity of the authorization:

  {}

If you want to change it to something new, revoke the current one first:

  orb auth revoke {}

You will be able to add a new one after the old one is revoked"#,
                did,
                cid,
                delegation.name
            ));
        }
    }

    let name = match name {
        Some(name) => name,
        None => {
            let random_name = witty_phrase_generator::WPGen::new()
                .with_words(3)
                .unwrap_or_else(|| vec!["Unnamed"])
                .into_iter()
                .map(String::from)
                .collect::<Vec<String>>()
                .join("-");
            println!(
                "Note: since no name was specified, the authorization will be saved with the generated name \"{}\"",
                random_name
            );
            random_name
        }
    };

    let my_key = workspace.get_local_key().await?;
    let my_did = my_key.get_did().await?;
    let sphere_did = workspace.get_local_identity().await?;
    let latest_sphere_cid = db.require_version(&sphere_did).await?;
    let authorization = workspace.get_local_authorization().await?;

    let mut signable = UcanBuilder::default()
        .issued_by(&my_key)
        .for_audience(did)
        .claiming_capability(&Capability {
            with: With::Resource {
                kind: Resource::Scoped(SphereReference {
                    did: sphere_did.clone(),
                }),
            },
            can: SphereAction::Authorize,
        })
        .with_expiration(SPHERE_LIFETIME)
        .with_nonce()
        // TODO(ucan-wg/rs-ucan#32): Clean this up when we can use a CID as an authorization
        // .witnessed_by(&authorization)
        .build()?;

    signable
        .proofs
        .push(Cid::try_from(&authorization)?.to_string());

    let jwt = signable.sign().await?.encode()?;

    let delegation = DelegationIpld::try_register(&name, &jwt, &mut db).await?;

    let sphere = Sphere::at(&latest_sphere_cid, &db);

    let mut mutation = SphereMutation::new(&my_did);

    mutation
        .allowed_ucans_mut()
        .set(&CidKey(delegation.jwt), &delegation);

    let mut revision = sphere.try_apply_mutation(&mutation).await?;
    let version_cid = revision.try_sign(&my_key, Some(&authorization)).await?;

    db.set_version(&sphere_did, &version_cid).await?;

    println!(
        r#"Successfully authorized {did} to access your sphere.

IMPORTANT: You MUST sync to enable your gateway to recognize the authorization:

  orb sync

This is the authorization's identity:

  {}
  
Use this identity when joining the sphere on the other client"#,
        delegation.jwt
    );

    Ok(())
}

pub async fn auth_list(as_json: bool, workspace: &Workspace) -> Result<()> {
    workspace.expect_local_directories()?;

    let db = workspace.get_local_db().await?;
    let sphere_did = workspace.get_local_identity().await?;
    let latest_sphere_cid = db
        .get_version(&sphere_did)
        .await?
        .ok_or_else(|| anyhow!("Sphere version pointer is missing or corrupted"))?;

    let sphere = Sphere::at(&latest_sphere_cid, &db);

    let authorization = sphere.try_get_authority().await?;

    let allowed_ucans = authorization.try_get_allowed_ucans().await?;

    let mut authorizations: Vec<(String, String, Cid)> = Vec::new();
    let mut delegation_stream = allowed_ucans.stream().await?;
    let mut max_name_length: usize = 7;

    while let Some(Ok((_, delegation))) = delegation_stream.next().await {
        let jwt = db.require_token(&delegation.jwt).await?;
        let ucan = Ucan::try_from_token_string(&jwt)?;
        let name = delegation.name.clone();

        max_name_length = max_name_length.max(name.len());
        authorizations.push((
            delegation.name.clone(),
            ucan.audience().into(),
            delegation.jwt,
        ));
    }

    if as_json {
        let authorizations: Vec<Value> = authorizations
            .into_iter()
            .map(|(name, did, cid)| {
                json!({
                    "name": name,
                    "did": did,
                    "cid": cid.to_string()
                })
            })
            .collect();
        println!("{}", serde_json::to_string_pretty(&json!(authorizations))?);
    } else {
        println!("{:1$}  AUTHORIZED KEY", "NAME", max_name_length);
        for (name, did, _) in authorizations {
            println!("{:1$}  {did}", name, max_name_length);
        }
    }

    Ok(())
}

pub async fn auth_revoke(name: &str, workspace: &Workspace) -> Result<()> {
    workspace.expect_local_directories()?;

    let mut db = workspace.get_local_db().await?;
    let sphere_did = workspace.get_local_identity().await?;
    let latest_sphere_cid = db
        .get_version(&sphere_did)
        .await?
        .ok_or_else(|| anyhow!("Sphere version pointer is missing or corrupted"))?;

    let my_key = workspace.get_local_key().await?;
    let my_did = my_key.get_did().await?;

    let sphere = Sphere::at(&latest_sphere_cid, &db);

    let authorization = sphere.try_get_authority().await?;

    let allowed_ucans = authorization.try_get_allowed_ucans().await?;

    let mut delegation_stream = allowed_ucans.stream().await?;

    while let Some(Ok((CidKey(cid), delegation))) = delegation_stream.next().await {
        if delegation.name == name {
            let revocation = RevocationIpld::try_revoke(cid, &my_key).await?;

            let mut mutation = SphereMutation::new(&my_did);

            let key = CidKey(*cid);

            mutation.allowed_ucans_mut().remove(&key);
            mutation.revoked_ucans_mut().set(&key, &revocation);

            let mut revision = sphere.try_apply_mutation(&mutation).await?;
            let ucan = workspace.get_local_authorization().await?;

            let sphere_cid = revision.try_sign(&my_key, Some(&ucan)).await?;

            db.set_version(&sphere_did, &sphere_cid).await?;

            println!("The authorization named {:?} has been revoked", name);

            return Ok(());
        }
    }

    Err(anyhow!("There is no authorization named {:?}", name))
}