hasp-core 0.2.0-alpha

Core contracts, errors, and traits for hasp.
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Structured audit events emitted by every `Store` verb.
//!
//! `AuditEvent` is a closed-shape record: a timestamp, a verb-and-phase
//! label, the URL scheme(s) the verb operated on, a stable outcome
//! label, and (on failure) a stable `error_kind` classifier. No field
//! carries a value, a value-derived length, or any byte of secret
//! material — the redaction posture is enforced by the type system:
//! the struct is `#[non_exhaustive]`, every field is either a
//! timestamp, a `&'static str` chosen from a closed set, or a small
//! owned `String` populated only from a URL scheme.
//!
//! Implementations of `AuditSink` only ever receive an
//! `&AuditEvent` — they cannot construct one with arbitrary content,
//! and they cannot widen the field set.

use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};

/// The verb a `Store` operation belongs to. Closed set so audit event
/// labels are statically known and cannot be widened by a caller.
///
/// Library-side verbs only. CLI-only concerns like `run` (subprocess
/// env injection) live in `hasp-cli` and build their own events via
/// [`AuditEvent::with_event`] using a `&'static str` label literal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verb {
    Get,
    Put,
    List,
    Delete,
    Exists,
    Cp,
    Diff,
}

/// Single-phase cache event classifier. Unlike [`Verb`] these events
/// have no start/done split — a cache hit is observable in one phase.
/// The label set is closed at the type level so audit consumers can
/// switch on it without parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheEvent {
    Hit,
    Miss,
    Expire,
    Clear,
}

impl CacheEvent {
    /// Stable `&'static str` label for the event.
    pub fn label(self) -> &'static str {
        match self {
            CacheEvent::Hit => "cache.hit",
            CacheEvent::Miss => "cache.miss",
            CacheEvent::Expire => "cache.expire",
            CacheEvent::Clear => "cache.clear",
        }
    }
}

impl Verb {
    /// Static label for the `*.start` event.
    pub fn start_label(self) -> &'static str {
        match self {
            Verb::Get => "get.start",
            Verb::Put => "put.start",
            Verb::List => "list.start",
            Verb::Delete => "delete.start",
            Verb::Exists => "exists.start",
            Verb::Cp => "cp.start",
            Verb::Diff => "diff.start",
        }
    }

    /// Static label for the `*.done` event.
    pub fn done_label(self) -> &'static str {
        match self {
            Verb::Get => "get.done",
            Verb::Put => "put.done",
            Verb::List => "list.done",
            Verb::Delete => "delete.done",
            Verb::Exists => "exists.done",
            Verb::Cp => "cp.done",
            Verb::Diff => "diff.done",
        }
    }
}

/// A redacted audit event.
///
/// Constructed via [`AuditEvent::start`] or [`AuditEvent::done`]; the
/// struct is `#[non_exhaustive]` so external crates cannot widen the
/// field set by struct-literal initialization. Sink implementations
/// receive `&AuditEvent` and can serialize whichever fields they
/// expose — but every field is, by construction, value-free.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct AuditEvent {
    pub ts: SystemTime,
    pub event: &'static str,
    pub url_scheme: String,
    pub dst_scheme: Option<String>,
    pub outcome: &'static str,
    pub error_kind: Option<&'static str>,
}

impl AuditEvent {
    /// Build a `*.start` event for `verb` operating on a URL with
    /// `scheme`. Default `outcome` is `"started"`.
    pub fn start(verb: Verb, scheme: impl Into<String>) -> Self {
        Self {
            ts: SystemTime::now(),
            event: verb.start_label(),
            url_scheme: scheme.into(),
            dst_scheme: None,
            outcome: "started",
            error_kind: None,
        }
    }

    /// Build a `*.done` event for `verb` with the given outcome label.
    pub fn done(verb: Verb, scheme: impl Into<String>, outcome: &'static str) -> Self {
        Self {
            ts: SystemTime::now(),
            event: verb.done_label(),
            url_scheme: scheme.into(),
            dst_scheme: None,
            outcome,
            error_kind: None,
        }
    }

    /// Attach a destination scheme (used by `cp`, `diff`, and any future
    /// two-URL verb).
    pub fn with_dst_scheme(mut self, dst_scheme: impl Into<String>) -> Self {
        self.dst_scheme = Some(dst_scheme.into());
        self
    }

    /// Attach a stable error-kind classifier (from `Error::kind()`).
    pub fn with_error_kind(mut self, kind: &'static str) -> Self {
        self.error_kind = Some(kind);
        self
    }

    /// Build an event with an arbitrary `'static` event label.
    ///
    /// CLI-only verbs that do not belong on the library-side [`Verb`]
    /// enum (e.g., `run.start` / `run.done` from subprocess env
    /// injection) build events through this constructor. The
    /// `&'static str` bound prevents runtime-built label strings from
    /// smuggling value bytes into the audit envelope: callers must
    /// pass string literals known at compile time.
    pub fn with_event(
        event: &'static str,
        scheme: impl Into<String>,
        outcome: &'static str,
    ) -> Self {
        Self {
            ts: SystemTime::now(),
            event,
            url_scheme: scheme.into(),
            dst_scheme: None,
            outcome,
            error_kind: None,
        }
    }

    /// Build a cache event for the given URL scheme. Single-phase —
    /// the `outcome` field carries the same classifier as `event`
    /// (e.g., `event = "cache.hit"`, `outcome = "hit"`) so consumers
    /// that filter on `outcome` see a stable label without parsing
    /// the `event` prefix.
    pub fn cache(kind: CacheEvent, scheme: impl Into<String>) -> Self {
        let outcome: &'static str = match kind {
            CacheEvent::Hit => "hit",
            CacheEvent::Miss => "miss",
            CacheEvent::Expire => "expire",
            CacheEvent::Clear => "clear",
        };
        Self {
            ts: SystemTime::now(),
            event: kind.label(),
            url_scheme: scheme.into(),
            dst_scheme: None,
            outcome,
            error_kind: None,
        }
    }

    /// Render to a single-line JSON string with no trailing newline.
    ///
    /// Wire format (fields appear in this order):
    ///
    /// ```json
    /// {"event":"get.done","ts":1234567890,"src_scheme":"vault","outcome":"ok"}
    /// ```
    ///
    /// `dst_scheme` and `error_kind` appear only when populated. The
    /// timestamp is UNIX seconds since the epoch; clock-skew anomalies
    /// fall back to `0` rather than panicking on the secret path.
    pub fn to_json_line(&self) -> String {
        let ts = self
            .ts
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let mut obj = serde_json::Map::new();
        obj.insert("event".into(), serde_json::Value::String(self.event.into()));
        obj.insert("ts".into(), serde_json::Value::Number(ts.into()));
        obj.insert(
            "src_scheme".into(),
            serde_json::Value::String(self.url_scheme.clone()),
        );
        if let Some(d) = &self.dst_scheme {
            obj.insert("dst_scheme".into(), serde_json::Value::String(d.clone()));
        }
        obj.insert(
            "outcome".into(),
            serde_json::Value::String(self.outcome.into()),
        );
        if let Some(k) = self.error_kind {
            obj.insert("error_kind".into(), serde_json::Value::String(k.into()));
        }
        serde_json::to_string(&serde_json::Value::Object(obj)).unwrap_or_default()
    }
}

/// A sink that consumes [`AuditEvent`]s.
///
/// Sinks must be `Send + Sync` because `Store` is shared across
/// threads. `emit` is intentionally infallible — the audit path must
/// never poison a verb's result. Sink implementations swallow IO
/// errors and degrade silently.
pub trait AuditSink: Send + Sync {
    fn emit(&self, event: &AuditEvent);
}

/// A sink that drops every event. Used to disable audit emission
/// entirely without making the sink itself optional.
pub struct NoopSink;

impl AuditSink for NoopSink {
    fn emit(&self, _event: &AuditEvent) {}
}

/// Writes each event as one JSON line to stderr.
pub struct StderrSink;

impl AuditSink for StderrSink {
    fn emit(&self, event: &AuditEvent) {
        let line = event.to_json_line();
        let _ = writeln!(io::stderr(), "{line}");
    }
}

/// Append-only file sink, one JSON event per line.
///
/// The file is opened in append mode with mode `0o600` on Unix (the
/// audit stream may carry which URLs were accessed and at what time;
/// that's not a secret value but it is process-history a hostile
/// uid-peer should not necessarily read). A `Mutex<File>` serializes
/// writes so concurrent emitters cannot interleave bytes.
pub struct FileSink {
    path: PathBuf,
    file: Mutex<File>,
}

impl FileSink {
    /// Open the audit file in append mode, creating it if missing.
    ///
    /// On Unix, sets the file mode to `0o600` after open. On other
    /// platforms the OS-default ACL applies.
    pub fn open(path: impl AsRef<Path>) -> io::Result<Self> {
        let path = path.as_ref().to_path_buf();

        // On Unix, set mode 0o600 at open time via OpenOptionsExt so a
        // same-uid attacker cannot win the race between create and the
        // subsequent chmod. The mode only applies when the file is
        // newly created; existing files keep their current
        // permissions (caller's responsibility — we don't widen).
        let file;
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            file = OpenOptions::new()
                .create(true)
                .append(true)
                .mode(0o600)
                .open(&path)?;
        }
        #[cfg(not(unix))]
        {
            file = OpenOptions::new().create(true).append(true).open(&path)?;
        }

        Ok(Self {
            path,
            file: Mutex::new(file),
        })
    }

    /// Path the sink is writing to.
    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl AuditSink for FileSink {
    fn emit(&self, event: &AuditEvent) {
        let line = event.to_json_line();
        if let Ok(mut file) = self.file.lock() {
            let _ = writeln!(file, "{line}");
            let _ = file.flush();
        }
    }
}

/// Forwards each event to the local syslog daemon via `libc::syslog`.
///
/// Unix-only (`#[cfg(unix)]`) — Windows has no syslog equivalent
/// (`Event Log` / ETW are a different API surface). Windows callers
/// should use [`FileSink`] and ship the file to whatever ingest the
/// host runs.
///
/// Each call to `emit` invokes `libc::syslog(priority, "%s", line)`
/// where `priority` is `LOG_INFO | LOG_USER`. The libc client takes
/// care of socket-path portability (`/dev/log` on Linux,
/// `/var/run/syslog` on macOS) and RFC3164/5424 framing — we don't
/// reimplement either.
///
/// ## Process-singleton constraint
///
/// `openlog(3)` / `closelog(3)` mutate process-global state in the
/// libc syslog client — a second `openlog` call replaces the first
/// connection's ident, and `closelog` tears down the connection for
/// **every** holder. To avoid cross-close hazards, this type
/// deliberately:
///
/// 1. Leaks the `ident` `CString` (`Box::leak`) so the pointer
///    `openlog` retained stays valid for the process lifetime, and
/// 2. Does **not** implement `Drop` (no `closelog` call).
///
/// Construct at most one `SyslogSink` per process. The CLI does
/// exactly this via `resolve_audit_sink()`. Library consumers that
/// need a second syslog destination should wrap an existing
/// `Arc<SyslogSink>` rather than calling `SyslogSink::open` again.
#[cfg(unix)]
#[derive(Debug)]
pub struct SyslogSink {
    priority: i32,
}

#[cfg(unix)]
impl SyslogSink {
    /// Open a syslog connection with `ident` (program name shown in
    /// log entries). Default priority: `LOG_INFO | LOG_USER`.
    ///
    /// Returns `Err` only if `ident` contains an interior NUL. The
    /// underlying `openlog(3)` is infallible — it does not perform
    /// I/O until the first `syslog(3)` call.
    pub fn open(ident: &str) -> io::Result<Self> {
        let cstr = std::ffi::CString::new(ident).map_err(|e| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("syslog ident contains NUL: {e}"),
            )
        })?;
        // The libc syslog client retains `ident` by pointer for the
        // life of the connection. Leak the CString so the pointer
        // stays valid for the process lifetime — see the type's
        // doc-comment for the singleton rationale.
        let leaked: &'static std::ffi::CStr = Box::leak(cstr.into_boxed_c_str());
        // SAFETY: leaked.as_ptr() is valid for 'static; option = 0
        // and facility = LOG_USER are POSIX-defined constants safe in
        // any process state.
        unsafe {
            libc::openlog(leaked.as_ptr(), 0, libc::LOG_USER);
        }
        Ok(Self {
            priority: libc::LOG_INFO | libc::LOG_USER,
        })
    }
}

#[cfg(unix)]
impl AuditSink for SyslogSink {
    fn emit(&self, event: &AuditEvent) {
        let line = event.to_json_line();
        // libc::syslog expects a NUL-terminated C string. Constructing
        // a CString allocates; that's acceptable on the audit path
        // (one allocation per event, off the hot secret-fetch path).
        // If the line contains an interior NUL (it can't, JSON has no
        // NUL bytes by construction) the emit silently drops.
        if let Ok(c) = std::ffi::CString::new(line) {
            // SAFETY: priority is a valid combined facility|level
            // bitmask; format is the literal "%s\0" with one
            // matching `*const c_char` argument; `c.as_ptr()` is
            // valid for the duration of the call. No interior NUL
            // (CString::new enforces).
            unsafe {
                libc::syslog(self.priority, c"%s".as_ptr(), c.as_ptr());
            }
        }
    }
}

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

    #[test]
    fn verb_labels_are_stable_strings() {
        // Soft guard against accidental relabeling — every verb's
        // start/done pair must be discoverable as a `*.start` /
        // `*.done` pattern.
        for v in [
            Verb::Get,
            Verb::Put,
            Verb::List,
            Verb::Delete,
            Verb::Exists,
            Verb::Cp,
            Verb::Diff,
        ] {
            assert!(v.start_label().ends_with(".start"));
            assert!(v.done_label().ends_with(".done"));
        }
    }

    #[test]
    fn start_event_serializes_minimal_fields() {
        let ev = AuditEvent::start(Verb::Get, "vault");
        let json = ev.to_json_line();
        assert!(json.contains("\"event\":\"get.start\""));
        assert!(json.contains("\"src_scheme\":\"vault\""));
        assert!(json.contains("\"outcome\":\"started\""));
        assert!(!json.contains("dst_scheme"));
        assert!(!json.contains("error_kind"));
    }

    #[test]
    fn done_event_with_dst_and_error_kind() {
        let ev = AuditEvent::done(Verb::Cp, "vault", "error")
            .with_dst_scheme("aws-sm")
            .with_error_kind("not_found");
        let json = ev.to_json_line();
        assert!(json.contains("\"event\":\"cp.done\""));
        assert!(json.contains("\"src_scheme\":\"vault\""));
        assert!(json.contains("\"dst_scheme\":\"aws-sm\""));
        assert!(json.contains("\"outcome\":\"error\""));
        assert!(json.contains("\"error_kind\":\"not_found\""));
    }

    #[test]
    fn stderr_sink_is_object_safe() {
        let s: Arc<dyn AuditSink> = Arc::new(StderrSink);
        s.emit(&AuditEvent::start(Verb::Get, "env"));
    }

    #[test]
    fn noop_sink_emits_nothing_observable() {
        let s: Arc<dyn AuditSink> = Arc::new(NoopSink);
        s.emit(&AuditEvent::start(Verb::Get, "env"));
    }

    #[test]
    fn file_sink_appends_one_line_per_event() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("audit.log");
        let sink = FileSink::open(&path).unwrap();
        sink.emit(&AuditEvent::start(Verb::Get, "env"));
        sink.emit(&AuditEvent::done(Verb::Get, "env", "ok"));
        let body = std::fs::read_to_string(&path).unwrap();
        assert_eq!(body.lines().count(), 2);
        assert!(body.lines().next().unwrap().contains("get.start"));
        assert!(body.lines().nth(1).unwrap().contains("get.done"));
    }

    #[cfg(unix)]
    #[test]
    fn file_sink_sets_0600_on_unix() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("audit.log");
        let _sink = FileSink::open(&path).unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o600);
    }

    #[cfg(unix)]
    #[test]
    fn syslog_sink_constructs_and_emits_without_panic() {
        // We cannot assert that syslogd actually received the message
        // (no portable way to read the local syslog from a unit test
        // without depending on the daemon being configured). What we
        // can assert: openlog/syslog/closelog do not panic, and the
        // sink is object-safe behind `Arc<dyn AuditSink>`. If syslogd
        // is absent the libc client silently drops — that is the
        // documented degrade behavior.
        let sink: Arc<dyn AuditSink> = Arc::new(SyslogSink::open("hasp-test").expect("openlog"));
        sink.emit(&AuditEvent::start(Verb::Get, "env"));
        sink.emit(&AuditEvent::done(Verb::Get, "env", "ok"));
    }

    #[cfg(unix)]
    #[test]
    fn syslog_sink_rejects_ident_with_interior_nul() {
        let err = SyslogSink::open("hasp\0bad").unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
    }
}