assay-lua 0.17.6

General-purpose enhanced Lua runtime. Batteries-included scripting, automation, and web services.
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
//! apt builtin — wraps apt-get/dpkg-query for use by the package manager.
//!
//! Functions are simple shell wrappers; the parsers (dpkg-query and
//! `apt list --upgradable -a` output) are pure-string transforms exposed via
//! `apt._parse_dpkg_lines` / `apt._parse_upgradable_lines` for unit testing.
//!
//! Operations that mutate system state (install, remove, update, add_source
//! against /etc paths) require root and are tested manually against a
//! throwaway nspawn machine in a downstream consumer's smoke tests.

use mlua::{Lua, Table};
use rand::RngExt;

/// Build a process-and-time-unique temp suffix. PID alone is predictable
/// (a co-located unprivileged process can pre-create symlinks at the
/// expected path); 64 random bits make pre-creation impractical.
fn tmp_suffix() -> String {
    format!("{:016x}", rand::rng().random::<u64>())
}

pub fn register_apt(lua: &Lua) -> mlua::Result<()> {
    let t = lua.create_table()?;

    // ── parsers (pure, exported for tests) ────────────────────────────────

    t.set("_parse_dpkg_lines", lua.create_function(parse_dpkg_lines)?)?;
    t.set(
        "_parse_upgradable_lines",
        lua.create_function(parse_upgradable_lines)?,
    )?;

    // ── query / list_installed / list_upgradable ──────────────────────────

    t.set(
        "query",
        lua.create_async_function(|lua, name: String| async move {
            let (status, stdout, _stderr) = run_command(
                "dpkg-query",
                &["-W", "-f=${Package}\t${Version}\t${Status}\n", &name],
            )
            .await?;
            let result = lua.create_table()?;
            if status != 0 {
                result.set("installed", false)?;
                result.set("version", mlua::Value::Nil)?;
                return Ok(result);
            }
            let parsed = parse_dpkg_lines(&lua, stdout)?;
            if let Ok(entry) = parsed.get::<Table>(name.clone()) {
                let installed: bool = entry.get("installed")?;
                let version: String = entry.get("version")?;
                result.set("installed", installed)?;
                if installed {
                    result.set("version", version)?;
                } else {
                    result.set("version", mlua::Value::Nil)?;
                }
            } else {
                result.set("installed", false)?;
                result.set("version", mlua::Value::Nil)?;
            }
            Ok(result)
        })?,
    )?;

    t.set(
        "list_installed",
        lua.create_async_function(|lua, ()| async move {
            let (status, stdout, stderr) = run_command(
                "dpkg-query",
                &["-W", "-f=${Package}\t${Version}\t${Status}\n"],
            )
            .await?;
            if status != 0 {
                return Err(mlua::Error::runtime(format!(
                    "apt.list_installed: dpkg-query exit {status}: {stderr}"
                )));
            }
            parse_dpkg_lines(&lua, stdout)
        })?,
    )?;

    t.set(
        "list_upgradable",
        lua.create_async_function(|lua, ()| async move {
            // Match list_installed's error semantics: surface non-zero apt
            // exits to the caller instead of silently returning [].
            let (status, stdout, stderr) =
                run_command("apt", &["list", "--upgradable", "-a"]).await?;
            if status != 0 {
                return Err(mlua::Error::runtime(format!(
                    "apt.list_upgradable: apt list exit {status}: {stderr}"
                )));
            }
            parse_upgradable_lines(&lua, stdout)
        })?,
    )?;

    // ── source management ─────────────────────────────────────────────────

    t.set("add_source", lua.create_function(add_source)?)?;

    // ── apt-get wrappers ──────────────────────────────────────────────────

    t.set(
        "update",
        lua.create_async_function(|lua, ()| async move {
            let (status, stdout, stderr) = run_command("apt-get", &["update"]).await?;
            let r = lua.create_table()?;
            r.set("status", status as i64)?;
            r.set("stdout", stdout)?;
            r.set("stderr", stderr)?;
            // Timeouts bubble up as mlua errors from run_command, not as a
            // table field — so the timed_out flag isn't part of this shape.
            Ok(r)
        })?,
    )?;

    t.set(
        "install",
        lua.create_async_function(|lua, opts: Table| async move {
            let names_table: Table = opts.get("names")?;
            let only_upgrade: bool = opts.get::<Option<bool>>("only_upgrade")?.unwrap_or(false);
            let mut names: Vec<String> = Vec::new();
            for v in names_table.sequence_values::<String>() {
                names.push(v?);
            }
            if names.is_empty() {
                return Err(mlua::Error::runtime("apt.install: names array is empty"));
            }
            let mut args: Vec<String> = vec![
                "install".into(),
                "-y".into(),
                "--no-install-recommends".into(),
            ];
            if only_upgrade {
                args.push("--only-upgrade".into());
            }
            // `--` ends option parsing — anything after is treated as a package
            // name even if it starts with `-`. Defends against caller-supplied
            // names like "--allow-unauthenticated" injecting apt-get flags.
            args.push("--".into());
            for n in &names {
                args.push(n.clone());
            }
            let args_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
            let (status, stdout, stderr) = run_command("apt-get", &args_refs).await?;
            let r = lua.create_table()?;
            r.set("status", status as i64)?;
            r.set("stdout", stdout)?;
            r.set("stderr", stderr)?;
            // Timeouts bubble up as mlua errors from run_command, not as a
            // table field — so the timed_out flag isn't part of this shape.
            Ok(r)
        })?,
    )?;

    t.set(
        "remove",
        lua.create_async_function(|lua, opts: Table| async move {
            let names_table: Table = opts.get("names")?;
            let mut names: Vec<String> = Vec::new();
            for v in names_table.sequence_values::<String>() {
                names.push(v?);
            }
            if names.is_empty() {
                return Err(mlua::Error::runtime("apt.remove: names array is empty"));
            }
            let mut args: Vec<String> = vec!["remove".into(), "-y".into()];
            args.push("--".into());
            for n in &names {
                args.push(n.clone());
            }
            let args_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
            let (status, stdout, stderr) = run_command("apt-get", &args_refs).await?;
            let r = lua.create_table()?;
            r.set("status", status as i64)?;
            r.set("stdout", stdout)?;
            r.set("stderr", stderr)?;
            // Timeouts bubble up as mlua errors from run_command, not as a
            // table field — so the timed_out flag isn't part of this shape.
            Ok(r)
        })?,
    )?;

    lua.globals().set("apt", t)?;
    Ok(())
}

// ── Parsers ──────────────────────────────────────────────────────────────────

/// Parse `dpkg-query -W -f='${Package}\t${Version}\t${Status}\n'` output.
/// Returns a table keyed by package name with { version=string, installed=bool }.
fn parse_dpkg_lines(lua: &Lua, input: String) -> mlua::Result<Table> {
    let out = lua.create_table()?;
    for line in input.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let parts: Vec<&str> = line.splitn(3, '\t').collect();
        if parts.len() < 3 {
            continue;
        }
        let name = parts[0].trim();
        let version = parts[1].trim();
        let status = parts[2].trim();
        // dpkg Status format: "<wanted> <flag> <status>"; we want the third field == "installed".
        let installed = status
            .split_whitespace()
            .nth(2)
            .map(|s| s == "installed")
            .unwrap_or(false);

        let entry = lua.create_table()?;
        entry.set("version", version)?;
        entry.set("installed", installed)?;
        out.set(name, entry)?;
    }
    Ok(out)
}

/// Parse `apt list --upgradable -a` output. Returns array of
/// { name=string, current=string, candidate=string, suite=string }.
fn parse_upgradable_lines(lua: &Lua, input: String) -> mlua::Result<Table> {
    let out = lua.create_table()?;
    let mut idx = 1usize;
    for line in input.lines() {
        let line = line.trim();
        if line.is_empty()
            || line.starts_with("Listing...")
            || line.starts_with("WARNING:")
            || line.starts_with("N:")
        {
            continue;
        }
        // Format: "name/suite candidate arch [upgradable from: current]"
        let upgradable_marker = "[upgradable from:";
        if !line.contains(upgradable_marker) {
            continue;
        }
        let (head, tail) = match line.split_once(upgradable_marker) {
            Some(p) => p,
            None => continue,
        };
        let head_parts: Vec<&str> = head.split_whitespace().collect();
        if head_parts.len() < 2 {
            continue;
        }
        let name_suite = head_parts[0];
        let candidate = head_parts[1];
        let (name, suite) = match name_suite.split_once('/') {
            Some((n, s)) => (n, s),
            None => (name_suite, ""),
        };
        let current = tail.trim_end_matches(']').trim();

        let entry = lua.create_table()?;
        entry.set("name", name)?;
        entry.set("current", current)?;
        entry.set("candidate", candidate)?;
        entry.set("suite", suite)?;
        out.set(idx, entry)?;
        idx += 1;
    }
    Ok(out)
}

// ── Shell helper ─────────────────────────────────────────────────────────────

/// Hard cap on apt-get / dpkg-query / apt-cache invocations. Long enough
/// for a fresh install over a slow link, short enough that a hung apt-get
/// update doesn't keep the Tokio task alive forever.
const APT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(900);

async fn run_command(program: &str, args: &[&str]) -> mlua::Result<(i32, String, String)> {
    let mut cmd = tokio::process::Command::new(program);
    cmd.args(args);
    cmd.env("DEBIAN_FRONTEND", "noninteractive");
    cmd.env("LC_ALL", "C");
    cmd.env_remove("APT_CONFIG");
    cmd.env_remove("APT_LISTCHANGES_FRONTEND");
    cmd.env_remove("DEBCONF_NONINTERACTIVE_SEEN");
    cmd.stdin(std::process::Stdio::null());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    cmd.kill_on_drop(true);

    // Spawn manually so we keep mutable access to `child` after timeout for
    // explicit kill + reap (kill_on_drop's reap is async-scheduled and not
    // guaranteed before the runtime tears down).
    let mut child = cmd
        .spawn()
        .map_err(|e| mlua::Error::runtime(format!("apt: spawn {program}: {e}")))?;

    let stdout_handle = child.stdout.take();
    let stderr_handle = child.stderr.take();
    let stdout_task = tokio::spawn(async move {
        let mut buf = Vec::new();
        if let Some(mut s) = stdout_handle {
            use tokio::io::AsyncReadExt;
            let _ = s.read_to_end(&mut buf).await;
        }
        buf
    });
    let stderr_task = tokio::spawn(async move {
        let mut buf = Vec::new();
        if let Some(mut s) = stderr_handle {
            use tokio::io::AsyncReadExt;
            let _ = s.read_to_end(&mut buf).await;
        }
        buf
    });

    match tokio::time::timeout(APT_TIMEOUT, child.wait()).await {
        Ok(Ok(status)) => {
            let stdout = stdout_task.await.unwrap_or_default();
            let stderr = stderr_task.await.unwrap_or_default();
            Ok((
                status.code().unwrap_or(-1),
                String::from_utf8_lossy(&stdout).to_string(),
                String::from_utf8_lossy(&stderr).to_string(),
            ))
        }
        Ok(Err(e)) => Err(mlua::Error::runtime(format!("apt: wait {program}: {e}"))),
        Err(_elapsed) => {
            let _ = child.start_kill();
            let _ = child.wait().await;
            stdout_task.abort();
            stderr_task.abort();
            Err(mlua::Error::runtime(format!(
                "apt: {program} timed out after {}s",
                APT_TIMEOUT.as_secs()
            )))
        }
    }
}

// ── source management ────────────────────────────────────────────────────────

/// apt.add_source({ id, source_list, key_path, _sources_dir?, _keyrings_dir? }) ->
///   { changed = bool, list_path = string, key_path = string }
///
/// Idempotent. `_sources_dir` and `_keyrings_dir` overrides exist for tests so
/// we don't write into /etc during cargo test. In production they default to
/// /etc/apt/sources.list.d and /usr/share/keyrings.
fn add_source(lua: &Lua, opts: Table) -> mlua::Result<Table> {
    let id: String = opts.get("id")?;
    let source_list: String = opts.get("source_list")?;
    let key_path: String = opts.get("key_path")?;
    let sources_dir: String = opts
        .get::<Option<String>>("_sources_dir")?
        .unwrap_or_else(|| "/etc/apt/sources.list.d".into());
    let keyrings_dir: String = opts
        .get::<Option<String>>("_keyrings_dir")?
        .unwrap_or_else(|| "/usr/share/keyrings".into());

    if id.is_empty()
        || !id
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
    {
        return Err(mlua::Error::runtime(format!(
            "apt.add_source: id {id:?} must match [a-z0-9-]+"
        )));
    }

    if source_list.contains('\n') || source_list.contains('\r') {
        return Err(mlua::Error::runtime(
            "apt.add_source: source_list must be a single line (no \\n or \\r)",
        ));
    }

    std::fs::create_dir_all(&sources_dir)
        .map_err(|e| mlua::Error::runtime(format!("apt.add_source: mkdir {sources_dir:?}: {e}")))?;
    std::fs::create_dir_all(&keyrings_dir).map_err(|e| {
        mlua::Error::runtime(format!("apt.add_source: mkdir {keyrings_dir:?}: {e}"))
    })?;

    let list_dst = format!("{sources_dir}/{id}.list");
    let key_dst = format!("{keyrings_dir}/{id}.gpg");

    let mut changed = false;

    // Write key BEFORE list: a stranded keyring is harmless, but a stranded
    // .list referring to a missing keyring breaks `apt-get update`.
    //
    // Idempotent key copy: read key_path, compare to dst, copy if different.
    let want_key = std::fs::read(&key_path)
        .map_err(|e| mlua::Error::runtime(format!("apt.add_source: read key {key_path:?}: {e}")))?;
    let cur_key = std::fs::read(&key_dst).ok();
    if cur_key.as_deref() != Some(&want_key) {
        let tmp = format!("{key_dst}.tmp.{}", tmp_suffix());
        std::fs::write(&tmp, &want_key)
            .map_err(|e| mlua::Error::runtime(format!("apt.add_source: write key {tmp:?}: {e}")))?;
        std::fs::rename(&tmp, &key_dst)
            .map_err(|e| mlua::Error::runtime(format!("apt.add_source: rename key: {e}")))?;
        changed = true;
    }

    // Idempotent list write: only write if missing or content differs.
    let want_list = format!("{}\n", source_list.trim_end());
    let cur_list = std::fs::read_to_string(&list_dst).ok();
    if cur_list.as_deref() != Some(&want_list) {
        let tmp = format!("{list_dst}.tmp.{}", tmp_suffix());
        std::fs::write(&tmp, &want_list)
            .map_err(|e| mlua::Error::runtime(format!("apt.add_source: write {tmp:?}: {e}")))?;
        std::fs::rename(&tmp, &list_dst)
            .map_err(|e| mlua::Error::runtime(format!("apt.add_source: rename: {e}")))?;
        changed = true;
    }

    let result = lua.create_table()?;
    result.set("changed", changed)?;
    result.set("list_path", list_dst)?;
    result.set("key_path", key_dst)?;
    Ok(result)
}