holger-traits 3.3.2

holger's shared vocabulary: ArtifactId, RepositoryBackendTrait, ZnippyPlugin discriminants, and ArtifactFormat — including `ArtifactFormat::home()`, the format→crate map that answers which crate serves PyPI when grepping cannot.
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
//! **The index row type**: what a package says about itself for its format's index
//! ([`IndexRow`]), and the bounds every row is held to ([`IndexRow::check`]).
//!
//! The rows are read out of packages by `holger-index-rows` (in the scan worker); the type
//! lives here so the format descriptors ([`crate::format`]) identify a package from it.

use serde::{Deserialize, Serialize};

/// The largest row of the small kinds (deb, rpm, Helm, Maven, Go), serialized.
pub const MAX_ROW: usize = 64 << 10;
/// The largest wheel `METADATA` a row carries (a larger one is served without PEP 658).
pub const MAX_WHEEL_METADATA: usize = 1 << 20;
/// The largest npm `package.json` a row carries, serialized (the packument's own cap).
pub const MAX_NPM_MANIFEST: usize = 1 << 20;
/// The longest id (a name, a version, an architecture).
pub const MAX_ID: usize = 512;
/// The longest free-text field (a summary, a description, a licence).
pub const MAX_TEXT: usize = 16 << 10;
/// The most rpm `provides`/`requires` entries one row may carry.
pub const MAX_DEPS: usize = 4096;
/// The largest crate index line a row carries, serialized.
pub const MAX_CRATE_LINE: usize = 1 << 20;

/// **A dependency version a crate pins**: an exact requirement
/// (`=1.6.0`) of a normal or build dependency in its `Cargo.toml`, or a registry package in a
/// binary crate's `Cargo.lock`. The vulnerability scan matches each one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Pinned {
    pub name: String,
    pub version: String,
    /// `Cargo.toml` or `Cargo.lock`.
    pub from: String,
}

/// **One dependency a package declares** (a POM `<dependency>`, a `go.mod` `require`, a
/// chart's `dependencies:` entry), as the package spells it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RowDep {
    /// The name in the format's own spelling (`org.slf4j:slf4j-api`, `golang.org/x/net`,
    /// `redis`, `monolog/monolog`).
    pub name: String,
    /// The requirement or version (`1.7.36`, `v0.17.0`, `17.x.x`, `^2.0`); `""` for none.
    #[serde(default)]
    pub req: String,
    /// `""` (shipped), or the format's word: Maven `test`/`provided`/`optional`, Go
    /// `indirect`.
    #[serde(default)]
    pub scope: String,
}

/// **One package's index fields.** Which variant is decided by the package's format.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum IndexRow {
    /// A `.deb`'s `control` stanza, as the package's `control.tar.*` carries it.
    Deb { control: String },
    /// An `.rpm`'s header fields (the NEVRA itself comes from the file name).
    Rpm {
        #[serde(default)]
        epoch: Option<String>,
        #[serde(default)]
        summary: Option<String>,
        #[serde(default)]
        license: Option<String>,
        #[serde(default)]
        url: Option<String>,
        #[serde(default)]
        vendor: Option<String>,
        #[serde(default)]
        sourcerpm: Option<String>,
        #[serde(default)]
        provides: Vec<String>,
        #[serde(default)]
        requires: Vec<String>,
    },
    /// A Helm chart's `Chart.yaml` fields.
    Helm {
        name: String,
        version: String,
        #[serde(default)]
        app_version: Option<String>,
        #[serde(default)]
        description: Option<String>,
        /// `Chart.yaml` `dependencies:` (the subcharts).
        #[serde(default)]
        dependencies: Vec<RowDep>,
    },
    /// A wheel's `<name>-<version>.dist-info/METADATA` (PEP 658), byte for byte, and its
    /// sha256. `metadata: None` when the wheel has none (or one over the cap).
    Wheel {
        #[serde(default, with = "b64")]
        metadata: Option<Vec<u8>>,
        #[serde(default)]
        sha256: Option<String>,
    },
    /// An npm tarball's `package.json` and its `sha512-` integrity.
    Npm {
        manifest: serde_json::Value,
        integrity: String,
    },
    /// A Maven file's coordinates (a `.pom`: from the POM, a parent's group and version
    /// inherited) and the POM's `<dependencies>`.
    Maven {
        group: String,
        artifact: String,
        version: String,
        file: String,
        #[serde(default)]
        deps: Vec<RowDep>,
    },
    /// A Go module file's module path, version and `require`s.
    Go {
        module: String,
        version: String,
        #[serde(default)]
        requires: Vec<RowDep>,
    },
    /// A Composer dist's `composer.json` name (`vendor/package`) and its version, when it states one.
    Composer {
        name: String,
        #[serde(default)]
        version: Option<String>,
    },
    /// An `.apk`'s `.PKGINFO`: its name, version, `depend` and `provides` entries.
    Apk {
        name: String,
        version: String,
        #[serde(default)]
        depends: Vec<String>,
        #[serde(default)]
        provides: Vec<String>,
    },
    /// A `.crate`'s sparse index line from its own `Cargo.toml` (no `cksum`, no `yanked`) and
    /// the dependency versions it pins.
    Crate {
        name: String,
        version: String,
        line: serde_json::Value,
        #[serde(default)]
        pinned: Vec<Pinned>,
    },
}

impl IndexRow {
    /// The variant's name, as the wire spells it.
    pub fn kind(&self) -> &'static str {
        match self {
            IndexRow::Deb { .. } => "deb",
            IndexRow::Rpm { .. } => "rpm",
            IndexRow::Helm { .. } => "helm",
            IndexRow::Wheel { .. } => "wheel",
            IndexRow::Npm { .. } => "npm",
            IndexRow::Maven { .. } => "maven",
            IndexRow::Go { .. } => "go",
            IndexRow::Crate { .. } => "crate",
            IndexRow::Composer { .. } => "composer",
            IndexRow::Apk { .. } => "apk",
        }
    }

    /// **Is this row within its bounds?** Every refusal names the field.
    pub fn check(&self) -> Result<(), String> {
        let bad = |field: &str, why: &str| Err(format!("the {} row's {field} {why}", self.kind()));
        match self {
            IndexRow::Deb { control } => {
                if control.is_empty() || !text_ok(control, MAX_ROW) {
                    return bad(
                        "control",
                        "is empty, longer than its cap or carries control characters",
                    );
                }
            }
            IndexRow::Rpm {
                epoch,
                summary,
                license,
                url,
                vendor,
                sourcerpm,
                provides,
                requires,
            } => {
                if epoch.as_deref().is_some_and(|e| !id_ok(e)) {
                    return bad("epoch", "is not an id");
                }
                for (field, v) in [
                    ("summary", summary),
                    ("license", license),
                    ("url", url),
                    ("vendor", vendor),
                    ("sourcerpm", sourcerpm),
                ] {
                    if v.as_deref().is_some_and(|t| !line_ok(t, MAX_TEXT)) {
                        return bad(
                            field,
                            "is longer than its cap or carries control characters",
                        );
                    }
                }
                for (field, v) in [("provides", provides), ("requires", requires)] {
                    if v.len() > MAX_DEPS
                        || v.iter().any(|d| !line_ok(d, MAX_ID * 2) || d.is_empty())
                    {
                        return bad(
                            field,
                            "has too many entries, or one that is not a dependency",
                        );
                    }
                }
            }
            IndexRow::Helm {
                name,
                version,
                app_version,
                description,
                dependencies,
            } => {
                if let Err(why) = deps_ok(dependencies) {
                    return bad("dependencies", why);
                }
                if !id_ok(name) {
                    return bad("name", "is not an id");
                }
                if !id_ok(version) {
                    return bad("version", "is not an id");
                }
                if app_version.as_deref().is_some_and(|v| !id_ok(v)) {
                    return bad("app_version", "is not an id");
                }
                if description
                    .as_deref()
                    .is_some_and(|d| !line_ok(d, MAX_TEXT))
                {
                    return bad(
                        "description",
                        "is longer than its cap or carries control characters",
                    );
                }
            }
            IndexRow::Wheel { metadata, sha256 } => {
                if metadata
                    .as_ref()
                    .is_some_and(|m| m.len() > MAX_WHEEL_METADATA)
                {
                    return bad("metadata", "is larger than its cap");
                }
                match (metadata, sha256) {
                    (Some(_), Some(h)) if hex64(h) => {}
                    (None, None) => {}
                    _ => {
                        return bad(
                            "sha256",
                            "is not the metadata's sha256 (64 hex digits, with the metadata only)",
                        )
                    }
                }
            }
            IndexRow::Npm {
                manifest,
                integrity,
            } => {
                if !manifest.is_object()
                    || serde_json::to_vec(manifest)
                        .map(|v| v.len())
                        .unwrap_or(usize::MAX)
                        > MAX_NPM_MANIFEST
                {
                    return bad("manifest", "is not an object, or is larger than its cap");
                }
                let b64 = integrity.strip_prefix("sha512-").unwrap_or("");
                if b64.is_empty()
                    || b64.len() > 100
                    || !b64
                        .bytes()
                        .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'/' | b'='))
                {
                    return bad("integrity", "is not a sha512- integrity");
                }
            }
            IndexRow::Maven {
                group,
                artifact,
                version,
                file,
                deps,
            } => {
                if let Err(why) = deps_ok(deps) {
                    return bad("deps", why);
                }
                for (field, v) in [
                    ("group", group),
                    ("artifact", artifact),
                    ("version", version),
                    ("file", file),
                ] {
                    if !id_ok(v)
                        || v.contains('/')
                        || v.contains('\\')
                        || v == "."
                        || v == ".."
                        || v.starts_with("..")
                    {
                        return bad(field, "is not one path segment");
                    }
                }
            }
            IndexRow::Go {
                module,
                version,
                requires,
            } => {
                if let Err(why) = deps_ok(requires) {
                    return bad("requires", why);
                }
                if !id_ok(module) {
                    return bad("module", "is not an id");
                }
                if !id_ok(version) {
                    return bad("version", "is not an id");
                }
            }
            IndexRow::Apk {
                name,
                version,
                depends,
                provides,
            } => {
                if !id_ok(name) || !id_ok(version) {
                    return bad("name", "or its version is not an id");
                }
                for (field, v) in [("depends", depends), ("provides", provides)] {
                    if v.len() > MAX_DEPS
                        || v.iter().any(|d| d.is_empty() || !line_ok(d, MAX_ID * 2))
                    {
                        return bad(
                            field,
                            "has too many entries, or one that is not a dependency",
                        );
                    }
                }
            }
            IndexRow::Composer { name, version } => {
                let vendor_package = name.split_once('/').is_some_and(|(v, p)| {
                    !v.is_empty() && !p.is_empty() && !p.contains('/') && v != ".." && p != ".."
                });
                if !id_ok(name) || !vendor_package {
                    return bad("name", "is not `vendor/package`");
                }
                if version.as_deref().is_some_and(|v| !id_ok(v)) {
                    return bad("version", "is not an id");
                }
            }
            IndexRow::Crate {
                name,
                version,
                line,
                pinned,
            } => {
                if !id_ok(name) || name.contains('/') {
                    return bad("name", "is not a crate name");
                }
                if !id_ok(version) {
                    return bad("version", "is not an id");
                }
                if !line.is_object()
                    || line.get("name").and_then(|n| n.as_str()) != Some(name.as_str())
                    || line.get("vers").and_then(|v| v.as_str()) != Some(version.as_str())
                    || serde_json::to_vec(line)
                        .map(|v| v.len())
                        .unwrap_or(usize::MAX)
                        > MAX_CRATE_LINE
                {
                    return bad(
                        "line",
                        "is not an index line of this crate, or is larger than its cap",
                    );
                }
                if pinned.len() > MAX_DEPS
                    || pinned
                        .iter()
                        .any(|p| !id_ok(&p.name) || !id_ok(&p.version) || !id_ok(&p.from))
                {
                    return bad(
                        "pinned",
                        "has too many entries, or one that is not a version",
                    );
                }
            }
        }
        let size = serde_json::to_vec(self)
            .map(|v| v.len())
            .unwrap_or(usize::MAX);
        let cap = match self {
            IndexRow::Wheel { .. } => MAX_WHEEL_METADATA * 4 / 3 + MAX_ROW,
            IndexRow::Npm { .. } => MAX_NPM_MANIFEST + MAX_ROW,
            IndexRow::Crate { .. } => MAX_CRATE_LINE + MAX_DEPS * 2 * MAX_ID,
            IndexRow::Helm { .. }
            | IndexRow::Maven { .. }
            | IndexRow::Go { .. }
            | IndexRow::Apk { .. } => MAX_ROW + MAX_DEPS * 3 * MAX_ID,
            _ => MAX_ROW,
        };
        if size > cap {
            return bad("size", "is larger than a row may be");
        }
        Ok(())
    }
}

/// Text of at most `max` bytes with no control character but newline and tab.
fn text_ok(s: &str, max: usize) -> bool {
    s.len() <= max && !s.chars().any(|c| c.is_control() && c != '\n' && c != '\t')
}

/// One line of at most `max` bytes: no control character at all.
fn line_ok(s: &str, max: usize) -> bool {
    s.len() <= max && !s.chars().any(char::is_control)
}

/// An id: one non-empty line of at most [`MAX_ID`] bytes.
/// A dependency list within its bounds: at most [`MAX_DEPS`], each name an id, each
/// requirement and scope one line.
fn deps_ok(deps: &[RowDep]) -> Result<(), &'static str> {
    if deps.len() > MAX_DEPS
        || deps
            .iter()
            .any(|d| !id_ok(&d.name) || !line_ok(&d.req, MAX_ID) || !line_ok(&d.scope, MAX_ID))
    {
        return Err("has too many entries, or one that is not a dependency");
    }
    Ok(())
}

fn id_ok(s: &str) -> bool {
    !s.is_empty() && line_ok(s, MAX_ID)
}

fn hex64(s: &str) -> bool {
    s.len() == 64
        && s.bytes()
            .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
}

/// `Option<Vec<u8>>` as standard base64 (a wheel's METADATA is bytes, not always UTF-8).
mod b64 {
    use base64::Engine as _;
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
        match v {
            Some(b) => s.serialize_some(&base64::engine::general_purpose::STANDARD.encode(b)),
            None => s.serialize_none(),
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
        let s: Option<String> = Option::deserialize(d)?;
        s.map(|t| {
            base64::engine::general_purpose::STANDARD
                .decode(t)
                .map_err(serde::de::Error::custom)
        })
        .transpose()
    }
}