envstash 0.1.12

Manage .env files across git branches with versioning, diffing, and optional encryption
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
pub mod email;
pub mod gist;
pub mod paste;
pub mod ssh;

use crate::config;
use crate::error::{Error, Result};

/// Send data to a remote target based on the `--to` value.
///
/// Returns `Ok(Some(url))` for backends that produce a URL (paste, gist),
/// `Ok(None)` for backends that don't (email, ssh).
pub fn send(
    target: &str,
    data: &[u8],
    public: bool,
    filename: Option<&str>,
) -> Result<Option<String>> {
    if target == "gist" {
        // For gist: base64-encode binary data (encrypted output).
        let payload = if is_binary(data) {
            use base64::Engine;
            base64::engine::general_purpose::STANDARD
                .encode(data)
                .into_bytes()
        } else {
            data.to_vec()
        };
        let url = gist::send(&payload, public, filename)?;
        Ok(Some(url))
    } else if let Some(addr) = target.strip_prefix("email:") {
        email::send(data, addr, "envstash send")?;
        Ok(None)
    } else if target.starts_with("ssh://") {
        ssh::send(data, target)?;
        Ok(None)
    } else if is_url(target) {
        let headers = config::load().send.resolve_headers_for_url(target);
        let url = paste::send(data, target, &headers)?;
        Ok(Some(url))
    } else {
        Err(Error::Other(format!(
            "Unknown target '{target}'. Use: --to, --to <url>, gist, email:<addr>, or ssh://user@host"
        )))
    }
}

/// Fetch data from a remote source based on the `--from` value.
pub fn fetch(source: &str) -> Result<Vec<u8>> {
    if source.starts_with("ssh://") {
        ssh::fetch(source)
    } else if is_gist_url(source) {
        let id = gist::extract_gist_id(source);
        let raw = gist::fetch(id)?;
        // If the gist content looks base64-encoded, decode it.
        maybe_base64_decode(&raw)
    } else if is_url(source) {
        let headers = config::load().send.resolve_headers_for_url(source);
        paste::fetch(source, &headers)
    } else {
        Err(Error::Other(format!(
            "Unknown source '{source}'. Use: https://<url>, ssh://user@host, or a gist URL"
        )))
    }
}

/// Check whether the data is binary (contains non-text bytes).
fn is_binary(data: &[u8]) -> bool {
    data.iter()
        .any(|&b| b > 127 || (b < 32 && b != b'\n' && b != b'\r' && b != b'\t'))
}

/// Check whether a string looks like an HTTP(S) URL.
fn is_url(s: &str) -> bool {
    s.starts_with("http://") || s.starts_with("https://")
}

/// Check whether a URL points to a GitHub Gist.
fn is_gist_url(s: &str) -> bool {
    s.starts_with("https://gist.github.com/") || s.starts_with("http://gist.github.com/")
}

/// If the data decodes as base64 to a known envstash transport magic
/// (`EVPW` for transport-encrypted v1, or `-----BEGIN PGP` for armored
/// GPG), return the decoded bytes. Otherwise return the input as-is.
fn maybe_base64_decode(data: &[u8]) -> Result<Vec<u8>> {
    let text = match std::str::from_utf8(data) {
        Ok(t) => t.trim(),
        Err(_) => return Ok(data.to_vec()),
    };

    use base64::Engine;
    let decoded = match base64::engine::general_purpose::STANDARD.decode(text) {
        Ok(d) => d,
        Err(_) => return Ok(data.to_vec()),
    };

    if decoded.starts_with(b"EVPW") || decoded.starts_with(b"-----BEGIN PGP") {
        Ok(decoded)
    } else {
        Ok(data.to_vec())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::export::{self, ExportEntry, ExportEnvelope};

    // -- URL detection --

    #[test]
    fn is_url_https() {
        assert!(is_url("https://0x0.st"));
        assert!(is_url("https://example.com/path"));
    }

    #[test]
    fn is_url_http() {
        assert!(is_url("http://example.com"));
    }

    #[test]
    fn is_url_non_urls() {
        assert!(!is_url("gist"));
        assert!(!is_url("ssh://user@host"));
        assert!(!is_url("email:user@host"));
        assert!(!is_url("ftp://example.com"));
    }

    #[test]
    fn is_gist_url_valid() {
        assert!(is_gist_url("https://gist.github.com/user/abc123"));
        assert!(is_gist_url("https://gist.github.com/user/abc123/"));
    }

    #[test]
    fn is_gist_url_not_gist() {
        assert!(!is_gist_url("https://github.com/user/repo"));
        assert!(!is_gist_url("https://0x0.st/abc"));
    }

    // -- binary detection --

    #[test]
    fn is_binary_plaintext() {
        assert!(!is_binary(b"DB_HOST=localhost\n"));
        assert!(!is_binary(b"line1\r\nline2\ttab"));
    }

    #[test]
    fn is_binary_with_high_bytes() {
        assert!(is_binary(&[0x80, 0x90, 0xFF]));
    }

    #[test]
    fn is_binary_with_control_chars() {
        assert!(is_binary(&[0x00]));
        assert!(is_binary(&[0x01]));
    }

    #[test]
    fn is_binary_empty() {
        assert!(!is_binary(b""));
    }

    // -- base64 auto-decode --

    #[test]
    fn maybe_decode_plaintext_export() {
        let data = b"# envstash export\nDB_HOST=localhost\n";
        let result = maybe_base64_decode(data).unwrap();
        assert_eq!(result, data);
    }

    #[test]
    fn maybe_decode_json_export() {
        let data = b"{\"version\":1,\"entries\":[]}";
        let result = maybe_base64_decode(data).unwrap();
        assert_eq!(result, data);
    }

    #[test]
    fn maybe_decode_evpw_magic() {
        use base64::Engine;
        let mut original = b"EVPW".to_vec();
        original.extend_from_slice(b"\x01plus some payload bytes");
        let encoded = base64::engine::general_purpose::STANDARD.encode(&original);
        let result = maybe_base64_decode(encoded.as_bytes()).unwrap();
        assert_eq!(result, original);
    }

    #[test]
    fn maybe_decode_pgp_armored() {
        use base64::Engine;
        let original = b"-----BEGIN PGP MESSAGE-----\nabc\n-----END PGP MESSAGE-----\n";
        let encoded = base64::engine::general_purpose::STANDARD.encode(original);
        let result = maybe_base64_decode(encoded.as_bytes()).unwrap();
        assert_eq!(result, original);
    }

    #[test]
    fn maybe_decode_unknown_base64_passthrough() {
        use base64::Engine;
        let original = b"arbitrary binary data without magic";
        let encoded = base64::engine::general_purpose::STANDARD.encode(original);
        let result = maybe_base64_decode(encoded.as_bytes()).unwrap();
        // Should return the raw base64 input unchanged.
        assert_eq!(result, encoded.as_bytes());
    }

    #[test]
    fn maybe_decode_invalid_base64_returns_as_is() {
        let data = b"not base64 at all!!! with spaces";
        let result = maybe_base64_decode(data).unwrap();
        assert_eq!(result, data);
    }

    #[test]
    fn maybe_decode_raw_binary_returns_as_is() {
        let data: Vec<u8> = vec![0x00, 0x80, 0xFF, 0x01];
        let result = maybe_base64_decode(&data).unwrap();
        assert_eq!(result, data);
    }

    // -- gist ID extraction --

    #[test]
    fn extract_gist_id_from_url() {
        assert_eq!(
            gist::extract_gist_id("https://gist.github.com/user/abc123"),
            "abc123"
        );
    }

    #[test]
    fn extract_gist_id_trailing_slash() {
        assert_eq!(
            gist::extract_gist_id("https://gist.github.com/user/abc123/"),
            "abc123"
        );
    }

    #[test]
    fn extract_gist_id_bare() {
        assert_eq!(gist::extract_gist_id("abc123"), "abc123");
    }

    // -- SSH dest parsing --

    #[test]
    fn ssh_parse_dest_with_prefix() {
        assert_eq!(ssh::parse_dest("ssh://user@host"), "user@host");
    }

    #[test]
    fn ssh_parse_dest_without_prefix() {
        assert_eq!(ssh::parse_dest("user@host"), "user@host");
    }

    // -- send dispatch routing --

    #[test]
    fn send_rejects_unknown_target() {
        let result = send("ftp://something", b"data", false, None);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Unknown target"));
    }

    // -- integration: 0x0.st paste round-trip --

    #[test]
    #[ignore] // requires network access
    fn paste_0x0_round_trip() {
        let env_entries = vec![
            crate::types::EnvEntry {
                key: "DB_HOST".to_string(),
                value: "localhost".to_string(),
                comment: Some("database host".to_string()),
            },
            crate::types::EnvEntry {
                key: "API_KEY".to_string(),
                value: "sk-test-12345".to_string(),
                comment: None,
            },
        ];
        let hash = crate::parser::content_hash(&env_entries);

        let envelope = ExportEnvelope {
            version: 1,
            file: ".env".to_string(),
            branch: "main".to_string(),
            commit: "abc123".to_string(),
            timestamp: "2024-06-17T12:00:00Z".to_string(),
            content_hash: hash,
            message: None,
            entries: vec![
                ExportEntry {
                    key: "DB_HOST".to_string(),
                    value: "localhost".to_string(),
                    comment: Some("database host".to_string()),
                },
                ExportEntry {
                    key: "API_KEY".to_string(),
                    value: "sk-test-12345".to_string(),
                    comment: None,
                },
            ],
        };
        let serialized = export::to_text(&envelope);
        let headers = std::collections::HashMap::new();

        let url = paste::send(serialized.as_bytes(), "https://0x0.st", &headers)
            .expect("paste upload to 0x0.st failed");

        assert!(
            url.starts_with("https://0x0.st/") || url.starts_with("http://0x0.st/"),
            "unexpected paste URL: {url}"
        );

        let fetched = paste::fetch(&url, &headers).expect("paste fetch from 0x0.st failed");
        let text = std::str::from_utf8(&fetched).expect("fetched data is not valid UTF-8");
        let parsed = export::auto_detect(text).expect("failed to parse fetched export data");
        assert_eq!(parsed.entries.len(), 2);
        assert_eq!(parsed.entries[0].key, "DB_HOST");
        assert_eq!(parsed.entries[0].value, "localhost");
        assert_eq!(parsed.entries[1].key, "API_KEY");
        assert_eq!(parsed.entries[1].value, "sk-test-12345");
    }

    // -- integration: GitHub Gist round-trip (skipped if gh unavailable) --

    #[test]
    #[ignore] // requires network access + gh auth
    fn gist_round_trip() {
        if !gist::is_available() {
            eprintln!("gh CLI not available, skipping gist round-trip test");
            return;
        }

        // Also verify the user is actually authenticated.
        let auth = crate::util::subprocess::spawn_clean("gh")
            .args(["auth", "status"])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status();
        match auth {
            Ok(s) if s.success() => {}
            _ => {
                eprintln!("gh auth not logged in, skipping gist round-trip test");
                return;
            }
        }

        // Build entries and compute a real content hash, matching what share.rs does.
        let env_entries = vec![
            crate::types::EnvEntry {
                key: "DB_HOST".to_string(),
                value: "localhost".to_string(),
                comment: Some("database host".to_string()),
            },
            crate::types::EnvEntry {
                key: "API_KEY".to_string(),
                value: "sk-test-12345".to_string(),
                comment: None,
            },
        ];
        let hash = crate::parser::content_hash(&env_entries);

        let envelope = ExportEnvelope {
            version: 1,
            file: ".env".to_string(),
            branch: "main".to_string(),
            commit: "abc123".to_string(),
            timestamp: "2024-06-17T12:00:00Z".to_string(),
            content_hash: hash.clone(),
            message: None,
            entries: vec![
                ExportEntry {
                    key: "DB_HOST".to_string(),
                    value: "localhost".to_string(),
                    comment: Some("database host".to_string()),
                },
                ExportEntry {
                    key: "API_KEY".to_string(),
                    value: "sk-test-12345".to_string(),
                    comment: None,
                },
            ],
        };
        let serialized = export::to_text(&envelope);

        let url =
            gist::send(serialized.as_bytes(), false, Some(&hash)).expect("gist create failed");
        let id = gist::extract_gist_id(&url).to_string();

        let fetched = gist::fetch(&id).expect("gist fetch failed");
        let text = std::str::from_utf8(&fetched).expect("fetched gist is not valid UTF-8");
        let parsed = export::auto_detect(text.trim()).expect("failed to parse fetched gist data");
        assert_eq!(parsed.entries.len(), 2);
        assert_eq!(parsed.entries[0].key, "DB_HOST");
        assert_eq!(parsed.entries[0].value, "localhost");
        assert_eq!(parsed.entries[1].key, "API_KEY");
        assert_eq!(parsed.entries[1].value, "sk-test-12345");

        // Cleanup: delete the gist so we don't leave litter.
        let _ = crate::util::subprocess::spawn_clean("gh")
            .args(["gist", "delete", &id])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status();
    }
}