aion-package 0.26.0

Archive validation, content hashing, and namespacing for Aion workflow packages.
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
//! The render's own rules, exercised on inputs this module constructs.

use std::collections::BTreeMap;

use serde_json::json;

use super::{
    ArgumentValue, ArgvSlot, CommandParameterContract, DeclaredCommandContract, EnvBindingContract,
    FillPiece, FillTemplate, RenderError,
};

/// What a test returns. Every fallible step is carried rather than unwrapped,
/// because the workspace denies panicking accessors in test code as firmly as
/// in library code.
type TestResult = Result<(), Box<dyn std::error::Error>>;

fn hole(parameter: &str) -> FillTemplate {
    FillTemplate {
        pieces: vec![FillPiece::Hole {
            parameter: parameter.to_owned(),
        }],
    }
}

fn mixed(prefix: &str, parameter: &str, suffix: &str) -> FillTemplate {
    FillTemplate {
        pieces: vec![
            FillPiece::Literal {
                text: prefix.to_owned(),
            },
            FillPiece::Hole {
                parameter: parameter.to_owned(),
            },
            FillPiece::Literal {
                text: suffix.to_owned(),
            },
        ],
    }
}

fn slot(fill: FillTemplate, label: &str, admits_leading_dash: bool) -> ArgvSlot {
    ArgvSlot {
        fill,
        label: label.to_owned(),
        admits_leading_dash,
    }
}

fn parameter(name: &str, list: bool, default: Option<FillTemplate>) -> CommandParameterContract {
    CommandParameterContract {
        name: name.to_owned(),
        list,
        default,
    }
}

fn contract(
    parameters: Vec<CommandParameterContract>,
    program: &[&str],
    args: Vec<ArgvSlot>,
) -> DeclaredCommandContract {
    DeclaredCommandContract {
        name: "probe".to_owned(),
        parameters,
        program: program.iter().map(|word| (*word).to_owned()).collect(),
        args,
        env: Vec::new(),
        cwd: None,
        hardened_path: None,
        timeout_ms: None,
        timeout_owner: None,
    }
}

fn supplied(pairs: &[(&str, ArgumentValue)]) -> BTreeMap<String, ArgumentValue> {
    pairs
        .iter()
        .map(|(name, value)| ((*name).to_owned(), value.clone()))
        .collect()
}

#[test]
fn a_value_carrying_shell_metacharacters_arrives_as_one_argv_element() -> TestResult {
    let command = contract(
        vec![parameter("value", false, None)],
        &["echo"],
        vec![slot(hole("value"), "value", true)],
    );
    let rendered = command.render(&supplied(&[(
        "value",
        ArgumentValue::scalar("$(boom); rm -rf /"),
    )]))?;
    assert_eq!(
        rendered.argv,
        vec!["echo".to_owned(), "$(boom); rm -rf /".to_owned()],
        "a hostile value must be one inert element, never re-split"
    );
    Ok(())
}

#[test]
fn a_list_alone_in_a_slot_becomes_one_element_per_item() -> TestResult {
    let command = contract(
        vec![parameter("paths", true, None)],
        &["git", "add"],
        vec![slot(hole("paths"), "paths", true)],
    );
    let rendered = command.render(&supplied(&[(
        "paths",
        ArgumentValue::list(["a.rs", "b rs", "c.rs"]),
    )]))?;
    assert_eq!(
        rendered.argv,
        vec!["git", "add", "a.rs", "b rs", "c.rs"]
            .into_iter()
            .map(str::to_owned)
            .collect::<Vec<_>>()
    );
    Ok(())
}

#[test]
fn a_default_resolves_against_the_parameters_declared_before_it() -> TestResult {
    let command = contract(
        vec![
            parameter("base", false, None),
            parameter("range", false, Some(mixed("", "base", "..HEAD"))),
        ],
        &["git", "log"],
        vec![slot(hole("range"), "range", true)],
    );
    let rendered = command.render(&supplied(&[("base", ArgumentValue::scalar("main"))]))?;
    assert_eq!(rendered.argv, vec!["git", "log", "main..HEAD"]);
    Ok(())
}

#[test]
fn a_supplied_value_beats_the_declared_default() -> TestResult {
    let command = contract(
        vec![parameter(
            "who",
            false,
            Some(FillTemplate::literal("nobody")),
        )],
        &["echo"],
        vec![slot(hole("who"), "who", true)],
    );
    let rendered = command.render(&supplied(&[("who", ArgumentValue::scalar("world"))]))?;
    assert_eq!(rendered.argv, vec!["echo", "world"]);
    Ok(())
}

#[test]
fn a_parameter_with_no_value_and_no_default_refuses_by_name() {
    let command = contract(
        vec![parameter("who", false, None)],
        &["echo"],
        vec![slot(hole("who"), "who", true)],
    );
    assert_eq!(
        command.render(&BTreeMap::new()),
        Err(RenderError::ArgumentMissing {
            command: "probe".to_owned(),
            parameter: "who".to_owned(),
        })
    );
}

#[test]
fn a_value_the_command_does_not_declare_refuses_by_name() {
    let command = contract(Vec::new(), &["echo"], Vec::new());
    assert_eq!(
        command.render(&supplied(&[("stray", ArgumentValue::scalar("x"))])),
        Err(RenderError::ArgumentUndeclared {
            command: "probe".to_owned(),
            parameter: "stray".to_owned(),
        })
    );
}

#[test]
fn a_shape_mismatch_refuses_naming_both_shapes() {
    let command = contract(
        vec![parameter("paths", true, None)],
        &["git"],
        vec![slot(hole("paths"), "paths", true)],
    );
    assert_eq!(
        command.render(&supplied(&[("paths", ArgumentValue::scalar("a.rs"))])),
        Err(RenderError::ArgumentTypeMismatch {
            command: "probe".to_owned(),
            parameter: "paths".to_owned(),
            observed: "a.rs".to_owned(),
            declared: "list",
            supplied: "single value",
        })
    );
}

#[test]
fn a_leading_dash_operand_refuses_where_the_program_still_reads_options() {
    let command = contract(
        vec![parameter("name", false, None)],
        &["git", "tag"],
        vec![slot(hole("name"), "name", false)],
    );
    let Err(error) = command.render(&supplied(&[("name", ArgumentValue::scalar("-n"))])) else {
        panic_free_failure("a leading-dash operand must refuse");
        return;
    };
    assert_eq!(
        error,
        RenderError::LeadingDashOperand {
            command: "probe".to_owned(),
            argument: "name".to_owned(),
            element: "-n".to_owned(),
            marker: "--",
        }
    );
}

/// A NAMED argument's value is not dash-guarded, and must not be: an author
/// writing `arg "--max-count": String = "{{n}}"` wrote a flag and its value,
/// and the flag itself begins with a dash. The guard is a property of an
/// OPERAND standing where the program still reads options — nowhere else — and
/// this pins that the two-slot modelling of a named argument did not widen it.
#[test]
fn a_named_arguments_value_is_not_dash_guarded() -> TestResult {
    let command = contract(
        vec![parameter("count", false, None)],
        &["grep"],
        vec![
            slot(FillTemplate::literal("--max-count"), "--max-count", true),
            slot(hole("count"), "--max-count", true),
        ],
    );
    let rendered = command.render(&supplied(&[("count", ArgumentValue::scalar("-3"))]))?;
    assert_eq!(rendered.argv, vec!["grep", "--max-count", "-3"]);
    Ok(())
}

#[test]
fn the_same_bytes_pass_once_the_end_of_options_marker_stands_before_them() -> TestResult {
    let command = contract(
        vec![parameter("name", false, None)],
        &["git", "tag"],
        vec![
            slot(FillTemplate::literal("--"), "--", true),
            slot(hole("name"), "name", true),
        ],
    );
    let rendered = command.render(&supplied(&[("name", ArgumentValue::scalar("-n"))]))?;
    assert_eq!(rendered.argv, vec!["git", "tag", "--", "-n"]);
    Ok(())
}

#[test]
fn env_and_path_bindings_render_from_the_same_bound_values() -> TestResult {
    let mut command = contract(vec![parameter("root", false, None)], &["true"], Vec::new());
    command.env = vec![EnvBindingContract {
        name: "PROJECT_ROOT".to_owned(),
        value: hole("root"),
    }];
    command.hardened_path = Some(mixed("", "root", "/bin"));
    let rendered = command.render(&supplied(&[("root", ArgumentValue::scalar("/srv/app"))]))?;
    assert_eq!(
        rendered.env,
        vec![("PROJECT_ROOT".to_owned(), "/srv/app".to_owned())]
    );
    assert_eq!(rendered.hardened_path, Some("/srv/app/bin".to_owned()));
    Ok(())
}

#[test]
fn json_values_take_their_one_obvious_argument_form() -> TestResult {
    assert_eq!(
        ArgumentValue::from_json("p", &json!("text"))?,
        ArgumentValue::scalar("text")
    );
    assert_eq!(
        ArgumentValue::from_json("p", &json!(7))?,
        ArgumentValue::scalar("7")
    );
    assert_eq!(
        ArgumentValue::from_json("p", &json!(true))?,
        ArgumentValue::scalar("true")
    );
    assert_eq!(
        ArgumentValue::from_json("p", &json!(["a", 2]))?,
        ArgumentValue::list(["a", "2"])
    );
    Ok(())
}

#[test]
fn json_values_with_no_argument_form_refuse_by_name() {
    for (value, kind) in [
        (json!(null), "null"),
        (json!({ "a": 1 }), "an object"),
        (json!([[1]]), "a nested array"),
    ] {
        assert_eq!(
            ArgumentValue::from_json("p", &value),
            Err(RenderError::UnrepresentableValue {
                parameter: "p".to_owned(),
                kind,
            })
        );
    }
    assert_eq!(
        ArgumentValue::from_json("p", &json!("has\0nul")),
        Err(RenderError::InteriorNul {
            parameter: "p".to_owned(),
        })
    );
}

#[test]
fn the_contract_round_trips_through_json() -> TestResult {
    let mut command = contract(
        vec![parameter(
            "who",
            false,
            Some(FillTemplate::literal("world")),
        )],
        &["echo"],
        vec![slot(mixed("hello ", "who", "!"), "greeting", false)],
    );
    command.cwd = Some("{workspace_root}".to_owned());
    command.timeout_ms = Some(30_000);
    command.timeout_owner = Some("release".to_owned());
    let encoded = serde_json::to_string(&command)?;
    let decoded: DeclaredCommandContract = serde_json::from_str(&encoded)?;
    assert_eq!(decoded, command);
    Ok(())
}

/// Every field of the emitted form is executable authority, so no two
/// distinct commands may hash alike — and the CAPTURE is authority too: the
/// same argv returning a decoded record and returning a string are two
/// different promises to a caller.
#[test]
fn every_distinguishing_edit_moves_the_identity_bytes() -> TestResult {
    use crate::contract::{ActionBodyContract, ActionContract, CommandBodyCapture};

    let base = contract(
        vec![parameter("who", false, None)],
        &["echo"],
        vec![slot(hole("who"), "who", true)],
    );
    let action = |capture: CommandBodyCapture, command: DeclaredCommandContract| ActionContract {
        name: "greet".to_owned(),
        input_schema: serde_json::json!({}),
        output_schema: serde_json::json!({}),
        node: None,
        timeout: None,
        retry: None,
        advisory: false,
        agent: false,
        body: Some(ActionBodyContract::Command {
            capture,
            command: Box::new(command),
        }),
    };

    let mut seen = std::collections::BTreeSet::new();
    let mut record = |contract: &ActionContract| -> Result<(), Box<dyn std::error::Error>> {
        let mut bytes = Vec::new();
        crate::declared_command::encode_identity(
            &mut bytes,
            match contract.body.as_ref() {
                Some(ActionBodyContract::Command { command, .. }) => command.as_ref(),
                _ => return Err("the fixture carries a command body".into()),
            },
        );
        if let Some(ActionBodyContract::Command { capture, .. }) = contract.body.as_ref() {
            bytes.push(u8::from(matches!(capture, CommandBodyCapture::Json)));
        }
        assert!(seen.insert(bytes), "two distinct commands hashed alike");
        Ok(())
    };

    record(&action(CommandBodyCapture::Text, base.clone()))?;
    // The capture alone.
    record(&action(CommandBodyCapture::Json, base.clone()))?;
    // The program.
    let mut edited = base.clone();
    edited.program = vec!["printf".to_owned()];
    record(&action(CommandBodyCapture::Text, edited))?;
    // The argument list.
    let mut edited = base.clone();
    edited
        .args
        .push(slot(FillTemplate::literal("--"), "--", true));
    record(&action(CommandBodyCapture::Text, edited))?;
    // The order of the argument list: `--` before an operand and after it are
    // different commands.
    let mut edited = base.clone();
    edited
        .args
        .insert(0, slot(FillTemplate::literal("--"), "--", true));
    record(&action(CommandBodyCapture::Text, edited))?;
    // The dash-guard fact.
    let mut edited = base.clone();
    edited.args[0].admits_leading_dash = false;
    record(&action(CommandBodyCapture::Text, edited))?;
    // The environment.
    let mut edited = base.clone();
    edited.env = vec![EnvBindingContract {
        name: "A".to_owned(),
        value: FillTemplate::literal("1"),
    }];
    record(&action(CommandBodyCapture::Text, edited))?;
    // The working directory.
    let mut edited = base.clone();
    edited.cwd = Some("/srv".to_owned());
    record(&action(CommandBodyCapture::Text, edited))?;
    // The hardened PATH.
    let mut edited = base.clone();
    edited.hardened_path = Some(FillTemplate::literal("/usr/bin"));
    record(&action(CommandBodyCapture::Text, edited))?;
    // The ceiling, and separately its owner.
    let mut edited = base.clone();
    edited.timeout_ms = Some(1_000);
    record(&action(CommandBodyCapture::Text, edited))?;
    let mut edited = base.clone();
    edited.timeout_owner = Some("ops".to_owned());
    record(&action(CommandBodyCapture::Text, edited))?;
    // A parameter's list-ness, and its default.
    let mut edited = base.clone();
    edited.parameters[0].list = true;
    record(&action(CommandBodyCapture::Text, edited))?;
    let mut edited = base;
    edited.parameters[0].default = Some(FillTemplate::literal("world"));
    record(&action(CommandBodyCapture::Text, edited))?;
    Ok(())
}

/// Fails the calling test without a panicking accessor.
fn panic_free_failure(reason: &str) {
    assert!(reason.is_empty(), "{reason}");
}