ckms 5.20.1

Command Line Interface used to manage the Cosmian KMS server. If any assistance is needed, please either visit the Cosmian technical documentation at https://docs.cosmian.com or contact the Cosmian support team on Discord https://discord.com/invite/7kPMNtHpnz
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
use std::{net::TcpListener, path::PathBuf, process::Command};

use assert_cmd::prelude::*;
use base64::Engine;
use cosmian_config_utils::ConfigUtils;
use cosmian_kms_cli_actions::{
    actions::symmetric::keys::create_key::CreateKeyAction,
    reexport::cosmian_kms_client::{
        read_object_from_json_ttlv_file, reexport::cosmian_http_client::HttpClientConfig,
    },
};
use cosmian_logger::{debug, info, log_init, trace};
use tempfile::TempDir;
use test_kms_server::{
    AuthenticationOptions, ClientAuthOptions, MainDBConfig, ServerJwtAuth as JwtAuth,
    ServerTlsMode as TlsMode, build_server_params, start_default_test_kms_server_with_jwt_auth,
    start_test_server_with_options,
};
use tokio::fs;

use super::utils::recover_cmd_logs;
use crate::{
    config::{CKMS_CONF_ENV, ClientConfig},
    error::result::CosmianResult,
    tests::{
        PROG_NAME,
        access::SUB_COMMAND,
        force_save_kms_cli_config,
        shared::{ExportKeyParams, export_key},
        symmetric::create_key::create_symmetric_key,
    },
};

fn run_owned_cli_command(owner_client_conf_path: &str) {
    // Debug: ensure token/cert presence in saved config
    if let Ok(conf) = ClientConfig::from_toml(owner_client_conf_path) {
        let http = &conf.kms_config.http_config;
        debug!(
            "[auth_tests] Using conf {} => url: {}, token: {}, cert: {}",
            owner_client_conf_path,
            http.server_url,
            if http.access_token.is_some() {
                "set"
            } else {
                "none"
            },
            if http.tls_client_pkcs12_path.is_some() {
                "set"
            } else {
                "none"
            }
        );
    }
    let mut cmd = Command::cargo_bin(PROG_NAME).expect(" cargo bin failed");
    cmd.env(CKMS_CONF_ENV, owner_client_conf_path);

    cmd.arg(SUB_COMMAND).args(vec!["owned"]);
    recover_cmd_logs(&mut cmd);
    cmd.assert().success();
}

/// This function runs the CLI command with the provided configuration path and expects it to fail.
fn run_owned_cli_command_expect_failure(owner_client_conf_path: &str) {
    // Debug: ensure token/cert presence in saved config
    if let Ok(conf) = ClientConfig::from_toml(owner_client_conf_path) {
        let http = &conf.kms_config.http_config;
        debug!(
            "[auth_tests] Using conf (expected fail) {} => url: {}, token: {}, cert: {}",
            owner_client_conf_path,
            http.server_url,
            if http.access_token.is_some() {
                "set"
            } else {
                "none"
            },
            if http.tls_client_pkcs12_path.is_some() {
                "set"
            } else {
                "none"
            }
        );
    }
    let mut cmd = Command::cargo_bin(PROG_NAME).expect(" cargo bin failed");
    cmd.env(CKMS_CONF_ENV, owner_client_conf_path);

    cmd.arg(SUB_COMMAND).args(vec!["owned"]);
    recover_cmd_logs(&mut cmd);
    cmd.assert().failure();
}

fn create_api_token(owner_client_conf_path: &str) -> CosmianResult<(String, String)> {
    // Create and export an API token
    let api_token_id = create_symmetric_key(owner_client_conf_path, CreateKeyAction::default())?;
    trace!("Symmetric key created of unique identifier: {api_token_id:?}");

    // Export as default (JsonTTLV with Raw Key Format Type)
    // create a temp dir
    let tmp_dir = TempDir::new()?;
    let tmp_path = tmp_dir.path();
    export_key(ExportKeyParams {
        cli_conf_path: owner_client_conf_path.to_string(),
        sub_command: "sym".to_owned(),
        key_id: api_token_id.clone(),
        key_file: tmp_path.join("api_token").to_str().unwrap().to_owned(),
        ..Default::default()
    })?;

    let api_token = base64::engine::general_purpose::STANDARD.encode(
        read_object_from_json_ttlv_file(&tmp_path.join("api_token"))?
            .key_block()?
            .key_bytes()?,
    );
    trace!("API token created: {api_token}");
    Ok((api_token_id, api_token))
}

// Pick a free local port to avoid collisions with other tests
fn pick_free_port() -> u16 {
    TcpListener::bind("127.0.0.1:0")
        .expect("Failed to bind to an ephemeral port")
        .local_addr()
        .expect("Failed to read local_addr")
        .port()
}

#[allow(clippy::large_stack_frames)]
#[tokio::test]
pub(crate) async fn test_kms_all_authentications() -> CosmianResult<()> {
    log_init(None);

    // Determine a base port and clean up its associated workspace directory
    let base_port = pick_free_port();
    let _e = fs::remove_dir_all(PathBuf::from(format!(
        "/tmp/kms_test_workspace_{base_port}"
    )))
    .await;

    // plaintext no auth
    info!("==> Testing server with no auth");
    let port = base_port;
    let ctx = start_test_server_with_options(
        MainDBConfig {
            database_type: Some("sqlite".to_owned()),
            sqlite_path: PathBuf::from("./sqlite-data-auth-tests"),
            clear_database: true,
            ..MainDBConfig::default()
        },
        port,
        AuthenticationOptions {
            client: ClientAuthOptions::default(),
            server_params: Some(build_server_params(
                MainDBConfig {
                    database_type: Some("sqlite".to_owned()),
                    sqlite_path: PathBuf::from("./sqlite-data-auth-tests"),
                    clear_database: false,
                    ..MainDBConfig::default()
                },
                port,
                TlsMode::PlainHttp,
                JwtAuth::Disabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);

    run_owned_cli_command(&owner_client_conf_path);
    // Create an API auth token with admin rights for later
    let (api_token_id, api_token) = create_api_token(&owner_client_conf_path)?;
    ctx.stop_server().await?;

    let default_db_config = MainDBConfig {
        database_type: Some("sqlite".to_owned()),
        sqlite_path: PathBuf::from("./sqlite-data-auth-tests"),
        clear_database: false,
        ..MainDBConfig::default()
    };

    // plaintext JWT token auth
    info!("==> Testing server with JWT token over HTTP");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                jwt: test_kms_server::JwtPolicy::AutoDefault,
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::PlainHttp,
                JwtAuth::Enabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // tls token auth
    info!("==> Testing server with JWT token auth over HTTPS");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                jwt: test_kms_server::JwtPolicy::AutoDefault,
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::HttpsWithClientCa,
                JwtAuth::Enabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // Client Certificate authentication (PKCS#12)
    info!("==> Testing server with Client Certificate auth (PKCS#12)");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions::default(),
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::HttpsWithClientCa,
                JwtAuth::Disabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // Client Certificate authentication (PEM cert + key — FIPS-compatible format)
    info!("==> Testing server with Client Certificate auth (PEM)");
    let port = pick_free_port();
    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let pem_cert = manifest_dir
        .join("../../../test_data/certificates/client_server/owner/owner.client.acme.com.crt")
        .canonicalize()
        .expect("owner PEM cert must exist in test_data");
    let pem_key = manifest_dir
        .join("../../../test_data/certificates/client_server/owner/owner.client.acme.com.key")
        .canonicalize()
        .expect("owner PEM key must exist in test_data");
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                http: HttpClientConfig {
                    tls_client_pem_cert_path: Some(pem_cert.to_string_lossy().into_owned()),
                    tls_client_pem_key_path: Some(pem_key.to_string_lossy().into_owned()),
                    ..Default::default()
                },
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::HttpsWithClientCa,
                JwtAuth::Disabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // SCENARIO 1: Both Client Certificates and JWT authentication enabled, user presents JWT token only
    info!(
        "==> Testing server with both Client Certificates and JWT auth - User sends JWT token only"
    );
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                // Suppress client certificate to ensure JWT-only auth path
                client_cert: test_kms_server::ClientCertPolicy::Suppress,
                jwt: test_kms_server::JwtPolicy::AutoDefault,
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::HttpsWithClientCa,
                JwtAuth::Enabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // SCENARIO 2: Both Client Certificates and API token authentication enabled, user presents API token only
    info!(
        "==> Testing server with both Client Certificates and API token auth -User sends API \
         token only"
    );
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                http: HttpClientConfig {
                    access_token: Some(api_token.clone()),
                    ..Default::default()
                },
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::HttpsWithClientCa,
                JwtAuth::Disabled,
                None,
                Some(api_token_id.clone()),
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // SCENARIO 3: Both JWT and API token authentication enabled, user presents API token only
    info!("==> Testing server with both JWT and API token auth - User sends the API token only");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                // Suppress JWT to ensure API token only
                jwt: test_kms_server::JwtPolicy::Suppress,
                http: HttpClientConfig {
                    access_token: Some(api_token.clone()),
                    ..Default::default()
                },
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::HttpsWithClientCa,
                JwtAuth::Enabled,
                None,
                Some(api_token_id.clone()),
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // SCENARIO 4: JWT authentication enabled, no token provided (failure case)
    info!("==> Testing server with JWT auth - User does not send the token (should fail)");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                jwt: test_kms_server::JwtPolicy::Suppress,
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::PlainHttp,
                JwtAuth::Enabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command_expect_failure(&owner_client_conf_path);
    ctx.stop_server().await?;

    // SCENARIO 5: Client Certificate authentication enabled, no certificate provided (failure case)
    info!("==> Testing server with Client Certificate auth - missing certificate (should fail)");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                client_cert: test_kms_server::ClientCertPolicy::Suppress,
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::HttpsWithClientCa,
                JwtAuth::Disabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command_expect_failure(&owner_client_conf_path);
    ctx.stop_server().await?;

    // SCENARIO 6: API token authentication enabled, no token provided (failure case)
    info!("==> Testing server with API token auth - missing token (should fail)");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                http: HttpClientConfig {
                    access_token: None, // missing token -> should fail
                    ..Default::default()
                },
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::HttpsNoClientCa,
                JwtAuth::Disabled,
                None,
                Some(api_token_id.clone()),
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command_expect_failure(&owner_client_conf_path);
    ctx.stop_server().await?;

    // SCENARIO 7: JWT authentication enabled, but no JWT token presented (failure case)
    info!("===> Testing server with JWT auth - but no JWT token sent (should fail)");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                jwt: test_kms_server::JwtPolicy::Suppress,
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::PlainHttp,
                JwtAuth::Enabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command_expect_failure(&owner_client_conf_path);
    ctx.stop_server().await?;

    // Bad API token auth but JWT auth used at first
    info!("==> Testing server with bad API token auth but JWT auth used at first");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                jwt: test_kms_server::JwtPolicy::AutoDefault,
                ..Default::default()
            },
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::PlainHttp,
                JwtAuth::Enabled,
                None,
                None,
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // Bad API token auth, but cert auth used at first
    info!("==> Testing server with bad API token auth but cert auth used at first");
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config.clone(),
        port,
        AuthenticationOptions {
            client: ClientAuthOptions::default(),
            server_params: Some(build_server_params(
                default_db_config.clone(),
                port,
                TlsMode::HttpsWithClientCa,
                JwtAuth::Disabled,
                None,
                Some("my_bad_token_id".to_owned()),
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // Bad API token and good JWT token auth but still cert auth used at first
    info!(
        "==> Testing server with bad API token and good JWT token auth but still cert auth used \
         at first"
    );
    let port = pick_free_port();
    let ctx = start_test_server_with_options(
        default_db_config,
        port,
        AuthenticationOptions {
            client: ClientAuthOptions {
                jwt: test_kms_server::JwtPolicy::AutoDefault,
                ..Default::default()
            },
            server_params: Some(build_server_params(
                MainDBConfig {
                    database_type: Some("sqlite".to_owned()),
                    sqlite_path: PathBuf::from("./sqlite-data-auth-tests"),
                    clear_database: false,
                    ..MainDBConfig::default()
                },
                port,
                TlsMode::HttpsWithClientCa,
                JwtAuth::Enabled,
                None,
                Some("my_bad_token_id".to_owned()),
            )?),
        },
        None,
        None,
    )
    .await?;
    let (owner_client_conf_path, _) = force_save_kms_cli_config(&ctx);
    run_owned_cli_command(&owner_client_conf_path);
    ctx.stop_server().await?;

    // delete the temp db dir
    let _e = fs::remove_dir_all(PathBuf::from(format!(
        "/tmp/kms_test_workspace_{base_port}"
    )))
    .await;

    Ok(())
}

/// Regression test: ensure JWT authentication succeeds end-to-end.
///
/// This test guards against the panic introduced in `jsonwebtoken` 10.x when
/// neither the `rust_crypto` nor the `aws_lc_rs` feature is enabled for that
/// crate. Previously the server worker would panic on the first JWT-authenticated
/// request with:
///
/// > "Could not automatically determine the process-level CryptoProvider …"
///
/// The test also catches the `jsonwebtoken` 10.x audience-validation regression:
/// tokens carrying an `aud` claim were rejected with `InvalidAudience` when the
/// server had no expected audience configured (`validate_aud` defaulted to `true`
/// but the expected audience set was empty).
#[allow(clippy::large_stack_frames)]
#[tokio::test]
pub(crate) async fn test_jwt_authentication_no_panic() -> CosmianResult<()> {
    log_init(None);

    let ctx = start_default_test_kms_server_with_jwt_auth().await;
    let (owner_conf_path, _) = force_save_kms_cli_config(ctx);

    // A simple `access owned` command is enough to exercise the full
    // JWT-authenticated request path without touching any cryptographic keys.
    run_owned_cli_command(&owner_conf_path);

    Ok(())
}