bashkit 0.5.0

Awesomely fast virtual sandbox with bash and file system
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
//! Git configuration for Bashkit.
//!
//! # Security Mitigations
//!
//! This module mitigates the following threats (see `specs/threat-model.md`):
//!
//! - **TM-GIT-001**: Unauthorized clone → remote URL allowlist (Phase 2)
//! - **TM-GIT-002**: Host identity leak → configurable virtual identity
//! - **TM-GIT-003**: Host git config access → no host filesystem access
//! - **TM-GIT-010**: Push to unauthorized remote → remote URL allowlist (Phase 2)

use std::collections::HashSet;
#[cfg(feature = "git")]
use url::Url;

/// Default author name for commits in the virtual environment.
pub const DEFAULT_AUTHOR_NAME: &str = "sandbox";

/// Default author email for commits in the virtual environment.
pub const DEFAULT_AUTHOR_EMAIL: &str = "sandbox@bashkit.local";

/// Git configuration for Bashkit.
///
/// Controls git behavior including author identity and remote access.
///
/// # Example
///
/// ```rust
/// use bashkit::GitConfig;
///
/// let config = GitConfig::new()
///     .author("Deploy Bot", "deploy@example.com");
/// ```
///
/// # Security
///
/// - Author identity is virtual (never reads from host)
/// - Remote URLs require explicit allowlist (Phase 2)
/// - All operations confined to virtual filesystem
#[derive(Debug, Clone)]
pub struct GitConfig {
    /// Author name for commits
    pub(crate) author_name: String,
    /// Author email for commits
    pub(crate) author_email: String,
    /// Remote URL patterns that are allowed (Phase 2)
    pub(crate) remote_allowlist: HashSet<String>,
    /// Allow all remote URLs (dangerous - testing only)
    pub(crate) allow_all_remotes: bool,
}

impl Default for GitConfig {
    fn default() -> Self {
        Self {
            author_name: DEFAULT_AUTHOR_NAME.to_string(),
            author_email: DEFAULT_AUTHOR_EMAIL.to_string(),
            remote_allowlist: HashSet::new(),
            allow_all_remotes: false,
        }
    }
}

impl GitConfig {
    /// Create a new git configuration with default virtual identity.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bashkit::GitConfig;
    ///
    /// let config = GitConfig::new();
    /// // Uses default author: "sandbox <sandbox@bashkit.local>"
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the author name and email for commits.
    ///
    /// # Security (TM-GIT-002)
    ///
    /// This is the only way to set author identity. The git builtin will
    /// never read from host `~/.gitconfig` or environment variables.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bashkit::GitConfig;
    ///
    /// let config = GitConfig::new()
    ///     .author("CI Bot", "ci@example.com");
    /// ```
    pub fn author(mut self, name: impl Into<String>, email: impl Into<String>) -> Self {
        self.author_name = name.into();
        self.author_email = email.into();
        self
    }

    /// Add a remote URL pattern to the allowlist (Phase 2).
    ///
    /// Remote operations (clone, push, pull, fetch) require URLs to be
    /// in the allowlist. This method will be used in Phase 2.
    ///
    /// # Example
    ///
    /// ```rust
    /// use bashkit::GitConfig;
    ///
    /// let config = GitConfig::new()
    ///     .allow_remote("https://github.com/myorg/");
    /// ```
    pub fn allow_remote(mut self, pattern: impl Into<String>) -> Self {
        self.remote_allowlist.insert(pattern.into());
        self
    }

    /// Add multiple remote URL patterns to the allowlist (Phase 2).
    pub fn allow_remotes(mut self, patterns: impl IntoIterator<Item = impl Into<String>>) -> Self {
        for pattern in patterns {
            self.remote_allowlist.insert(pattern.into());
        }
        self
    }

    /// Allow all remote URLs.
    ///
    /// # Warning
    ///
    /// This is dangerous and should only be used for testing or
    /// when the script is fully trusted.
    pub fn allow_all_remotes(mut self) -> Self {
        self.allow_all_remotes = true;
        self
    }

    /// Get the configured author name.
    pub fn author_name(&self) -> &str {
        &self.author_name
    }

    /// Get the configured author email.
    pub fn author_email(&self) -> &str {
        &self.author_email
    }

    /// Check if remote access is configured.
    #[allow(dead_code)]
    pub(crate) fn has_remote_access(&self) -> bool {
        self.allow_all_remotes || !self.remote_allowlist.is_empty()
    }

    /// Check if a remote URL is allowed.
    ///
    /// # Security (TM-GIT-010, TM-GIT-011)
    ///
    /// Returns true only if:
    /// - allow_all_remotes is true, or
    /// - URL starts with one of the allowed patterns
    ///
    /// # Security (TM-GIT-012, TM-GIT-013)
    ///
    /// Also validates that the URL uses HTTPS (not SSH or git://).
    #[cfg(feature = "git")]
    pub(crate) fn is_url_allowed(&self, url: &str) -> Result<(), String> {
        let parsed_url = Url::parse(url).map_err(|err| {
            format!(
                "error: invalid remote URL '{}': {}\n\
                 hint: remote URLs must be valid absolute HTTPS URLs",
                url, err
            )
        })?;

        // TM-GIT-012, TM-GIT-013: Only allow HTTPS
        if parsed_url.scheme() != "https" {
            return Err(format!(
                "error: only HTTPS URLs are allowed (got '{}')\n\
                 hint: SSH and git:// protocols are disabled for security",
                url
            ));
        }

        // Check allowlist
        if self.allow_all_remotes {
            return Ok(());
        }

        if self.remote_allowlist.is_empty() {
            return Err("error: no remote URLs are allowed\n\
                 hint: configure allowed remotes with GitConfig::allow_remote()"
                .to_string());
        }

        // Check parsed URL against allowlist patterns.
        for pattern in &self.remote_allowlist {
            let Ok(pattern_url) = Url::parse(pattern) else {
                continue;
            };
            if pattern_url.scheme() != "https" {
                continue;
            }

            if parsed_url.host_str() != pattern_url.host_str() {
                continue;
            }

            if parsed_url.port_or_known_default() != pattern_url.port_or_known_default() {
                continue;
            }

            let pattern_path = pattern_url.path();
            let url_path = parsed_url.path();

            if pattern_path == "/" || pattern_path.is_empty() {
                return Ok(());
            }

            if !url_path.starts_with(pattern_path) {
                continue;
            }

            if !pattern_path.ends_with('/') && url_path.len() > pattern_path.len() {
                let Some(&next) = url_path.as_bytes().get(pattern_path.len()) else {
                    continue;
                };
                if next != b'/' {
                    continue;
                }
            }

            return Ok(());
        }

        Err(format!(
            "error: remote URL '{}' is not in allowlist\n\
             hint: configure allowed remotes with GitConfig::allow_remote()",
            url
        ))
    }
}

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

    #[test]
    fn test_default_config() {
        let config = GitConfig::new();
        assert_eq!(config.author_name(), DEFAULT_AUTHOR_NAME);
        assert_eq!(config.author_email(), DEFAULT_AUTHOR_EMAIL);
        assert!(!config.has_remote_access());
    }

    #[test]
    fn test_custom_author() {
        let config = GitConfig::new().author("Test User", "test@example.com");
        assert_eq!(config.author_name(), "Test User");
        assert_eq!(config.author_email(), "test@example.com");
    }

    #[test]
    fn test_remote_allowlist() {
        let config = GitConfig::new()
            .allow_remote("https://github.com/org1/")
            .allow_remote("https://github.com/org2/");

        assert!(config.has_remote_access());
        assert_eq!(config.remote_allowlist.len(), 2);
    }

    #[test]
    fn test_allow_all_remotes() {
        let config = GitConfig::new().allow_all_remotes();
        assert!(config.has_remote_access());
    }

    #[test]
    #[cfg(feature = "git")]
    fn test_url_validation_https_allowed() {
        let config = GitConfig::new().allow_remote("https://github.com/org/");

        // Allowed URL
        assert!(
            config
                .is_url_allowed("https://github.com/org/repo.git")
                .is_ok()
        );

        // Different org - not allowed
        assert!(
            config
                .is_url_allowed("https://github.com/other/repo.git")
                .is_err()
        );
    }

    #[test]
    #[cfg(feature = "git")]
    fn test_url_validation_ssh_blocked() {
        let config = GitConfig::new().allow_all_remotes();

        // SSH URLs should be blocked
        assert!(
            config
                .is_url_allowed("git@github.com:org/repo.git")
                .is_err()
        );
    }

    #[test]
    #[cfg(feature = "git")]
    fn test_url_validation_git_protocol_blocked() {
        let config = GitConfig::new().allow_all_remotes();

        // git:// protocol should be blocked
        assert!(
            config
                .is_url_allowed("git://github.com/org/repo.git")
                .is_err()
        );
    }

    #[test]
    #[cfg(feature = "git")]
    fn test_url_validation_empty_allowlist() {
        let config = GitConfig::new();

        // Empty allowlist should block all
        assert!(
            config
                .is_url_allowed("https://github.com/org/repo.git")
                .is_err()
        );
    }

    #[test]
    #[cfg(feature = "git")]
    fn test_url_validation_allow_all() {
        let config = GitConfig::new().allow_all_remotes();

        // All HTTPS URLs should be allowed
        assert!(
            config
                .is_url_allowed("https://github.com/any/repo.git")
                .is_ok()
        );
        assert!(
            config
                .is_url_allowed("https://gitlab.com/any/repo.git")
                .is_ok()
        );
    }

    #[test]
    #[cfg(feature = "git")]
    fn test_url_boundary_prevents_prefix_confusion() {
        let config = GitConfig::new().allow_remote("https://github.com/myorg");

        // Should match with path separator
        assert!(
            config
                .is_url_allowed("https://github.com/myorg/repo.git")
                .is_ok()
        );
        // Should NOT match org with similar prefix
        assert!(
            config
                .is_url_allowed("https://github.com/myorg-evil/malicious.git")
                .is_err()
        );
        assert!(
            config
                .is_url_allowed("https://github.com/myorg-phishing/repo.git")
                .is_err()
        );
    }

    #[test]
    #[cfg(feature = "git")]
    fn test_url_boundary_exact_match() {
        let config = GitConfig::new().allow_remote("https://github.com/myorg/repo.git");
        assert!(
            config
                .is_url_allowed("https://github.com/myorg/repo.git")
                .is_ok()
        );
    }

    #[test]
    #[cfg(feature = "git")]
    fn test_url_boundary_with_trailing_slash() {
        let config = GitConfig::new().allow_remote("https://github.com/myorg/");
        assert!(
            config
                .is_url_allowed("https://github.com/myorg/repo.git")
                .is_ok()
        );
        assert!(
            config
                .is_url_allowed("https://github.com/myorg-evil/repo.git")
                .is_err()
        );
    }

    #[test]
    #[cfg(feature = "git")]
    fn test_url_allowlist_rejects_host_confusion_vectors() {
        let config = GitConfig::new().allow_remote("https://github.com");

        assert!(
            config
                .is_url_allowed("https://github.com@evil.com/org/repo.git")
                .is_err()
        );
        assert!(
            config
                .is_url_allowed("https://github.com.evil.com/org/repo.git")
                .is_err()
        );
    }
}