wdl-modules 0.3.1

Implementation of the WDL module specification
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
//! `[modules]` configuration parsed from `sprocket.toml`.

use std::path::PathBuf;
use std::str::FromStr;

use schemars::JsonSchema;
use thiserror::Error;
use toml_spanner::Toml;
use toml_spanner::helper::display;
use toml_spanner::helper::parse_string;

/// The `[modules]` configuration section.
#[derive(Clone, Debug, PartialEq, Eq, Toml, JsonSchema)]
#[toml(Toml, deny_unknown_fields)]
#[schemars(deny_unknown_fields)]
pub struct ModulesConfig {
    /// Override the global cache location for this project.
    pub cache_path: Option<PathBuf>,

    /// Threshold for the large-file warning, or [`LargeFileWarning::Disabled`]
    /// when the user opts out. Defaults to 1 MiB.
    #[toml(default, FromToml with = parse_string, ToToml with = display)]
    #[schemars(default)]
    pub large_file_warning: LargeFileWarning,

    /// Reject any unsigned module in the dependency tree.
    #[toml(default)]
    #[schemars(default)]
    pub require_signed: bool,

    /// TOFU policy for new signer keys.
    #[toml(default)]
    #[schemars(default)]
    pub trust_mode: TrustMode,

    /// URL schemes permitted for top-level Git dependencies. Defaults
    /// to `["https", "ssh"]`.
    #[toml(default = default_top_level_schemes())]
    #[schemars(default = "default_top_level_schemes")]
    pub allowed_schemes: Vec<String>,

    /// URL schemes permitted for transitive Git dependencies. Defaults
    /// to `["https"]` so remote manifests cannot silently trigger SSH
    /// authentication against an attacker-controlled host.
    #[toml(default = default_transitive_schemes())]
    #[schemars(default = "default_transitive_schemes")]
    pub allowed_transitive_schemes: Vec<String>,

    /// Maximum number of advertised refs accepted from a remote.
    /// Defaults to 100,000.
    #[toml(default = default_max_refs())]
    #[schemars(default = "default_max_refs")]
    pub max_advertised_refs: u64,

    /// Hosts denied for all Git dependencies. Defaults to localhost
    /// addresses.
    #[toml(default = default_denied_hosts())]
    #[schemars(default = "default_denied_hosts")]
    pub denied_hosts: Vec<String>,

    /// Hosts permitted for top-level Git dependencies. Empty means any
    /// non-denied host is allowed.
    #[toml(default)]
    #[schemars(default)]
    pub allowed_hosts: Vec<String>,

    /// Hosts permitted for transitive Git dependencies. Defaults to
    /// `["github.com", "gitlab.com"]`. When non-empty, a transitive
    /// dependency may only be fetched from a host on this list, and Git
    /// credentials are presented only to those hosts, so a transitive
    /// manifest cannot direct the user's credentials at a host the user
    /// has not vouched for. An empty list permits any non-denied host but
    /// presents no credentials to transitive dependencies.
    #[toml(default = default_allowed_transitive_hosts())]
    #[schemars(default = "default_allowed_transitive_hosts")]
    pub allowed_transitive_hosts: Vec<String>,

    /// Maximum number of files allowed in a single materialized module
    /// tree. `None` (the default) disables the limit. Checked against
    /// the Git tree object after fetch but before sparse checkout; this
    /// bounds materialized content, not network transfer.
    pub max_materialized_files: Option<u64>,

    /// Maximum total bytes of regular files allowed in a single
    /// materialized module tree. `None` (the default) disables the
    /// limit. Same enforcement point as `max_materialized_files`.
    pub max_materialized_bytes: Option<u64>,
}

/// The default maximum advertised-ref count.
const fn default_max_refs() -> u64 {
    100_000
}

/// Returns the default set of allowed URL schemes for top-level Git
/// dependencies.
fn default_top_level_schemes() -> Vec<String> {
    vec!["https".into(), "ssh".into()]
}

/// Returns the default set of allowed URL schemes for transitive Git
/// dependencies.
fn default_transitive_schemes() -> Vec<String> {
    vec!["https".into()]
}

/// Returns the default set of allowed hosts for transitive Git
/// dependencies.
///
/// The two major public Git hosts are trusted by default so transitive
/// dependencies resolve out of the box while still presenting
/// credentials only to well-known hosts.
fn default_allowed_transitive_hosts() -> Vec<String> {
    vec!["github.com".into(), "gitlab.com".into()]
}

/// Returns the default denied-host list.
///
/// Loopback and unspecified addresses are blocked to prevent a
/// dependency's `module.json` from directing the resolver at a
/// service running on the user's machine. Without this, a malicious
/// transitive dependency could exfiltrate data or probe internal
/// services by pointing its `git` URL at `localhost`.
fn default_denied_hosts() -> Vec<String> {
    vec![
        "localhost".into(),
        "127.0.0.1".into(),
        "::1".into(),
        "0.0.0.0".into(),
    ]
}

impl Default for ModulesConfig {
    fn default() -> Self {
        Self {
            cache_path: None,
            large_file_warning: LargeFileWarning::default(),
            require_signed: false,
            trust_mode: TrustMode::default(),
            allowed_schemes: default_top_level_schemes(),
            allowed_transitive_schemes: default_transitive_schemes(),
            max_advertised_refs: default_max_refs(),
            denied_hosts: default_denied_hosts(),
            allowed_hosts: Vec::new(),
            allowed_transitive_hosts: default_allowed_transitive_hosts(),
            max_materialized_files: None,
            max_materialized_bytes: None,
        }
    }
}

#[cfg(test)]
use crate::resolver::DependencyScope;

#[cfg(test)]
impl ModulesConfig {
    /// Returns `true` if the given host is permitted for a dependency
    /// at this level of the tree.
    fn host_allowed(&self, host: &str, scope: DependencyScope) -> bool {
        if self
            .denied_hosts
            .iter()
            .any(|h| h.eq_ignore_ascii_case(host))
        {
            return false;
        }
        if is_non_public_ip(host) {
            return false;
        }
        let allowed = if matches!(scope, DependencyScope::Transitive) {
            &self.allowed_transitive_hosts
        } else {
            &self.allowed_hosts
        };
        allowed.is_empty() || allowed.iter().any(|h| h.eq_ignore_ascii_case(host))
    }
}

/// Returns `true` if `host` parses as a non-public IP address
/// (loopback, private RFC1918, link-local, unique-local, multicast,
/// unspecified, or the AWS/cloud metadata service at
/// `169.254.169.254`).
pub(crate) fn is_non_public_ip(host: &str) -> bool {
    use std::net::IpAddr;
    let Ok(ip) = host.parse::<IpAddr>() else {
        return false;
    };
    match ip {
        IpAddr::V4(v4) => {
            // 127.0.0.0/8
            v4.is_loopback()
                // 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 (RFC 1918)
                || v4.is_private()
                // 169.254.0.0/16 — includes the cloud metadata endpoint 169.254.169.254
                || v4.is_link_local()
                // 224.0.0.0/4
                || v4.is_multicast()
                // 0.0.0.0
                || v4.is_unspecified()
                // 255.255.255.255
                || v4.is_broadcast()
                // 100.64.0.0/10 — carrier-grade NAT (RFC 6598)
                || v4.octets()[0] == 100 && (v4.octets()[1] & 0xC0) == 64
        }
        IpAddr::V6(v6) => {
            // ::ffff:0:0/96 — IPv4-mapped IPv6; check the inner v4 address
            if let Some(mapped) = v6.to_ipv4_mapped() {
                return is_non_public_ip(&mapped.to_string());
            }
            // ::1
            v6.is_loopback()
                // ff00::/8
                || v6.is_multicast()
                // ::
                || v6.is_unspecified()
                // fc00::/7 — unique local addresses (RFC 4193)
                || (v6.segments()[0] & 0xFE00) == 0xFC00
                // fe80::/10 — link-local addresses
                || (v6.segments()[0] & 0xFFC0) == 0xFE80
        }
    }
}

/// Dummy type used to generate the JSON schema for [`bytesize::ByteSize`]s.
#[derive(Debug, JsonSchema)]
#[schemars(untagged, inline)]
#[expect(dead_code, reason = "Only used for schema generation.")]
enum ByteSizeSchema {
    /// Absolute byte count.
    Bytes(u64),
    /// Byte count as a formatted string (e.g., '1KiB').
    String(#[schemars(pattern(r"^\d+(?:\.\d+)?\s*(?:[KMGTPEkmgtpe][Ii]?[Bb]?|[Bb])$"))] String),
}

/// Threshold for the large-file warning emitted at sign- and fetch-time.
#[derive(Clone, Copy, Debug, PartialEq, Eq, JsonSchema)]
pub enum LargeFileWarning {
    /// The warning is disabled.
    #[schemars(rename = "none")]
    Disabled,
    /// Files at or above this byte count trigger a warning.
    #[schemars(with = "ByteSizeSchema", untagged)]
    Threshold(u64),
}

impl Default for LargeFileWarning {
    fn default() -> Self {
        // 1 MiB
        Self::Threshold(1024 * 1024)
    }
}

impl FromStr for LargeFileWarning {
    type Err = LargeFileWarningError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.eq_ignore_ascii_case("none") {
            return Ok(Self::Disabled);
        }
        let bytes = s
            .parse::<bytesize::ByteSize>()
            .map_err(|_| LargeFileWarningError(s.to_string()))?
            .as_u64();
        Ok(Self::Threshold(bytes))
    }
}

impl std::fmt::Display for LargeFileWarning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LargeFileWarning::Disabled => f.write_str("none"),
            LargeFileWarning::Threshold(b) => write!(f, "{}", bytesize::ByteSize(*b)),
        }
    }
}

/// Error parsing a [`LargeFileWarning`] string.
#[derive(Debug, Error)]
#[error("`{0}` is not a valid file-size string (expected e.g. `1MiB`, `500KB`, or `none`)")]
pub struct LargeFileWarningError(String);

/// Trust-on-first-use (TOFU) policy for new signer keys.
///
/// When the resolver encounters a signed module whose signer key is not
/// yet recorded in the lockfile, this setting controls whether the key
/// is accepted silently or requires explicit user confirmation. The
/// library computes a [`LockfileDiff`](super::lock::LockfileDiff) that
/// flags new signers; the CLI is responsible for acting on the policy
/// (e.g., prompting the user when `Confirm` is set).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Toml, JsonSchema)]
#[toml(Toml, rename_all = "lowercase")]
#[schemars(rename_all = "lowercase")]
pub enum TrustMode {
    /// New signer keys are recorded in the lockfile without prompting.
    /// This is the default and is suitable for non-interactive or
    /// CI environments where manual confirmation is impractical.
    #[default]
    Auto,
    /// The CLI must prompt the user to confirm any newly-trusted signer
    /// key before writing the lockfile. Intended for interactive use
    /// where the user wants to review each new signer.
    Confirm,
}

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

    #[test]
    fn parses_default_threshold_when_absent() {
        let cfg: ModulesConfig = toml_spanner::from_str("").unwrap();
        assert!(matches!(
            cfg.large_file_warning,
            LargeFileWarning::Threshold(b) if b == 1024 * 1024
        ));
    }

    #[test]
    fn parses_size_string() {
        let cfg: ModulesConfig = toml_spanner::from_str(r#"large_file_warning = "5MiB""#).unwrap();
        assert!(matches!(
            cfg.large_file_warning,
            LargeFileWarning::Threshold(b) if b == 5 * 1024 * 1024
        ));
    }

    #[test]
    fn parses_none_sentinel() {
        for s in ["none", "NONE", "None"] {
            let cfg: ModulesConfig =
                toml_spanner::from_str(&format!(r#"large_file_warning = "{s}""#)).unwrap();
            assert!(matches!(cfg.large_file_warning, LargeFileWarning::Disabled));
        }
    }

    #[test]
    fn rejects_invalid_size_string() {
        let err =
            toml_spanner::from_str::<ModulesConfig>(r#"large_file_warning = "abc""#).unwrap_err();
        assert!(err.to_string().contains("abc"), "wrong message: {err}");
    }

    #[test]
    fn default_policy_denies_localhost_hosts() {
        let cfg = ModulesConfig::default();
        assert!(!cfg.host_allowed("localhost", DependencyScope::TopLevel));
        assert!(!cfg.host_allowed("127.0.0.1", DependencyScope::Transitive));
        assert!(!cfg.host_allowed("::1", DependencyScope::Transitive));
        assert!(!cfg.host_allowed("0.0.0.0", DependencyScope::TopLevel));
    }

    #[test]
    fn default_policy_denies_private_and_metadata_ips() {
        let cfg = ModulesConfig::default();
        let denied = [
            "169.254.169.254",
            "10.0.0.1",
            "192.168.1.1",
            "172.16.0.1",
            "100.64.0.1",
            "127.0.0.1",
            "0.0.0.0",
            "255.255.255.255",
            "224.0.0.1",
            "::1",
            "::",
            "fe80::1",
            "fc00::1",
            "ff02::1",
            // IPv4-mapped IPv6
            "::ffff:127.0.0.1",
            "::ffff:169.254.169.254",
            "::ffff:10.0.0.1",
            "::ffff:192.168.1.1",
        ];
        for ip in denied {
            for scope in [DependencyScope::TopLevel, DependencyScope::Transitive] {
                assert!(
                    !cfg.host_allowed(ip, scope),
                    "`{ip}` should be denied for `{scope:?}`"
                );
            }
        }
    }

    #[test]
    fn default_policy_allows_public_hosts() {
        let cfg = ModulesConfig::default();
        assert!(cfg.host_allowed("github.com", DependencyScope::TopLevel));
        assert!(cfg.host_allowed("github.com", DependencyScope::Transitive));
        assert!(
            cfg.host_allowed("::ffff:140.82.121.3", DependencyScope::TopLevel),
            "public IPv4-mapped IPv6 should be allowed"
        );
    }

    #[test]
    fn allowlist_limits_transitive_hosts() {
        let cfg = ModulesConfig {
            allowed_transitive_hosts: vec!["github.com".into()],
            ..ModulesConfig::default()
        };
        assert!(cfg.host_allowed("github.com", DependencyScope::Transitive));
        assert!(!cfg.host_allowed("gitlab.com", DependencyScope::Transitive));
        assert!(cfg.host_allowed("gitlab.com", DependencyScope::TopLevel));
    }
}