std-mel 0.11.1

Mélodium standard 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
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! Secrets: creating them from locators, narrowing their policy, concealing and revealing values.
//!
//! A `Secret<T>` holds where its value comes from (such as `env:MELODIUM_SECRET_NAME` or
//! `file:PATH`) rather than the value itself, and is resolved only when an element reveals it.
//! Programs only get the environment variables whose name starts with `MELODIUM_SECRET_`.
//! Every reveal is checked against the secret policy and recorded as a debug event,
//! and refused or failed ones are also written to the log.
//!
//! The policy of a secret is set when it is created, and can only be narrowed afterwards.
//! By default, a secret stays on the engine that holds it, any element may reveal it,
//! and the plain `reveal` treatment may not. Secrets from the environment and from files
//! are never plainly revealed, whatever their policy.
//!
//! Secrets can be derived from other secrets (formatted, encoded) without revealing them:
//! a derived secret is computed when revealed, and gets the most restrictive combination
//! of the policies of the secrets it comes from.
//!
//! The functions derive and narrow secrets given as parameters; the treatments of
//! `std/secret/block` do the same for secrets received at runtime.
//!
//! When a program is distributed, secrets given to a distant engine follow their
//! transmission: `local` ones are refused, `reference` ones send only their locator,
//! resolved by the distant engine with its own sources (derived secrets have none),
//! and `value` ones send their value, over TLS only. The distant engine keeps the policy.
//!
//! Plaintext held by Mélodium (values of concealed secrets, revealed values, values masked
//! in logs, vault caches) is overwritten once not needed anymore, and before the process
//! exits, including on SIGINT, SIGTERM and SIGHUP. This is best effort, and does not cover:
//! - a process stopped by SIGKILL, the out-of-memory killer or a power loss;
//! - memory written to swap or to core dumps;
//! - copies made by libraries, child processes and remote services given the value;
//! - buffers of messages carrying a secret sent by value to a distant engine,
//! nor values made plain by `reveal`, which become ordinary data.

use crate::data::map::*;
use base64::Engine;
use melodium_core::common::descriptor::DataType;
use melodium_core::common::executive::{
    Secret as ExecutiveSecret, SecretDerivation, SecretOrigin, SecretPolicy, SecretReveal,
    SecretTransmission,
};
use melodium_core::*;
use melodium_macro::{mel_function, mel_treatment};
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use std::collections::HashMap;
use std::sync::Arc;
use zeroize::Zeroize;

pub mod block;

/// Secret read from the environment variable `variable` when revealed.
///
/// Only variables whose name starts with `MELODIUM_SECRET_` are given to programs.
#[mel_function]
pub fn from_environment(variable: string, name: string) -> Secret<string> {
    ExecutiveSecret::new(
        name,
        DataType::String,
        SecretPolicy::default(),
        SecretOrigin::Locator(format!("env:{variable}")),
    )
    .unwrap()
}

/// Secret read from the file at `path` when revealed.
///
/// One trailing newline is removed from the content.
#[mel_function]
pub fn from_file(path: string, name: string) -> Secret<string> {
    ExecutiveSecret::new(
        name,
        DataType::String,
        SecretPolicy::default(),
        SecretOrigin::Locator(format!("file:{path}")),
    )
    .unwrap()
}

/// Secret read from the file at `path` when revealed, as bytes.
///
/// The content is kept unchanged.
#[mel_function]
pub fn from_file_bytes(path: string, name: string) -> Secret<Vec<byte>> {
    ExecutiveSecret::new(
        name,
        DataType::Vec(Box::new(DataType::Byte)),
        SecretPolicy::default(),
        SecretOrigin::Locator(format!("file:{path}")),
    )
    .unwrap()
}

/// Secret resolved from `locator` when revealed, with an explicit policy.
///
/// - `locator`: `<scheme>:<path>`, such as `env:MELODIUM_SECRET_NAME`, `file:PATH`, or a scheme registered by a source model.
/// - `transmission`: where the secret may go when the program is distributed,
/// `local` (never leaves this engine), `reference` (only the locator is sent),
/// or `value` (the value is sent).
/// - `plain_reveal`: whether the plain `reveal` treatment may reveal it, never for
///   `env:` and `file:` secrets.
///
/// Gives none if `locator` or `transmission` are not valid.
#[mel_function(
    generic T ()
)]
pub fn locate(
    locator: string,
    name: string,
    transmission: string,
    plain_reveal: bool,
) -> Option<Secret<T>> {
    transmission
        .parse::<SecretTransmission>()
        .and_then(|transmission| {
            ExecutiveSecret::new(
                name,
                generics.get("T").unwrap().clone(),
                SecretPolicy {
                    transmission,
                    reveal: SecretReveal::Any,
                    plain_reveal,
                },
                SecretOrigin::Locator(locator),
            )
        })
        .ok()
}

/// Gives the name of a secret.
#[mel_function(
    generic T ()
)]
pub fn name(secret: Secret<T>) -> string {
    secret.name().to_string()
}

/// Keeps a secret on the engine that holds it, it is never sent to another one.
#[mel_function(
    generic T ()
)]
pub fn keep_local(secret: Secret<T>) -> Secret<T> {
    secret.narrow(&keep_local_narrowing())
}

/// Limits a secret to be sent to other engines by reference only, its value is never sent.
#[mel_function(
    generic T ()
)]
pub fn limit_to_reference(secret: Secret<T>) -> Secret<T> {
    secret.narrow(&limit_to_reference_narrowing())
}

/// Limits the elements that may reveal a secret to the ones in `elements`,
/// given as identifiers such as `std/secret::reveal`.
#[mel_function(
    generic T ()
)]
pub fn reveal_only_by(secret: Secret<T>, elements: Vec<string>) -> Secret<T> {
    secret.narrow(&reveal_only_by_narrowing(elements))
}

/// Forbids the plain `reveal` treatment to reveal a secret.
#[mel_function(
    generic T ()
)]
pub fn forbid_plain_reveal(secret: Secret<T>) -> Secret<T> {
    secret.narrow(&forbid_plain_reveal_narrowing())
}

// Narrowings, shared by the functions and the treatments of `block`.

pub(crate) fn keep_local_narrowing() -> SecretPolicy {
    SecretPolicy {
        transmission: SecretTransmission::Local,
        ..SecretPolicy::unrestricted()
    }
}

pub(crate) fn limit_to_reference_narrowing() -> SecretPolicy {
    SecretPolicy {
        transmission: SecretTransmission::Reference,
        ..SecretPolicy::unrestricted()
    }
}

pub(crate) fn reveal_only_by_narrowing(elements: Vec<String>) -> SecretPolicy {
    SecretPolicy {
        reveal: SecretReveal::Only(elements),
        ..SecretPolicy::unrestricted()
    }
}

pub(crate) fn forbid_plain_reveal_narrowing() -> SecretPolicy {
    SecretPolicy {
        plain_reveal: false,
        ..SecretPolicy::unrestricted()
    }
}

/// Gives the bytes of a string or bytes value.
fn value_bytes(value: &Value) -> Option<std::borrow::Cow<'_, [u8]>> {
    match value {
        Value::String(text) => Some(std::borrow::Cow::Borrowed(text.as_bytes())),
        Value::Packed(PackedArray::Byte(bytes)) | Value::Packed(PackedArray::U8(bytes)) => {
            Some(std::borrow::Cow::Borrowed(bytes.as_slice()))
        }
        Value::Vec(values) => values
            .iter()
            .map(|value| match value {
                Value::Byte(byte) | Value::U8(byte) => Some(*byte),
                _ => None,
            })
            .collect::<Option<Vec<u8>>>()
            .map(std::borrow::Cow::Owned),
        _ => None,
    }
}

/// Sorts the entries of `|format`: plain strings, names and values of string secrets,
/// and names of invalid entries.
fn format_entries(
    entries: HashMap<String, Value>,
) -> (
    HashMap<String, String>,
    Vec<String>,
    Vec<String>,
    Vec<ExecutiveSecret>,
) {
    let mut plain_entries = HashMap::new();
    let mut secret_entries = Vec::new();
    let mut invalid_entries = Vec::new();
    let mut inputs = Vec::new();
    for (entry, value) in entries {
        let value = match value {
            Value::Option(Some(value)) => *value,
            // An empty option counts as no entry.
            Value::Option(None) => continue,
            value => value,
        };
        match value {
            Value::String(text) => {
                plain_entries.insert(entry, text);
            }
            Value::Secret(secret) if secret.datatype() == &DataType::String => {
                secret_entries.push(entry);
                inputs.push(secret);
            }
            _ => invalid_entries.push(entry),
        }
    }
    (plain_entries, secret_entries, invalid_entries, inputs)
}

/// Template filled with plain strings and string secrets.
#[derive(Debug)]
struct FormatDerivation {
    template: String,
    plain_entries: HashMap<String, String>,
    /// Entries given by the input secrets, in their order.
    secret_entries: Vec<String>,
    /// Entries that are neither strings nor string secrets.
    invalid_entries: Vec<String>,
}

impl SecretDerivation for FormatDerivation {
    fn derive(&self, inputs: &[Value]) -> Result<Value, String> {
        if let Some(entry) = self.invalid_entries.first() {
            return Err(format!(
                "entry '{entry}' is neither a string nor a Secret<string>"
            ));
        }
        let mut entries = self.plain_entries.clone();
        let mut invalid = None;
        for (entry, value) in self.secret_entries.iter().zip(inputs) {
            match value {
                Value::String(text) => {
                    entries.insert(entry.clone(), text.clone());
                }
                _ => {
                    invalid = Some(format!("entry '{entry}' is not a string"));
                    break;
                }
            }
        }
        let formatted = match invalid {
            Some(invalid) => Err(invalid),
            None => Ok(strfmt::strfmt(&self.template, &entries)),
        };
        for (_, mut text) in entries.drain() {
            text.zeroize();
        }
        // strfmt errors may quote formatted content, so only their kind is kept.
        formatted?.map(Value::String).map_err(|err| match err {
            strfmt::FmtError::Invalid(_) => "the template is not valid".to_string(),
            strfmt::FmtError::KeyError(_) => {
                "the template uses an entry that is not given".to_string()
            }
            strfmt::FmtError::TypeError(_) => {
                "the template has an invalid placeholder format".to_string()
            }
        })
    }
}

#[derive(Debug)]
pub(crate) struct Base64Derivation;

impl SecretDerivation for Base64Derivation {
    fn derive(&self, inputs: &[Value]) -> Result<Value, String> {
        let bytes = inputs
            .first()
            .and_then(value_bytes)
            .ok_or_else(|| "base64 needs a string or bytes".to_string())?;
        let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
        if let std::borrow::Cow::Owned(mut bytes) = bytes {
            bytes.zeroize();
        }
        Ok(Value::String(encoded))
    }
}

/// Every character except the unreserved ones of RFC 3986 (`A-Z a-z 0-9 - . _ ~`).
const URL_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~');

#[derive(Debug)]
pub(crate) struct UrlEncodeDerivation;

impl SecretDerivation for UrlEncodeDerivation {
    fn derive(&self, inputs: &[Value]) -> Result<Value, String> {
        match inputs.first() {
            Some(Value::String(text)) => Ok(Value::String(
                utf8_percent_encode(text, URL_COMPONENT).to_string(),
            )),
            _ => Err("URL encoding needs a string".to_string()),
        }
    }
}

#[derive(Debug)]
pub(crate) struct BytesDerivation;

impl SecretDerivation for BytesDerivation {
    fn derive(&self, inputs: &[Value]) -> Result<Value, String> {
        match inputs.first() {
            Some(Value::String(text)) => Ok(Value::Packed(PackedArray::Byte(Arc::new(
                text.as_bytes().to_vec(),
            )))),
            _ => Err("bytes conversion needs a string".to_string()),
        }
    }
}

/// Secret made of `template` filled with `entries`, computed when revealed.
///
/// `template` contains braced placeholders, such as `"Bearer {token}"`.
/// `entries` maps placeholders to `string` or `Secret<string>` values, built with
/// `std/data/map::|map` and `|entry`. Values can also be in an option, as `|locate`
/// gives secrets: an empty option counts as no entry for its placeholder.
/// The secret is named `name`, and gets the most restrictive combination
/// of the policies of the secrets in `entries`.
///
/// Revealing fails if the template uses a placeholder with no entry, or if an entry
/// is neither a `string` nor a `Secret<string>`.
#[mel_function]
pub fn format(template: string, entries: Map, name: string) -> Secret<string> {
    formatted(template, entries.map, name)
}

/// Secret made of `template` filled with `entries`, shared by `|format` and `block::format`.
pub(crate) fn formatted(
    template: String,
    entries: HashMap<String, Value>,
    name: String,
) -> ExecutiveSecret {
    let (plain_entries, secret_entries, invalid_entries, inputs) = format_entries(entries);
    ExecutiveSecret::derive(
        name,
        DataType::String,
        inputs,
        Arc::new(FormatDerivation {
            template,
            plain_entries,
            secret_entries,
            invalid_entries,
        }),
    )
    .unwrap()
}

/// Secret made of the base64 encoding (standard, padded) of a string secret, computed when revealed.
///
/// Such as the credentials of HTTP Basic authentication: `|base64(|format("{user}:{password}", ...), ...)`.
#[mel_function]
pub fn base64(secret: Secret<string>, name: string) -> Secret<string> {
    derived(name, DataType::String, secret, Arc::new(Base64Derivation))
}

/// Secret made of the base64 encoding (standard, padded) of a bytes secret, computed when revealed.
#[mel_function]
pub fn base64_bytes(secret: Secret<Vec<byte>>, name: string) -> Secret<string> {
    derived(name, DataType::String, secret, Arc::new(Base64Derivation))
}

/// Secret made of the URL encoding of a string secret, computed when revealed.
///
/// Every character except `A-Z a-z 0-9 - . _ ~` is percent-encoded,
/// so the result fits in any URL part, such as credentials: `https://{user}:{password}@host`.
#[mel_function]
pub fn url_encode(secret: Secret<string>, name: string) -> Secret<string> {
    derived(
        name,
        DataType::String,
        secret,
        Arc::new(UrlEncodeDerivation),
    )
}

/// Secret made of the UTF-8 bytes of a string secret, computed when revealed.
#[mel_function]
pub fn to_bytes(secret: Secret<string>, name: string) -> Secret<Vec<byte>> {
    derived(
        name,
        DataType::Vec(Box::new(DataType::Byte)),
        secret,
        Arc::new(BytesDerivation),
    )
}

/// Secret derived from `secret` by `derivation`, shared by the functions and `block`.
pub(crate) fn derived(
    name: String,
    datatype: DataType,
    secret: ExecutiveSecret,
    derivation: Arc<dyn SecretDerivation>,
) -> ExecutiveSecret {
    ExecutiveSecret::derive(name, datatype, vec![secret], derivation).unwrap()
}

/// Conceals a value into a secret.
///
/// Intended for values only known at runtime, such as a token given by an API response.
/// The secret is named `name`, its policy is given by `transmission` (`local`, `reference` or `value`)
/// and `plain_reveal` (whether the plain `reveal` treatment may reveal it).
///
/// If the secret cannot be created, `failed` is emitted and `error` contains the reason.
#[mel_treatment(
    generic T ()
    input value Block<T>
    output secret Block<Secret<T>>
    output failed Block<void>
    output error Block<string>
    default transmission "local"
    default plain_reveal false
)]
pub async fn conceal(name: string, transmission: string, plain_reveal: bool) {
    if let Ok(content) = value.recv_one().await {
        let concealed = transmission
            .parse::<SecretTransmission>()
            .and_then(|transmission| {
                ExecutiveSecret::new(
                    name,
                    T,
                    SecretPolicy {
                        transmission,
                        reveal: SecretReveal::Any,
                        plain_reveal,
                    },
                    SecretOrigin::Inline(content),
                )
            });
        match concealed {
            Ok(concealed) => {
                let _ = secret.send_one(Value::Secret(concealed)).await;
            }
            Err(err) => {
                let _ = failed.send_one(().into()).await;
                let _ = error.send_one(err.to_string().into()).await;
            }
        }
    }
}

/// Reveals the value of a secret, as a plain value.
///
/// The secret policy must allow plain reveal, which is not the default. Secrets from the
/// environment and from files (`env:`, `file:`) are never plainly revealed.
/// The access is recorded as a debug event, and a refused or failed one is also written to the log.
///
/// If the value cannot be revealed, `failed` is emitted and `error` contains the reason.
#[mel_treatment(
    generic T ()
    input secret Block<Secret<T>>
    output value Block<T>
    output failed Block<void>
    output error Block<string>
    secrets_access
)]
pub async fn reveal() {
    if let Ok(Value::Secret(concealed)) = secret.recv_one().await {
        match secrets_access
            .reveal_plainly(&concealed, |content| content.clone())
            .await
        {
            Ok(content) => {
                let _ = value.send_one(content).await;
            }
            Err(err) => {
                let _ = failed.send_one(().into()).await;
                let _ = error.send_one(err.to_string().into()).await;
            }
        }
    }
}

/// Searches the values revealed by the engine in data, cutting the data when one is found.
///
/// The bytes received through `data` are given through `scanned`, unless they hold a value
/// the engine revealed, as is, in base64, URL-encoded, or as bytes when it is not text, such
/// as before uploading files that would not be masked anymore once they left the engine.
/// The last bytes received are held until the next ones come, as they could start a value:
/// nothing of a value found is given.
///
/// Once `data` ends without any value found, the bytes held are given and `completed` is
/// emitted. When a value is found, `scanned` and `data` are closed, `failed` is emitted, and
/// `error` names the secret the value comes from, never the value.
/// `finished` is emitted in both cases.
///
/// ⚠️ `scanned` ends in both cases: only `completed` tells that all the data was given, and
/// that it holds no revealed value.
///
/// Values revealed while the data goes through are searched from then on. Only the values
/// revealed by this engine are known, not those revealed by distant ones.
///
/// ```mermaid
/// graph LR
///     T("scan()")
///     B["… 🟦 🟦 🟦"] -->|data| T
///
///     T -->|scanned| O["… 🟦 🟦 🟦"]
///     T -->|completed| C["〈🟩〉"]
///     T -->|failed| F["〈🟥〉"]
///
///     style B fill:#ffffff,stroke:#ffffff
///     style O fill:#ffffff,stroke:#ffffff
///     style C fill:#ffffff,stroke:#ffffff
///     style F fill:#ffffff,stroke:#ffffff
/// ```
#[mel_treatment(
    input data Stream<byte>
    output scanned Stream<byte>
    output completed Block<void>
    output failed Block<void>
    output finished Block<void>
    output error Block<string>
    secrets_access
)]
pub async fn scan() {
    let mut search = secrets_access.revealed_scan();
    let mut held = Hold::default();
    let mut found = None;
    let mut given = true;

    while let Ok(mut bytes) = data.recv_many_as::<u8>().await {
        found = search.scan(&bytes);
        if found.is_some() {
            bytes.zeroize();
            break;
        }
        let released = held.push(bytes, search.overlap());
        if !released.is_empty()
            && scanned
                .send_many(TransmissionValue::Byte(released))
                .await
                .is_err()
        {
            given = false;
            break;
        }
    }

    match found {
        Some(name) => {
            data.close();
            scanned.close().await;
            let _ = failed.send_one(().into()).await;
            let _ = error
                .send_one(format!("the data holds a value revealed from secret '{name}'").into())
                .await;
        }
        None if given => {
            let rest = held.take();
            if rest.is_empty()
                || scanned
                    .send_many(TransmissionValue::Byte(rest))
                    .await
                    .is_ok()
            {
                scanned.close().await;
                let _ = completed.send_one(().into()).await;
            }
        }
        None => {
            data.close();
        }
    }
    let _ = finished.send_one(().into()).await;
}

/// Bytes held back by `scan`, as they could start a revealed value, overwritten once dropped.
#[derive(Default)]
struct Hold(VecDeque<u8>);

impl Hold {
    /// Adds `bytes`, and gives the bytes that cannot start a value anymore, keeping the last
    /// `overlap` ones.
    fn push(&mut self, mut bytes: Vec<u8>, overlap: usize) -> VecDeque<u8> {
        self.0.extend(bytes.iter());
        bytes.zeroize();
        let release = self.0.len().saturating_sub(overlap);
        self.0.drain(..release).collect()
    }

    /// Gives every byte held.
    fn take(&mut self) -> VecDeque<u8> {
        core::mem::take(&mut self.0)
    }
}

impl Drop for Hold {
    fn drop(&mut self) {
        self.0.iter_mut().for_each(|byte| *byte = 0);
    }
}

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

    const SENTINEL: &str = "s3cr3t:value/@";

    #[test]
    fn hold_keeps_what_could_start_a_value() {
        let mut hold = Hold::default();
        assert!(hold.push(b"abc".to_vec(), 5).is_empty());
        assert_eq!(
            hold.push(b"defgh".to_vec(), 5),
            VecDeque::from(b"abc".to_vec())
        );
        assert_eq!(
            hold.push(b"ij".to_vec(), 0),
            VecDeque::from(b"defghij".to_vec())
        );
        assert!(hold.take().is_empty());
        assert_eq!(hold.push(b"klm".to_vec(), 2), VecDeque::from(b"k".to_vec()));
        assert_eq!(hold.take(), VecDeque::from(b"lm".to_vec()));
    }

    #[test]
    fn format_fills_plain_and_secret_entries() {
        let derivation = FormatDerivation {
            template: "{scheme}://{user}:{password}@host".to_string(),
            plain_entries: HashMap::from([
                ("scheme".to_string(), "https".to_string()),
                ("user".to_string(), "ci".to_string()),
            ]),
            secret_entries: vec!["password".to_string()],
            invalid_entries: Vec::new(),
        };
        assert_eq!(
            derivation.derive(&[Value::String(SENTINEL.to_string())]),
            Ok(Value::String(format!("https://ci:{SENTINEL}@host")))
        );
    }

    #[test]
    fn format_takes_entries_in_options() {
        let secret = ExecutiveSecret::from_locator("env:TOKEN", DataType::String).unwrap();
        let entries = Map::new_with(HashMap::from([
            (
                "token".to_string(),
                Value::Option(Some(Box::new(Value::Secret(secret.clone())))),
            ),
            (
                "user".to_string(),
                Value::Option(Some(Box::new(Value::String("ci".to_string())))),
            ),
            ("none".to_string(), Value::Option(None)),
            (
                "count".to_string(),
                Value::Option(Some(Box::new(Value::U64(3)))),
            ),
        ]));
        let (plain, secret_entries, invalid, inputs) = format_entries(entries.map);
        assert_eq!(
            plain,
            HashMap::from([("user".to_string(), "ci".to_string())])
        );
        assert_eq!(secret_entries, vec!["token".to_string()]);
        // The empty option is no entry, the other one holds neither a string nor a secret.
        assert_eq!(invalid, vec!["count".to_string()]);
        assert_eq!(inputs, vec![secret]);
    }

    #[test]
    fn format_takes_empty_options_as_no_entries() {
        let (plain_entries, secret_entries, invalid_entries, _) = format_entries(HashMap::from([
            ("user".to_string(), Value::String("ci".to_string())),
            ("none".to_string(), Value::Option(None)),
        ]));
        let derivation = |template: &str| FormatDerivation {
            template: template.to_string(),
            plain_entries: plain_entries.clone(),
            secret_entries: secret_entries.clone(),
            invalid_entries: invalid_entries.clone(),
        };
        assert_eq!(
            derivation("{user}").derive(&[]),
            Ok(Value::String("ci".to_string()))
        );
        assert_eq!(
            derivation("{user}:{none}").derive(&[]),
            Err("the template uses an entry that is not given".to_string())
        );
    }

    #[test]
    fn format_errors_never_show_values() {
        let missing = FormatDerivation {
            template: "{missing} {password}".to_string(),
            plain_entries: HashMap::new(),
            secret_entries: vec!["password".to_string()],
            invalid_entries: Vec::new(),
        };
        let invalid_format = FormatDerivation {
            template: "{password:>.3e}".to_string(),
            plain_entries: HashMap::new(),
            secret_entries: vec!["password".to_string()],
            invalid_entries: Vec::new(),
        };
        let invalid_entry = FormatDerivation {
            template: "{password}".to_string(),
            plain_entries: HashMap::new(),
            secret_entries: vec!["password".to_string()],
            invalid_entries: vec!["count".to_string()],
        };
        for derivation in [missing, invalid_format, invalid_entry] {
            let error = derivation
                .derive(&[Value::String(SENTINEL.to_string())])
                .unwrap_err();
            assert!(!error.contains(SENTINEL), "leaked in {error}");
        }
    }

    #[test]
    fn encodings() {
        let value = Value::String(SENTINEL.to_string());
        assert_eq!(
            UrlEncodeDerivation.derive(&[value.clone()]),
            Ok(Value::String("s3cr3t%3Avalue%2F%40".to_string()))
        );
        assert_eq!(
            UrlEncodeDerivation.derive(&[Value::String("aZ09-._~ é".to_string())]),
            Ok(Value::String("aZ09-._~%20%C3%A9".to_string()))
        );
        assert_eq!(
            Base64Derivation.derive(&[Value::String("ci:password".to_string())]),
            Ok(Value::String("Y2k6cGFzc3dvcmQ=".to_string()))
        );
        let bytes = BytesDerivation.derive(&[value]).unwrap();
        assert_eq!(
            bytes,
            Value::Packed(PackedArray::Byte(Arc::new(SENTINEL.as_bytes().to_vec())))
        );
        assert_eq!(bytes.datatype(), DataType::Vec(Box::new(DataType::Byte)));
        assert_eq!(
            Base64Derivation.derive(&[Value::Vec(vec![Value::Byte(0xff), Value::Byte(0)])]),
            Ok(Value::String("/wA=".to_string()))
        );
        assert!(Base64Derivation.derive(&[Value::U64(1)]).is_err());
    }
}