drawbridge 0.4.2

Drawbridge library.
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// SPDX-FileCopyrightText: 2022 Profian Inc. <opensource@profian.com>
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashMap;
use std::time::{Duration, SystemTime};

use drawbridge_client::mime::APPLICATION_OCTET_STREAM;
use drawbridge_client::types::{RepositoryConfig, TreePath, UserRecord};
use drawbridge_client::Client;
use drawbridge_server::{App, OidcConfig, TlsConfig};

use async_std::fs::{create_dir, write};
use async_std::net::{Ipv4Addr, TcpListener};
use async_std::task::{spawn, spawn_blocking};
use drawbridge_type::digest::Algorithms;
use drawbridge_type::Meta;
use futures::channel::oneshot::channel;
use futures::{join, try_join, StreamExt};
use http_types::convert::{json, Serialize};
use http_types::{Body, Response, StatusCode};
use jsonwebtoken::{encode, EncodingKey, Header};
use openidconnect::core::{
    CoreJwsSigningAlgorithm, CoreProviderMetadata, CoreResponseType, CoreSubjectIdentifierType,
};
use openidconnect::{
    AuthUrl, EmptyAdditionalProviderMetadata, IssuerUrl, JsonWebKeySetUrl, ResponseTypes,
};
use rsa::pkcs1::EncodeRsaPrivateKey;
use rsa::traits::PublicKeyParts;
use rustls::RootCertStore;
use rustls_pemfile::Item::{Pkcs1Key, Pkcs8Key, Sec1Key};
use rustls_pki_types::CertificateDer;
use rustls_pki_types::PrivateKeyDer;
use tempfile::tempdir;

#[derive(Debug, Clone, serde::Serialize)]
struct TokenClaims {
    #[serde(rename = "iss")]
    issuer: String,
    #[serde(rename = "aud")]
    audience: Vec<String>,
    #[serde(rename = "sub")]
    subject: String,
    #[serde(rename = "iat")]
    issued_at: u64,
    #[serde(rename = "exp")]
    expires_at: u64,
    scope: String,
}

#[async_std::test]
async fn app() {
    tracing_subscriber::fmt::init();

    let oidc_lis = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
        .await
        .expect("failed to bind to address");
    let oidc_addr = oidc_lis.local_addr().unwrap();
    let oidc_issuer = format!("http://{oidc_addr}/");
    let oidc_audience = "testserver";

    let mut rng = rand::thread_rng();
    let oidc_key_raw = rsa::RsaPrivateKey::new(&mut rng, 2048).expect("failed to generate a key");
    let oidc_key_der = oidc_key_raw.to_pkcs1_der().expect("failed to encode key");
    let oidc_key = EncodingKey::from_rsa_der(oidc_key_der.as_bytes());
    let oidc_key_pub = oidc_key_raw.to_public_key();
    let oidc_key_jwk = drawbridge_jose::jwk::Jwk {
        key: drawbridge_jose::jwk::Key::Rsa {
            prv: None,
            n: oidc_key_pub.n().to_bytes_be().into(),
            e: oidc_key_pub.e().to_bytes_be().into(),
        },
        prm: drawbridge_jose::jwk::Parameters {
            kid: Some("signkey".into()),
            ..Default::default()
        },
    };
    let oidc_pubkeys = drawbridge_jose::jwk::JwkSet {
        keys: vec![oidc_key_jwk.clone()],
    };

    const SUBJECT: &str = "test|subject";

    let mut jwt_header = Header::new(jsonwebtoken::Algorithm::RS256);
    jwt_header.kid = Some("signkey".to_owned());
    let jwt_payload = TokenClaims {
        issuer: oidc_issuer.clone(),
        audience: vec![oidc_audience.to_owned()],
        subject: SUBJECT.to_owned(),
        issued_at: SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        expires_at: (SystemTime::now() + Duration::from_secs(3600))
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        scope:
            "openid manage:drawbridge_users manage:drawbridge_repositories manage:drawbridge_tags"
                .into(),
    };

    let mut oidc_tokens = HashMap::from([
        ("valid", {
            let payload = jwt_payload.clone();
            encode(&jwt_header, &payload, &oidc_key).expect("failed to sign token")
        }),
        ("expired", {
            let mut payload = jwt_payload.clone();
            payload.issued_at = SystemTime::now()
                .checked_sub(Duration::from_secs(3600))
                .unwrap()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap()
                .as_secs();
            payload.expires_at = SystemTime::now()
                .checked_sub(Duration::from_secs(3600))
                .unwrap()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap()
                .as_secs();
            encode(&jwt_header, &payload, &oidc_key).expect("failed to sign token")
        }),
        ("no_scopes", {
            let mut payload = jwt_payload.clone();
            payload.scope = "openid".into();
            encode(&jwt_header, &payload, &oidc_key).expect("failed to sign token")
        }),
        ("missing_manage_user_scope", {
            let mut payload = jwt_payload.clone();
            payload.scope = "openid manage:drawbridge_repositories manage:drawbridge_tags read:drawbridge_users".into();
            encode(&jwt_header, &payload, &oidc_key).expect("failed to sign token")
        }),
        ("invalid_aud", {
            let mut payload = jwt_payload.clone();
            payload.audience = vec!["invalid".into()];
            encode(&jwt_header, &payload, &oidc_key).expect("failed to sign token")
        }),
        ("invalid_iss", {
            let mut payload = jwt_payload.clone();
            payload.issuer = "invalid".into();
            encode(&jwt_header, &payload, &oidc_key).expect("failed to sign token")
        }),
        ("invalid_sig", {
            let payload = jwt_payload.clone();
            let mut token = encode(&jwt_header, &payload, &oidc_key).expect("failed to sign token");
            token.pop();
            token
        }),
    ]);
    let oidc_token_valid = oidc_tokens.remove("valid").unwrap();

    let (oidc_tx, oidc_rx) = channel::<()>();
    let oidc = spawn(async move {
        oidc_lis
            .incoming()
            .take_until(oidc_rx)
            .for_each_concurrent(None, |stream| async {
                let oidc_pubkeys = &oidc_pubkeys;

                async_h1::accept(
                    stream.expect("failed to initialize stream"),
                    |req| async move {
                        fn json_response(
                            body: &impl Serialize,
                        ) -> Result<Response, http_types::Error> {
                            let mut res = Response::new(StatusCode::Ok);
                            res.insert_header("Content-Type", "application/json");
                            let body = Body::from_json(&json!(body))?;
                            res.set_body(body);
                            Ok(res)
                        }

                        let oidc_url = format!("http://{oidc_addr}/");
                        match req.url().path() {
                            "/.well-known/openid-configuration" => {
                                json_response(&CoreProviderMetadata::new(
                                    // Parameters required by the OpenID Connect Discovery spec.
                                    IssuerUrl::new(oidc_url.to_string()).unwrap(),
                                    AuthUrl::new(format!("{oidc_url}authorize")).unwrap(),
                                    // Use the JsonWebKeySet struct to serve the JWK Set at this URL.
                                    JsonWebKeySetUrl::new(format!("{oidc_url}jwks")).unwrap(),
                                    vec![ResponseTypes::new(vec![CoreResponseType::Code])],
                                    vec![CoreSubjectIdentifierType::Pairwise],
                                    vec![CoreJwsSigningAlgorithm::RsaSsaPssSha256],
                                    EmptyAdditionalProviderMetadata {},
                                ))
                            }
                            "/jwks" => json_response(&oidc_pubkeys),
                            p => panic!("Unsupported path requested: `{p}`"),
                        }
                    },
                )
                .await
                .expect("failed to handle OIDC connection");
            })
            .await
    });

    let srv_lis = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
        .await
        .expect("failed to bind to address");
    let srv_port = srv_lis.local_addr().unwrap().port();

    let store = tempdir().expect("failed to create temporary store directory");

    let (srv_tx, srv_rx) = channel::<()>();
    let srv = spawn(async move {
        let tls = TlsConfig::read(
            include_bytes!("../testdata/server.crt").as_slice(),
            include_bytes!("../testdata/server.key").as_slice(),
            include_bytes!("../testdata/ca.crt").as_slice(),
        )
        .unwrap();
        let app = App::new(
            store.path(),
            tls,
            OidcConfig {
                audience: oidc_audience.to_string(),
                issuer: oidc_issuer.parse().unwrap(),
            },
        )
        .await
        .unwrap();
        srv_lis
            .incoming()
            .take_until(srv_rx)
            .for_each_concurrent(None, |stream| async {
                app.handle(stream.expect("failed to initialize stream"))
                    .await
                    .expect("failed to handle stream")
            })
            .await
    });

    let cl = spawn_blocking(move || async move {
        let (anon_cl, cert_cl, oidc_valid_cl, blank_cl) = {
            let cl = Client::builder(format!("https://localhost:{srv_port}").parse().unwrap())
                .roots({
                    let mut roots = RootCertStore::empty();
                    rustls_pemfile::certs(&mut std::io::BufReader::new(
                        include_bytes!("../testdata/ca.crt").as_slice(),
                    ))
                    .for_each(|c| {
                        if let Ok(cert) = c {
                            roots.add(cert).expect("failed to add cert to root store");
                        }
                    });
                    roots
                });

            let cert = rustls_pemfile::certs(&mut std::io::BufReader::new(
                include_bytes!("../testdata/client.crt").as_slice(),
            ))
            .filter_map(|c| match c {
                Ok(cert) => Some(cert),
                Err(_) => None,
            })
            .collect::<Vec<CertificateDer>>();

            let key = rustls_pemfile::read_one(&mut std::io::BufReader::new(
                include_bytes!("../testdata/client.key").as_slice(),
            ))
            .unwrap()
            .map(|item| match item {
                Pkcs1Key(buf) => PrivateKeyDer::from(buf),
                Pkcs8Key(buf) => PrivateKeyDer::from(buf),
                Sec1Key(buf) => PrivateKeyDer::from(buf),
                _ => panic!("unsupported key type `{item:?}`"),
            })
            .unwrap();

            (
                cl.clone().build().unwrap(),
                cl.clone().credentials(cert, key).build().unwrap(),
                cl.clone().token(oidc_token_valid).build().unwrap(),
                cl,
            )
        };

        let user_name = "testuser".parse().unwrap();
        let user_record = UserRecord {
            subject: SUBJECT.into(),
        };

        let anon_user = anon_cl.user(&user_name);
        let cert_user = cert_cl.user(&user_name);
        let oidc_user = oidc_valid_cl.user(&user_name);

        assert!(anon_user.get().is_err());
        assert!(cert_user.get().is_err());
        assert!(oidc_user.get().is_err());

        assert!(anon_user.create(&user_record).is_err());
        assert!(cert_user.create(&user_record).is_err());
        for (token_type, token) in oidc_tokens {
            let client = blank_cl.clone().token(token).build().unwrap();
            assert!(
                client.user(&user_name).create(&user_record).is_err(),
                "OIDC token type {token_type} accepted incorrectly"
            );
        }
        assert!(oidc_user
            .create(&UserRecord {
                subject: format!("{}other", user_record.subject),
            })
            .is_err());
        assert!(oidc_user
            .create(&user_record)
            .expect("failed to create user"));
        assert!(oidc_valid_cl
            .user(&format!("{user_name}other").parse().unwrap())
            .create(&user_record)
            .expect("failed to create other user"));

        assert!(anon_user.get().is_err());
        assert!(cert_user.get().is_err());
        assert_eq!(oidc_user.get().expect("failed to get user"), user_record);

        let prv_repo_name = "test-repo-private".parse().unwrap();
        let prv_repo_conf = RepositoryConfig { public: false };

        let pub_repo_name = "test-repo-public".parse().unwrap();
        let pub_repo_conf = RepositoryConfig { public: true };

        let anon_prv_repo = anon_user.repository(&prv_repo_name);
        let cert_prv_repo = cert_user.repository(&prv_repo_name);
        let oidc_prv_repo = oidc_user.repository(&prv_repo_name);

        let anon_pub_repo = anon_user.repository(&pub_repo_name);
        let cert_pub_repo = cert_user.repository(&pub_repo_name);
        let oidc_pub_repo = oidc_user.repository(&pub_repo_name);

        assert!(anon_prv_repo.get().is_err());
        assert!(cert_prv_repo.get().is_err());
        assert!(oidc_prv_repo.get().is_err());

        assert!(anon_pub_repo.get().is_err());
        assert!(cert_pub_repo.get().is_err());
        assert!(oidc_pub_repo.get().is_err());

        assert!(anon_prv_repo.tags().is_err());
        assert!(cert_prv_repo.tags().is_err());
        assert!(oidc_prv_repo.tags().is_err());

        assert!(anon_pub_repo.tags().is_err());
        assert!(cert_pub_repo.tags().is_err());
        assert!(oidc_pub_repo.tags().is_err());

        assert!(anon_prv_repo.create(&prv_repo_conf).is_err());
        assert!(cert_prv_repo.create(&prv_repo_conf).is_err());
        assert!(oidc_prv_repo
            .create(&prv_repo_conf)
            .expect("failed to create repository"));

        assert!(anon_pub_repo.create(&pub_repo_conf).is_err());
        assert!(cert_pub_repo.create(&pub_repo_conf).is_err());
        assert!(oidc_pub_repo
            .create(&pub_repo_conf)
            .expect("failed to create repository"));

        assert!(anon_prv_repo.get().is_err());
        assert!(cert_prv_repo.get().is_err());
        assert_eq!(
            oidc_prv_repo.get().expect("failed to get repository"),
            prv_repo_conf
        );

        assert!(anon_pub_repo.get().is_err());
        assert!(cert_pub_repo.get().is_err());
        assert_eq!(
            oidc_pub_repo.get().expect("failed to get repository"),
            pub_repo_conf
        );

        assert!(anon_prv_repo.tags().is_err());
        assert!(cert_prv_repo.tags().is_err());
        assert_eq!(oidc_prv_repo.tags().expect("failed to get tags"), vec![]);

        assert_eq!(anon_pub_repo.tags().expect("failed to get tags"), vec![]);
        assert_eq!(cert_pub_repo.tags().expect("failed to get tags"), vec![]);
        assert_eq!(oidc_pub_repo.tags().expect("failed to get tags"), vec![]);

        let pkg = tempdir().expect("failed to create temporary package directory");

        try_join!(
            write(pkg.path().join("test-file"), "no extension"),
            write(pkg.path().join("test-file.txt"), "text"),
            write(pkg.path().join("test-file.json"), "not valid json"),
            write(pkg.path().join("tEst-file..__.foo.42."), "invalidext"),
            create_dir(pkg.path().join("test-dir-1")),
        )
        .unwrap();

        try_join!(
            write(pkg.path().join("test-dir-1").join("test-file.txt"), "text"),
            write(pkg.path().join("test-dir-1").join("test-file"), "test"),
            create_dir(pkg.path().join("test-dir-1").join("test-subdir-1")),
            create_dir(pkg.path().join("test-dir-1").join("test-subdir-2")),
        )
        .unwrap();

        write(
            pkg.path()
                .join("test-dir-1")
                .join("test-subdir-2")
                .join("test-file"),
            "test",
        )
        .await
        .unwrap();

        let tag_name = "0.1.0".parse().unwrap();

        let anon_prv_tag = anon_prv_repo.tag(&tag_name);
        let cert_prv_tag = cert_prv_repo.tag(&tag_name);
        let oidc_prv_tag = oidc_prv_repo.tag(&tag_name);

        let anon_pub_tag = anon_pub_repo.tag(&tag_name);
        let cert_pub_tag = cert_pub_repo.tag(&tag_name);
        let oidc_pub_tag = oidc_pub_repo.tag(&tag_name);

        assert!(anon_prv_tag.get().is_err());
        assert!(cert_prv_tag.get().is_err());
        assert!(oidc_prv_tag.get().is_err());

        assert!(anon_pub_tag.get().is_err());
        assert!(cert_pub_tag.get().is_err());
        assert!(oidc_pub_tag.get().is_err());

        assert!(anon_prv_tag.create_from_path_unsigned(pkg.path()).is_err());
        assert!(cert_prv_tag.create_from_path_unsigned(pkg.path()).is_err());
        let (prv_tag_created, prv_tree_created) = oidc_prv_tag
            .create_from_path_unsigned(pkg.path())
            .expect("failed to create a tag and upload the tree");
        assert!(prv_tag_created);
        assert_eq!(
            prv_tree_created.clone().into_iter().collect::<Vec<_>>(),
            vec![
                (TreePath::ROOT, true),
                ("tEst-file..__.foo.42.".parse().unwrap(), true),
                ("test-dir-1".parse().unwrap(), true),
                ("test-dir-1/test-file".parse().unwrap(), true),
                ("test-dir-1/test-file.txt".parse().unwrap(), true),
                ("test-dir-1/test-subdir-1".parse().unwrap(), true),
                ("test-dir-1/test-subdir-2".parse().unwrap(), true),
                ("test-dir-1/test-subdir-2/test-file".parse().unwrap(), true),
                ("test-file".parse().unwrap(), true),
                ("test-file.json".parse().unwrap(), true),
                ("test-file.txt".parse().unwrap(), true),
            ]
        );

        assert!(anon_pub_tag.create_from_path_unsigned(pkg.path()).is_err());
        assert!(cert_pub_tag.create_from_path_unsigned(pkg.path()).is_err());
        assert_eq!(
            oidc_pub_tag
                .create_from_path_unsigned(pkg.path())
                .expect("failed to create a tag and upload the tree"),
            (prv_tag_created, prv_tree_created)
        );

        assert!(anon_prv_repo.tags().is_err());
        assert!(cert_prv_repo.tags().is_err());
        assert_eq!(
            oidc_prv_repo.tags().expect("failed to get tags"),
            vec![tag_name.clone()]
        );

        assert_eq!(
            anon_pub_repo.tags().expect("failed to get tags"),
            vec![tag_name.clone()]
        );
        assert_eq!(
            cert_pub_repo.tags().expect("failed to get tags"),
            vec![tag_name.clone()]
        );
        assert_eq!(
            oidc_pub_repo.tags().expect("failed to get tags"),
            vec![tag_name.clone()]
        );

        let file_name = "test-file.txt".parse().unwrap();
        let file_meta = Algorithms::default()
            .read_sync("text".as_bytes())
            .map(|(size, hash)| Meta {
                hash,
                size,
                mime: APPLICATION_OCTET_STREAM,
            })
            .unwrap();
        let file_expected = (file_meta, "text".into());

        let anon_prv_file = anon_prv_tag.path(&file_name);
        let cert_prv_file = cert_prv_tag.path(&file_name);
        let oidc_prv_file = oidc_prv_tag.path(&file_name);

        let anon_pub_file = anon_pub_tag.path(&file_name);
        let cert_pub_file = cert_pub_tag.path(&file_name);
        let oidc_pub_file = oidc_pub_tag.path(&file_name);

        assert!(anon_prv_file.get_string(5).is_err());
        assert_eq!(
            cert_prv_file.get_string(5).expect("failed to get file"),
            file_expected,
        );
        assert_eq!(
            oidc_prv_file.get_string(5).expect("failed to get file"),
            file_expected,
        );

        assert_eq!(
            anon_pub_file.get_string(5).expect("failed to get file"),
            file_expected,
        );
        assert_eq!(
            cert_pub_file.get_string(5).expect("failed to get file"),
            file_expected,
        );
        assert_eq!(
            oidc_pub_file.get_string(5).expect("failed to get file"),
            file_expected,
        );
    });
    assert!(matches!(cl.await.await, ()));

    // Stop OpenID Connect provider
    assert_eq!(oidc_tx.send(()), Ok(()));

    // Stop server
    assert_eq!(srv_tx.send(()), Ok(()));
    assert!(matches!(join!(oidc, srv), ((), ())));
}