hasp-backend-file 0.2.0-alpha

file:// backend for hasp — reads secrets from files.
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
//! `file://` backend for hasp.
//!
//! Grammar:
//! - `file:///absolute/path` — absolute path (host empty or `localhost`)
//! - `file://./relative/path` — relative to current working directory (host = `.`)
//! - `?raw=true` — disables the default newline trim (get only)
//!
//! `list` supports glob patterns in the path component:
//! - `file:///etc/secrets/*.key`
//! - `file:///etc/secrets/**/*.key`
//!
//! Query params for `list`:
//! - `?hidden=1` — include dotfiles (default: exclude)
//! - `?follow_symlinks=1` — follow symlinks during `**` traversal
//!   (default: skip — prevents escaping the intended tree)
//!
//! Supported operations: `get`, `put`, `exists`, `delete`, `list`.

use hasp_core::{
    secret_mem::wrap_secret, Backend, BackendFailureKind, Entry, Error, ExposeSecret, SecretString,
};
use std::path::PathBuf;
use url::Url;

/// URL shape for `file://` addresses.
///
/// `path` is the platform-native file path extracted from the URL.
/// `raw` disables the default newline trimming performed on `get`.
pub struct FileUrl {
    pub path: PathBuf,
    pub raw: bool,
    /// Include dotfiles in `list` results.
    pub hidden: bool,
    /// Follow symlinks during `**` glob traversal in `list`.
    pub follow_symlinks: bool,
}

impl TryFrom<&Url> for FileUrl {
    type Error = Error;

    fn try_from(url: &Url) -> Result<Self, Self::Error> {
        if url.scheme() != "file" {
            return Err(Error::InvalidUrl("expected file:// scheme".into()));
        }

        let host = url.host_str();
        let is_localhost = host.is_none_or(|h| h == "localhost");
        let is_relative = host == Some(".");

        if !is_localhost && !is_relative {
            return Err(Error::InvalidUrl(format!(
                "file:// host must be empty, 'localhost', or '.', got '{}'",
                host.unwrap_or("")
            )));
        }

        let mut raw = false;
        let mut hidden = false;
        let mut follow_symlinks = false;
        for (k, v) in url.query_pairs() {
            match k.as_ref() {
                "raw" if v == "true" => raw = true,
                "hidden" if v == "1" => hidden = true,
                "follow_symlinks" if v == "1" => follow_symlinks = true,
                _ => {
                    return Err(Error::InvalidUrl(format!(
                        "file:// unknown query parameter or value: {}={}",
                        k, v
                    )))
                }
            }
        }

        let path = if is_relative {
            let p = url.path();
            if p == "/" {
                return Err(Error::InvalidUrl(
                    "file:// relative path must not be empty".into(),
                ));
            }
            PathBuf::from(&p[1..])
        } else {
            url.to_file_path()
                .map_err(|_| Error::InvalidUrl("file:// invalid absolute path".into()))?
        };

        Ok(FileUrl {
            path,
            raw,
            hidden,
            follow_symlinks,
        })
    }
}

/// Stdlib-only backend that reads secrets from files.
///
/// Default behavior strips exactly one trailing `\n` or `\r\n` from the
/// file contents — matching the dominant convention for Docker secrets,
/// Kubernetes secrets, and systemd-creds. Use `?raw=true` for verbatim
/// bytes.
pub struct FileBackend;

impl Backend for FileBackend {
    fn scheme(&self) -> &'static str {
        "file"
    }

    fn validate(&self, url: &Url) -> Result<(), Error> {
        FileUrl::try_from(url).map(|_| ())
    }

    fn get(&self, url: &Url) -> Result<SecretString, Error> {
        let file_url = FileUrl::try_from(url)?;
        let mut contents =
            std::fs::read_to_string(&file_url.path).map_err(|e| map_io_error(e, &file_url.path))?;
        if !file_url.raw {
            trim_one_trailing_newline(&mut contents);
        }
        Ok(wrap_secret(contents))
    }

    fn put(&self, url: &Url, value: &SecretString) -> Result<(), Error> {
        let file_url = FileUrl::try_from(url)?;
        if let Some(parent) = file_url.path.parent() {
            if !parent.as_os_str().is_empty() {
                std::fs::create_dir_all(parent).map_err(|e| map_io_error(e, parent))?;
            }
        }
        std::fs::write(&file_url.path, value.expose_secret())
            .map_err(|e| map_io_error(e, &file_url.path))?;
        Ok(())
    }

    fn list(&self, url: &Url) -> Result<Vec<Entry>, Error> {
        let file_url = FileUrl::try_from(url)?;
        let pattern = file_url
            .path
            .to_str()
            .ok_or_else(|| Error::InvalidUrl("file:// path is not valid UTF-8".into()))?;

        // Containment root: the longest path prefix of `pattern` that
        // contains no glob metacharacters. When `follow_symlinks =
        // false` we require every returned path's canonical form to
        // remain under the canonical root, which closes the
        // symlink-directory-mid-pattern escape the leaf
        // `symlink_metadata` check below does NOT cover. (`glob`'s
        // `**` traversal follows symlinked directories regardless.)
        let canon_root = if !file_url.follow_symlinks {
            literal_prefix(pattern).and_then(|p| std::fs::canonicalize(p).ok())
        } else {
            None
        };

        let mut entries = Vec::new();
        let glob_opts = glob::MatchOptions {
            case_sensitive: true,
            require_literal_separator: true,
            require_literal_leading_dot: !file_url.hidden,
        };
        let paths = glob::glob_with(pattern, glob_opts)
            .map_err(|e| Error::InvalidUrl(format!("file:// invalid glob pattern: {e}")))?;

        for result in paths {
            let path = result.map_err(|e| Error::Backend {
                scheme: "file",
                kind: hasp_core::BackendFailureKind::Transient,
                message: format!("glob traversal error: {e}"),
            })?;

            // Leaf symlink filter: skip if the leaf itself is a symlink.
            if !file_url.follow_symlinks {
                if let Ok(meta) = std::fs::symlink_metadata(&path) {
                    if meta.file_type().is_symlink() {
                        continue;
                    }
                }
                // Containment: reject any candidate whose resolved
                // canonical form is outside the canonical pattern
                // root. Catches symlinked subdirectories that `glob`'s
                // `**` traversal silently followed. If we cannot
                // canonicalize either side, drop the candidate — safer
                // to under-report than to leak an escape.
                if let Some(root) = &canon_root {
                    match std::fs::canonicalize(&path) {
                        Ok(canon) if canon.starts_with(root) => {}
                        _ => continue,
                    }
                }
            }

            // Only emit paths that point to regular files (not dirs).
            // This matches the get/put contract: every Entry URL is
            // directly get()-able.
            if !path.is_file() {
                continue;
            }

            let path_url = Url::from_file_path(&path).map_err(|_| Error::Backend {
                scheme: "file",
                kind: hasp_core::BackendFailureKind::Permanent,
                message: format!("cannot convert path to URL: {}", path.display()),
            })?;
            let name = path.to_string_lossy().into_owned();
            entries.push(Entry {
                name,
                url: path_url,
            });
        }

        Ok(entries)
    }

    fn delete(&self, url: &Url) -> Result<(), Error> {
        let file_url = FileUrl::try_from(url)?;
        std::fs::remove_file(&file_url.path).map_err(|e| map_io_error(e, &file_url.path))?;
        Ok(())
    }

    fn exists(&self, url: &Url) -> Result<bool, Error> {
        let file_url = FileUrl::try_from(url)?;
        Ok(file_url.path.exists())
    }
}

/// Return the longest leading directory of `pattern` that contains no
/// glob metacharacter (`*`, `?`, `[`). Used as the containment root
/// for `list` so symlinked subdirectories cannot redirect a `**`
/// traversal outside the user-named tree.
fn literal_prefix(pattern: &str) -> Option<std::path::PathBuf> {
    let stop = pattern.find(['*', '?', '[']).unwrap_or(pattern.len());
    let head = &pattern[..stop];
    let last_sep = head.rfind('/')?;
    Some(std::path::PathBuf::from(&head[..=last_sep]))
}

/// Strips exactly one trailing `\r\n` or `\n` from the given string.
///
/// Mutates in place to avoid an extra allocation. This is the default
/// behavior for `file://` reads because most secret files are created
/// with `echo "secret" > file`, which appends an unwanted newline.
fn trim_one_trailing_newline(s: &mut String) {
    if s.ends_with("\r\n") {
        let new_len = s.len().saturating_sub(2);
        s.truncate(new_len);
    } else if s.ends_with('\n') {
        let new_len = s.len().saturating_sub(1);
        s.truncate(new_len);
    }
}

fn map_io_error(err: std::io::Error, path: &std::path::Path) -> Error {
    use std::io::ErrorKind;
    match err.kind() {
        ErrorKind::NotFound => Error::NotFound(format!("file not found: {}", path.display())),
        ErrorKind::PermissionDenied => {
            Error::PermissionDenied(format!("permission denied: {}", path.display()))
        }
        ErrorKind::WouldBlock | ErrorKind::TimedOut | ErrorKind::Interrupted => Error::Backend {
            scheme: "file",
            kind: BackendFailureKind::Transient,
            message: format!("file I/O transient failure: {err}"),
        },
        _ => Error::Backend {
            scheme: "file",
            kind: BackendFailureKind::Permanent,
            message: format!("file I/O permanent failure: {err}"),
        },
    }
}

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

    #[test]
    fn parse_absolute_url() {
        let url = Url::parse("file:///etc/secrets/db.txt").unwrap();
        let f = FileUrl::try_from(&url).unwrap();
        assert_eq!(f.path, PathBuf::from("/etc/secrets/db.txt"));
        assert!(!f.raw);
    }

    #[test]
    fn parse_localhost_url() {
        let url = Url::parse("file://localhost/etc/secrets/db.txt").unwrap();
        let f = FileUrl::try_from(&url).unwrap();
        assert_eq!(f.path, PathBuf::from("/etc/secrets/db.txt"));
        assert!(!f.raw);
    }

    #[test]
    fn parse_relative_url() {
        let url = Url::parse("file://./secrets/db.txt").unwrap();
        let f = FileUrl::try_from(&url).unwrap();
        assert_eq!(f.path, PathBuf::from("secrets/db.txt"));
        assert!(!f.raw);
    }

    #[test]
    fn parse_raw_true() {
        let url = Url::parse("file:///etc/secrets/db.txt?raw=true").unwrap();
        let f = FileUrl::try_from(&url).unwrap();
        assert_eq!(f.path, PathBuf::from("/etc/secrets/db.txt"));
        assert!(f.raw);
    }

    #[test]
    fn parse_invalid_host_fails() {
        let url = Url::parse("file://otherhost/etc/secrets/db.txt").unwrap();
        assert!(FileUrl::try_from(&url).is_err());
    }

    #[test]
    fn parse_unknown_query_fails() {
        let url = Url::parse("file:///etc/secrets/db.txt?foo=bar").unwrap();
        assert!(FileUrl::try_from(&url).is_err());
    }

    #[test]
    fn parse_relative_empty_path_fails() {
        let url = Url::parse("file://./").unwrap();
        assert!(FileUrl::try_from(&url).is_err());
    }

    #[test]
    fn trim_crlf() {
        let mut s = "hello\r\n".to_string();
        trim_one_trailing_newline(&mut s);
        assert_eq!(s, "hello");
    }

    #[test]
    fn trim_lf() {
        let mut s = "hello\n".to_string();
        trim_one_trailing_newline(&mut s);
        assert_eq!(s, "hello");
    }

    #[test]
    fn trim_prefers_crlf() {
        let mut s = "hello\r\n\n".to_string();
        trim_one_trailing_newline(&mut s);
        assert_eq!(s, "hello\r\n");
    }

    #[test]
    fn trim_no_op_when_no_newline() {
        let mut s = "hello".to_string();
        trim_one_trailing_newline(&mut s);
        assert_eq!(s, "hello");
    }

    #[test]
    fn backend_get_roundtrip_and_trim() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secret.txt");
        std::fs::write(&path, "my-secret\n").unwrap();

        let backend = FileBackend;
        let url = Url::from_file_path(&path).unwrap();
        let secret = backend.get(&url).unwrap();
        assert_eq!(secret.expose_secret(), "my-secret");
    }

    #[test]
    fn backend_get_raw_no_trim() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secret.txt");
        std::fs::write(&path, "my-secret\n").unwrap();

        let backend = FileBackend;
        let mut url = Url::from_file_path(&path).unwrap();
        url.query_pairs_mut().append_pair("raw", "true");
        let secret = backend.get(&url).unwrap();
        assert_eq!(secret.expose_secret(), "my-secret\n");
    }

    #[test]
    fn backend_put_creates_parent_dirs() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("nested/secret.txt");

        let backend = FileBackend;
        let url = Url::from_file_path(&path).unwrap();
        let value = SecretString::new("new-secret".into());
        backend.put(&url, &value).unwrap();

        let contents = std::fs::read_to_string(&path).unwrap();
        assert_eq!(contents, "new-secret");
    }

    #[test]
    fn backend_exists_and_delete() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("to-delete.txt");
        std::fs::write(&path, "value").unwrap();

        let backend = FileBackend;
        let url = Url::from_file_path(&path).unwrap();

        assert!(backend.exists(&url).unwrap());
        backend.delete(&url).unwrap();
        assert!(!backend.exists(&url).unwrap());
    }

    #[test]
    fn backend_get_not_found() {
        let backend = FileBackend;
        let url = Url::parse("file:///nonexistent/path/to/secret.txt").unwrap();
        let err = backend.get(&url).unwrap_err();
        assert!(matches!(err, Error::NotFound(_)));
    }

    #[test]
    fn backend_list_no_match_returns_empty() {
        let dir = tempfile::tempdir().unwrap();
        let backend = FileBackend;
        let pattern = format!("{}/*.nomatch", dir.path().display());
        let url = Url::parse(&format!("file://{pattern}")).unwrap();
        let entries = backend.list(&url).unwrap();
        assert!(entries.is_empty());
    }
}