rash_core 2.19.2

Declarative shell scripting using Rust native bindings
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
/// ANCHOR: module
/// # java_keystore
///
/// Manage Java keystores for SSL/TLS certificate management.
///
/// ## Attributes
///
/// ```yaml
/// check_mode:
///   support: full
/// ```
/// ANCHOR_END: module
/// ANCHOR: examples
/// ## Examples
///
/// ```yaml
/// - name: Import certificate into keystore
///   java_keystore:
///     path: /etc/ssl/keystore.jks
///     password: secret
///     certificate: /etc/ssl/cert.pem
///     private_key: /etc/ssl/key.pem
///     alias: myapp
///
/// - name: Import certificate with CA chain
///   java_keystore:
///     path: /etc/ssl/keystore.jks
///     password: secret
///     certificate: /etc/ssl/cert.pem
///     private_key: /etc/ssl/key.pem
///     alias: myapp
///     cacert_chain:
///       - /etc/ssl/ca-intermediate.pem
///       - /etc/ssl/ca-root.pem
///
/// - name: Import PKCS12 file into keystore
///   java_keystore:
///     path: /etc/ssl/keystore.jks
///     password: secret
///     pkcs12_path: /etc/ssl/bundle.p12
///     pkcs12_password: pkcs12secret
///     alias: myapp
///
/// - name: Remove certificate from keystore
///   java_keystore:
///     path: /etc/ssl/keystore.jks
///     password: secret
///     alias: oldcert
///     state: absent
///
/// - name: Create empty keystore
///   java_keystore:
///     path: /etc/ssl/keystore.jks
///     password: secret
///     state: present
///
/// - name: Import certificate with force overwrite
///   java_keystore:
///     path: /etc/ssl/keystore.jks
///     password: secret
///     certificate: /etc/ssl/newcert.pem
///     private_key: /etc/ssl/newkey.pem
///     alias: myapp
///     force: true
/// ```
/// ANCHOR_END: examples
use crate::error::{Error, ErrorKind, Result};
use crate::modules::{Module, ModuleResult, parse_params};

#[cfg(feature = "docs")]
use rash_derive::DocJsonSchema;

use std::fs;
use std::path::Path;
use std::process::Command;

use minijinja::Value;
#[cfg(feature = "docs")]
use schemars::{JsonSchema, Schema};
use serde::Deserialize;
use serde_json::json;
use serde_norway::Value as YamlValue;
use serde_norway::value;
#[cfg(feature = "docs")]
use strum_macros::{Display, EnumString};

#[derive(Debug, PartialEq, Deserialize)]
#[cfg_attr(feature = "docs", derive(JsonSchema, DocJsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Params {
    /// Path to the keystore file.
    pub path: String,
    /// Password for the keystore.
    pub password: String,
    /// Whether the entry should be present or absent.
    /// **[default: `"present"`]**
    pub state: Option<State>,
    /// Alias for the certificate in the keystore.
    pub alias: Option<String>,
    /// Path to the certificate file (PEM format).
    pub certificate: Option<String>,
    /// Path to the private key file (PEM format).
    pub private_key: Option<String>,
    /// List of CA certificate chain files (PEM format).
    pub cacert_chain: Option<Vec<String>>,
    /// Path to a PKCS12 file to import.
    pub pkcs12_path: Option<String>,
    /// Password for the PKCS12 file.
    pub pkcs12_password: Option<String>,
    /// Force overwrite existing entry with same alias.
    #[serde(default)]
    pub force: bool,
}

#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
#[cfg_attr(feature = "docs", derive(EnumString, Display, JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum State {
    #[default]
    Present,
    Absent,
}

fn run_keytool(args: &[&str], password: &str) -> Result<String> {
    let mut cmd = Command::new("keytool");
    cmd.args(args);
    cmd.args(["-storepass", password]);
    cmd.arg("-noprompt");

    let output = cmd.output().map_err(|e| {
        Error::new(
            ErrorKind::SubprocessFail,
            format!("Failed to execute keytool command: {e}"),
        )
    })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("KeyStoreException") || stderr.contains("IOException") {
            return Err(Error::new(
                ErrorKind::SubprocessFail,
                format!("Keytool command failed: {stderr}"),
            ));
        }
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

fn keystore_exists(path: &str) -> bool {
    Path::new(path).exists()
}

fn alias_exists(path: &str, alias: &str, password: &str) -> Result<bool> {
    let output = run_keytool(&["-list", "-keystore", path, "-alias", alias], password);

    match output {
        Ok(s) if s.contains(alias) || !s.contains("Alias <") => Ok(true),
        Ok(_) => Ok(false),
        Err(e) => {
            let err_str = e.to_string();
            if err_str.contains("does not exist") || err_str.contains("Alias <") {
                Ok(false)
            } else {
                Err(e)
            }
        }
    }
}

fn create_empty_keystore(path: &str, password: &str) -> Result<()> {
    let parent = Path::new(path).parent().ok_or_else(|| {
        Error::new(
            ErrorKind::NotFound,
            format!("Cannot determine parent directory for: {path}"),
        )
    })?;

    if !parent.exists() {
        fs::create_dir_all(parent).map_err(|e| {
            Error::new(
                ErrorKind::SubprocessFail,
                format!("Failed to create directory {}: {e}", parent.display()),
            )
        })?;
    }

    let mut cmd = Command::new("keytool");
    cmd.args([
        "-genkeypair",
        "-keystore",
        path,
        "-alias",
        "temp_alias_for_creation",
        "-keyalg",
        "RSA",
        "-keysize",
        "2048",
        "-validity",
        "1",
        "-dname",
        "CN=temp",
        "-storepass",
        password,
        "-keypass",
        password,
        "-noprompt",
    ]);

    let output = cmd.output().map_err(|e| {
        Error::new(
            ErrorKind::SubprocessFail,
            format!("Failed to execute keytool command: {e}"),
        )
    })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(Error::new(
            ErrorKind::SubprocessFail,
            format!("Failed to create keystore: {stderr}"),
        ));
    }

    let mut cmd = Command::new("keytool");
    cmd.args([
        "-delete",
        "-keystore",
        path,
        "-alias",
        "temp_alias_for_creation",
        "-storepass",
        password,
        "-noprompt",
    ]);

    let _ = cmd.output();

    Ok(())
}

fn create_pkcs12_bundle(
    cert_path: &str,
    key_path: &str,
    ca_chain: &[&str],
    pkcs12_path: &str,
    password: &str,
) -> Result<()> {
    let mut cmd = Command::new("openssl");
    cmd.args(["pkcs12", "-export"]);
    cmd.args(["-in", cert_path]);
    cmd.args(["-inkey", key_path]);
    cmd.args(["-out", pkcs12_path]);
    cmd.args(["-passout", &format!("pass:{password}")]);

    for ca_cert in ca_chain {
        cmd.args(["-certfile", ca_cert]);
    }

    let output = cmd.output().map_err(|e| {
        Error::new(
            ErrorKind::SubprocessFail,
            format!("Failed to execute openssl command: {e}"),
        )
    })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(Error::new(
            ErrorKind::SubprocessFail,
            format!("Failed to create PKCS12 bundle: {stderr}"),
        ));
    }

    Ok(())
}

fn import_pkcs12(
    keystore_path: &str,
    pkcs12_path: &str,
    pkcs12_password: &str,
    alias: &str,
    keystore_password: &str,
) -> Result<()> {
    let mut cmd = Command::new("keytool");
    cmd.args([
        "-importkeystore",
        "-srckeystore",
        pkcs12_path,
        "-srcstoretype",
        "PKCS12",
        "-srcstorepass",
        pkcs12_password,
        "-destkeystore",
        keystore_path,
        "-deststoretype",
        "JKS",
        "-deststorepass",
        keystore_password,
        "-srcalias",
        "1",
        "-destalias",
        alias,
        "-noprompt",
    ]);

    let output = cmd.output().map_err(|e| {
        Error::new(
            ErrorKind::SubprocessFail,
            format!("Failed to execute keytool command: {e}"),
        )
    })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(Error::new(
            ErrorKind::SubprocessFail,
            format!("Failed to import PKCS12: {stderr}"),
        ));
    }

    Ok(())
}

fn delete_alias(path: &str, alias: &str, password: &str) -> Result<()> {
    run_keytool(&["-delete", "-keystore", path, "-alias", alias], password)?;
    Ok(())
}

fn get_keystore_info(path: &str, password: &str) -> Result<String> {
    run_keytool(&["-list", "-keystore", path], password)
}

pub fn java_keystore(params: Params, check_mode: bool) -> Result<ModuleResult> {
    trace!("params: {params:?}");

    let state = params.state.clone().unwrap_or_default();

    match state {
        State::Present => {
            if params.certificate.is_some() && params.private_key.is_none() {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    "private_key is required when certificate is provided",
                ));
            }

            if params.private_key.is_some() && params.certificate.is_none() {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    "certificate is required when private_key is provided",
                ));
            }

            if params.pkcs12_path.is_some() && params.alias.is_none() {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    "alias is required when pkcs12_path is provided",
                ));
            }

            if params.certificate.is_some() && params.alias.is_none() {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    "alias is required when importing certificates",
                ));
            }

            if !keystore_exists(&params.path) {
                if check_mode {
                    return Ok(ModuleResult {
                        changed: true,
                        output: Some(format!("Would create keystore at {}", params.path)),
                        extra: None,
                    });
                }

                if params.pkcs12_path.is_some() || params.certificate.is_some() {
                    create_empty_keystore(&params.path, &params.password)?;
                }
            }

            if let Some(ref alias) = params.alias
                && alias_exists(&params.path, alias, &params.password)?
            {
                if !params.force {
                    let _info = get_keystore_info(&params.path, &params.password)?;
                    let extra = json!({
                        "path": params.path,
                        "alias": alias,
                        "exists": true,
                    });

                    return Ok(ModuleResult {
                        changed: false,
                        output: Some(format!(
                            "Alias '{}' already exists in keystore {}",
                            alias, params.path
                        )),
                        extra: Some(value::to_value(extra)?),
                    });
                }

                if check_mode {
                    return Ok(ModuleResult {
                        changed: true,
                        output: Some(format!(
                            "Would overwrite alias '{}' in keystore {}",
                            alias, params.path
                        )),
                        extra: None,
                    });
                }

                delete_alias(&params.path, alias, &params.password)?;
            }

            if check_mode {
                let action = if params.pkcs12_path.is_some() {
                    "Would import PKCS12 into keystore"
                } else if params.certificate.is_some() {
                    "Would import certificate into keystore"
                } else {
                    "Would ensure keystore exists"
                };
                return Ok(ModuleResult {
                    changed: true,
                    output: Some(format!("{} at {}", action, params.path)),
                    extra: None,
                });
            }

            if let Some(ref pkcs12_path) = params.pkcs12_path {
                let alias = params
                    .alias
                    .as_ref()
                    .ok_or_else(|| Error::new(ErrorKind::InvalidData, "alias is required"))?;

                let pkcs12_password = params
                    .pkcs12_password
                    .as_deref()
                    .unwrap_or(&params.password);

                import_pkcs12(
                    &params.path,
                    pkcs12_path,
                    pkcs12_password,
                    alias,
                    &params.password,
                )?;

                let extra = json!({
                    "path": params.path,
                    "alias": alias,
                    "pkcs12_path": pkcs12_path,
                });

                return Ok(ModuleResult {
                    changed: true,
                    output: Some(format!(
                        "Imported PKCS12 '{}' as alias '{}' into keystore {}",
                        pkcs12_path, alias, params.path
                    )),
                    extra: Some(value::to_value(extra)?),
                });
            }

            if let (Some(cert_path), Some(key_path), Some(alias)) =
                (&params.certificate, &params.private_key, &params.alias)
            {
                let temp_pkcs12 = format!("{}.temp.p12", params.path);
                let ca_chain = params.cacert_chain.clone().unwrap_or_default();

                let ca_refs: Vec<&str> = ca_chain.iter().map(|s| s.as_str()).collect();

                create_pkcs12_bundle(
                    cert_path,
                    key_path,
                    &ca_refs,
                    &temp_pkcs12,
                    &params.password,
                )?;

                let result = import_pkcs12(
                    &params.path,
                    &temp_pkcs12,
                    &params.password,
                    alias,
                    &params.password,
                );

                let _ = fs::remove_file(&temp_pkcs12);

                result?;

                let extra = json!({
                    "path": params.path,
                    "alias": alias,
                    "certificate": cert_path,
                    "private_key": key_path,
                    "ca_chain": ca_chain,
                });

                return Ok(ModuleResult {
                    changed: true,
                    output: Some(format!(
                        "Imported certificate '{}' as alias '{}' into keystore {}",
                        cert_path, alias, params.path
                    )),
                    extra: Some(value::to_value(extra)?),
                });
            }

            let extra = json!({
                "path": params.path,
            });

            Ok(ModuleResult {
                changed: true,
                output: Some(format!("Keystore {} is present", params.path)),
                extra: Some(value::to_value(extra)?),
            })
        }
        State::Absent => {
            if !keystore_exists(&params.path) {
                return Ok(ModuleResult {
                    changed: false,
                    output: Some(format!("Keystore {} does not exist", params.path)),
                    extra: None,
                });
            }

            let alias = params.alias.as_ref().ok_or_else(|| {
                Error::new(
                    ErrorKind::InvalidData,
                    "alias is required when state=absent",
                )
            })?;

            if !alias_exists(&params.path, alias, &params.password)? {
                return Ok(ModuleResult {
                    changed: false,
                    output: Some(format!(
                        "Alias '{}' does not exist in keystore {}",
                        alias, params.path
                    )),
                    extra: None,
                });
            }

            if check_mode {
                return Ok(ModuleResult {
                    changed: true,
                    output: Some(format!(
                        "Would remove alias '{}' from keystore {}",
                        alias, params.path
                    )),
                    extra: None,
                });
            }

            delete_alias(&params.path, alias, &params.password)?;

            let extra = json!({
                "path": params.path,
                "alias": alias,
            });

            Ok(ModuleResult {
                changed: true,
                output: Some(format!(
                    "Removed alias '{}' from keystore {}",
                    alias, params.path
                )),
                extra: Some(value::to_value(extra)?),
            })
        }
    }
}

#[derive(Debug)]
pub struct JavaKeystore;

impl Module for JavaKeystore {
    fn get_name(&self) -> &str {
        "java_keystore"
    }

    fn exec(
        &self,
        _: &crate::context::GlobalParams,
        optional_params: YamlValue,
        _vars: &Value,
        check_mode: bool,
    ) -> Result<(ModuleResult, Option<Value>)> {
        Ok((
            java_keystore(parse_params(optional_params)?, check_mode)?,
            None,
        ))
    }

    #[cfg(feature = "docs")]
    fn get_json_schema(&self) -> Option<Schema> {
        Some(Params::get_json_schema())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_params_basic() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            path: /etc/ssl/keystore.jks
            password: secret
            certificate: /etc/ssl/cert.pem
            private_key: /etc/ssl/key.pem
            alias: myapp
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.path, "/etc/ssl/keystore.jks");
        assert_eq!(params.password, "secret");
        assert_eq!(params.certificate, Some("/etc/ssl/cert.pem".to_string()));
        assert_eq!(params.private_key, Some("/etc/ssl/key.pem".to_string()));
        assert_eq!(params.alias, Some("myapp".to_string()));
        assert_eq!(params.state, None);
    }

    #[test]
    fn test_parse_params_with_state() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            path: /etc/ssl/keystore.jks
            password: secret
            alias: oldcert
            state: absent
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.state, Some(State::Absent));
    }

    #[test]
    fn test_parse_params_with_force() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            path: /etc/ssl/keystore.jks
            password: secret
            certificate: /etc/ssl/cert.pem
            private_key: /etc/ssl/key.pem
            alias: myapp
            force: true
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert!(params.force);
    }

    #[test]
    fn test_parse_params_with_ca_chain() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            path: /etc/ssl/keystore.jks
            password: secret
            certificate: /etc/ssl/cert.pem
            private_key: /etc/ssl/key.pem
            alias: myapp
            cacert_chain:
              - /etc/ssl/ca-intermediate.pem
              - /etc/ssl/ca-root.pem
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(
            params.cacert_chain,
            Some(vec![
                "/etc/ssl/ca-intermediate.pem".to_string(),
                "/etc/ssl/ca-root.pem".to_string()
            ])
        );
    }

    #[test]
    fn test_parse_params_with_pkcs12() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            path: /etc/ssl/keystore.jks
            password: secret
            pkcs12_path: /etc/ssl/bundle.p12
            pkcs12_password: pkcs12secret
            alias: myapp
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.pkcs12_path, Some("/etc/ssl/bundle.p12".to_string()));
        assert_eq!(params.pkcs12_password, Some("pkcs12secret".to_string()));
    }

    #[test]
    fn test_parse_params_unknown_field() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            path: /etc/ssl/keystore.jks
            password: secret
            unknown_field: value
            "#,
        )
        .unwrap();
        let error = parse_params::<Params>(yaml).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidData);
    }

    #[test]
    fn test_default_state() {
        let state: State = Default::default();
        assert_eq!(state, State::Present);
    }
}