Skip to main content

vault_core/
calendar.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! iCalendar (RFC 5545) feed for the vault's dates — the Rust twin of
4//! `src/ts/calendar.ts`.
5//!
6//! This is the fourth format in the project implemented twice, and it follows
7//! the rule the other three established: **one golden file, asserted from both
8//! sides**. `tests/fixtures/parity/calendar.ics` is written by the TypeScript
9//! suite and read back by `unv-app/tests/parity.rs`, because reviewing two
10//! implementations for agreement does not work — the first time that fixture
11//! ran for the exporters it found two live bugs.
12//!
13//! # What is deliberately not in the file
14//!
15//! No secret values, and no fingerprints either. An `.ics` is the least private
16//! thing this program writes: it exists to be handed to Google Calendar or a
17//! phone, which stores it unencrypted on hardware nobody here controls. A
18//! fingerprint is stable per value, so a feed carrying them would tell anyone
19//! holding two feeds which secrets are the same — an equality oracle over the
20//! vault, published to a third party. Names and dates travel; nothing else.
21
22use serde_json::Value;
23use time::OffsetDateTime;
24
25/// Which kinds of event to emit.
26#[derive(Clone, Copy, PartialEq, Eq, Debug)]
27pub enum EventKind {
28    Created,
29    Expires,
30    Rotation,
31}
32
33impl EventKind {
34    /// The `CATEGORIES` value, matching the TypeScript side's
35    /// `ev.kind.toUpperCase()`.
36    fn category(self) -> &'static str {
37        match self {
38            EventKind::Created => "CREATED",
39            EventKind::Expires => "EXPIRES",
40            EventKind::Rotation => "ROTATION",
41        }
42    }
43
44    /// Parses a CLI `--kind` value.
45    pub fn parse(s: &str) -> Option<Self> {
46        match s.to_ascii_lowercase().as_str() {
47            "created" | "creation" => Some(EventKind::Created),
48            "expires" | "expiry" | "expiring" => Some(EventKind::Expires),
49            "rotation" | "rotate" => Some(EventKind::Rotation),
50            _ => None,
51        }
52    }
53}
54
55/// Options for [`build_ics`].
56pub struct IcsOptions {
57    pub kinds: Vec<EventKind>,
58    /// `DTSTAMP` as an RFC 3339 string.
59    ///
60    /// Injectable for the same reason as the TypeScript side: a fixture that
61    /// embeds the wall clock cannot be compared with anything, and without a
62    /// fixed stamp the CLI and the app can never produce identical bytes.
63    pub now: String,
64    pub calendar_name: String,
65}
66
67impl Default for IcsOptions {
68    fn default() -> Self {
69        IcsOptions {
70            kinds: vec![EventKind::Created, EventKind::Expires, EventKind::Rotation],
71            now: crate::iso_now(),
72            calendar_name: "UnENVerse".to_string(),
73        }
74    }
75}
76
77struct CalEvent {
78    uid: String,
79    date: String,
80    summary: String,
81    description: String,
82    kind: EventKind,
83    alarm_days_before: u32,
84}
85
86/// RFC 5545 §3.3.11 escaping: backslash, semicolon, comma, newline.
87pub fn ics_escape(text: &str) -> String {
88    let mut out = String::with_capacity(text.len());
89    let mut chars = text.chars().peekable();
90    while let Some(c) = chars.next() {
91        match c {
92            '\\' => out.push_str("\\\\"),
93            ';' => out.push_str("\\;"),
94            ',' => out.push_str("\\,"),
95            '\r' => {
96                // CRLF collapses to one escaped newline, matching the
97                // TypeScript `/\r?\n/`.
98                if chars.peek() == Some(&'\n') {
99                    chars.next();
100                }
101                out.push_str("\\n");
102            }
103            '\n' => out.push_str("\\n"),
104            _ => out.push(c),
105        }
106    }
107    out
108}
109
110/// RFC 5545 §3.1 folding: 75 **octets** for the first line, 74 for each
111/// continuation, which begins with a space.
112///
113/// Octets, not characters — the same trap the TypeScript twin documents. A name
114/// with an accent or an emoji is several bytes per character, and folding by
115/// character count yields a line that is legal by one measure and illegal by the
116/// one a parser applies.
117pub fn ics_fold(line: &str) -> String {
118    let bytes = line.as_bytes();
119    if bytes.len() <= 75 {
120        return line.to_string();
121    }
122    let mut out = String::new();
123    let mut start = 0usize;
124    let mut limit = 75usize;
125    while start < bytes.len() {
126        let mut end = (start + limit).min(bytes.len());
127        // Never split a UTF-8 sequence: continuation bytes are 0b10xxxxxx.
128        while end > start && end < bytes.len() && (bytes[end] & 0xC0) == 0x80 {
129            end -= 1;
130        }
131        if !out.is_empty() {
132            out.push_str("\r\n ");
133        }
134        out.push_str(&line[start..end]);
135        start = end;
136        limit = 74;
137    }
138    out
139}
140
141/// Parses an RFC 3339 timestamp, falling back to a bare `YYYY-MM-DD` prefix.
142///
143/// The fallback is not laxity for its own sake: vault JSON can come from an
144/// imported backup or a hand edit, and a date-only `expires_at` is exactly what
145/// a human types. `new Date()` on the TypeScript side accepts it, so refusing
146/// it here would put an event in the app's calendar and not in the CLI's.
147fn parse_dt(iso: &str) -> Option<OffsetDateTime> {
148    if let Ok(dt) = OffsetDateTime::parse(iso, &time::format_description::well_known::Rfc3339) {
149        return Some(dt);
150    }
151    let head = iso.get(0..10)?;
152    let mut parts = head.split('-');
153    let y: i32 = parts.next()?.parse().ok()?;
154    let m: u8 = parts.next()?.parse().ok()?;
155    let d: u8 = parts.next()?.parse().ok()?;
156    let date = time::Date::from_calendar_date(y, time::Month::try_from(m).ok()?, d).ok()?;
157    Some(date.midnight().assume_utc())
158}
159
160/// `2026-08-26T21:00:00Z` → `20260826` (UTC), or `None` when unparseable.
161pub fn to_ics_date(iso: Option<&str>) -> Option<String> {
162    let dt = parse_dt(iso?)?;
163    Some(format!(
164        "{:04}{:02}{:02}",
165        dt.year(),
166        dt.month() as u8,
167        dt.day()
168    ))
169}
170
171/// `2026-08-26T21:00:00Z` → `20260826T210000Z`, for `DTSTAMP`.
172pub fn to_ics_stamp(iso: &str) -> String {
173    let dt = parse_dt(iso).unwrap_or(OffsetDateTime::UNIX_EPOCH);
174    let utc = dt.to_offset(time::UtcOffset::UTC);
175    format!(
176        "{:04}{:02}{:02}T{:02}{:02}{:02}Z",
177        utc.year(),
178        utc.month() as u8,
179        utc.day(),
180        utc.hour(),
181        utc.minute(),
182        utc.second()
183    )
184}
185
186/// The day after `YYYYMMDD` — what an all-day `DTEND` must be.
187pub fn next_day(yyyymmdd: &str) -> String {
188    let y: i32 = yyyymmdd[0..4].parse().unwrap_or(1970);
189    let m: u8 = yyyymmdd[4..6].parse().unwrap_or(1);
190    let d: u8 = yyyymmdd[6..8].parse().unwrap_or(1);
191    let date = time::Month::try_from(m)
192        .ok()
193        .and_then(|mm| time::Date::from_calendar_date(y, mm, d).ok())
194        .map(|dd| dd.next_day().unwrap_or(dd));
195    match date {
196        Some(dd) => format!("{:04}{:02}{:02}", dd.year(), dd.month() as u8, dd.day()),
197        None => yyyymmdd.to_string(),
198    }
199}
200
201fn s(entry: &Value, key: &str) -> Option<String> {
202    entry
203        .get(key)
204        .and_then(|v| v.as_str())
205        .filter(|v| !v.is_empty())
206        .map(str::to_string)
207}
208
209/// Display name: provider, plus whatever distinguishes it from its siblings.
210pub fn entry_label(entry: &Value) -> String {
211    let provider = s(entry, "provider").unwrap_or_default();
212    let extra: Vec<String> = ["key_id", "account_name"]
213        .iter()
214        .filter_map(|k| s(entry, k))
215        .collect();
216    if extra.is_empty() {
217        provider
218    } else {
219        format!("{provider} ({})", extra.join(" / "))
220    }
221}
222
223/// When rotation is next due, anchored on the last rotation or, failing that,
224/// on creation.
225///
226/// A 90-day key that has never been rotated is due 90 days after it was issued,
227/// not never. An entry with neither anchor gets no event: putting a deadline in
228/// someone's calendar that no evidence supports is worse than leaving it out.
229pub fn rotation_due(entry: &Value) -> Option<String> {
230    let days = entry.get("rotation_days").and_then(|v| v.as_i64())?;
231    if days <= 0 {
232        return None;
233    }
234    let anchor = s(entry, "last_rotated_at").or_else(|| s(entry, "created_at"))?;
235    let dt = parse_dt(&anchor)?;
236    let due = dt + time::Duration::days(days);
237    Some(format!(
238        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
239        due.year(),
240        due.month() as u8,
241        due.day(),
242        due.hour(),
243        due.minute(),
244        due.second()
245    ))
246}
247
248fn meta_lines(entry: &Value) -> String {
249    let mut parts = Vec::new();
250    if let Some(t) = s(entry, "secretType") {
251        parts.push(format!("Type: {t}"));
252    }
253    if let Some(e) = s(entry, "environment") {
254        parts.push(format!("Environment: {e}"));
255    }
256    let cats: Vec<String> = entry
257        .get("categories")
258        .and_then(|v| v.as_array())
259        .map(|a| {
260            a.iter()
261                .filter_map(|c| c.as_str())
262                .map(str::to_string)
263                .collect()
264        })
265        .unwrap_or_default();
266    if !cats.is_empty() {
267        parts.push(format!("Categories: {}", cats.join(", ")));
268    }
269    parts.join("\n")
270}
271
272fn events_for_entry(entry: &Value, kinds: &[EventKind]) -> Vec<CalEvent> {
273    let mut out = Vec::new();
274    // `id` is guaranteed by the app's `ensureEntryIds`; the fallback stops a
275    // hand-edited vault producing two events with one UID, which a calendar
276    // treats as one event updating itself.
277    let id = s(entry, "id").unwrap_or_else(|| {
278        format!(
279            "{}:{}:{}",
280            s(entry, "provider").unwrap_or_default(),
281            s(entry, "key_id").unwrap_or_default(),
282            s(entry, "account_name").unwrap_or_default()
283        )
284    });
285    let label = entry_label(entry);
286    let meta = meta_lines(entry);
287    let join = |head: String| -> String {
288        if meta.is_empty() {
289            head
290        } else {
291            format!("{head}\n{meta}")
292        }
293    };
294
295    if kinds.contains(&EventKind::Created) {
296        if let Some(date) = to_ics_date(s(entry, "created_at").as_deref()) {
297            out.push(CalEvent {
298                uid: format!("{id}-created@unenverse"),
299                date,
300                summary: format!("Created: {label}"),
301                description: join(format!("{label} was added to the vault.")),
302                kind: EventKind::Created,
303                alarm_days_before: 0,
304            });
305        }
306    }
307
308    if kinds.contains(&EventKind::Expires) {
309        if let Some(date) = to_ics_date(s(entry, "expires_at").as_deref()) {
310            out.push(CalEvent {
311                uid: format!("{id}-expires@unenverse"),
312                date,
313                summary: format!("Expires: {label}"),
314                description: join(format!("{label} expires on this day.")),
315                kind: EventKind::Expires,
316                // A reminder on the morning it dies arrives during the outage.
317                alarm_days_before: 7,
318            });
319        }
320    }
321
322    // Dates that live in a type's named variables rather than `expires_at`
323    // (Phase 24.5): a licence's maintenance window and an identity document's
324    // expiry. Date only, never the number or the holder: an identity document
325    // gets no metadata lines at all, because those lines carry account names and
326    // a calendar feed is shared further than the vault is.
327    if kinds.contains(&EventKind::Expires) {
328        let (var, what, with_meta) = match s(entry, "secretType").as_deref() {
329            Some("license_key") => ("maintenance_until", "Maintenance ends", true),
330            Some("identity_document") => ("expires", "Expires", false),
331            _ => ("", "", false),
332        };
333        if !var.is_empty() {
334            let value = entry
335                .get("extra_vars")
336                .and_then(|v| v.as_array())
337                .into_iter()
338                .flatten()
339                .find(|v| v.get("key").and_then(|k| k.as_str()) == Some(var))
340                .and_then(|v| v.get("value").and_then(|x| x.as_str()))
341                .map(str::to_string);
342            if let Some(date) = to_ics_date(value.as_deref()) {
343                // `entry_label` appends the account name, which for an identity
344                // document is the holder's.
345                let label = if with_meta {
346                    label.clone()
347                } else {
348                    s(entry, "provider").unwrap_or_default()
349                };
350                let head = format!("{label}: {}.", what.to_lowercase());
351                out.push(CalEvent {
352                    uid: format!("{id}-{var}@unenverse"),
353                    date,
354                    summary: format!("{what}: {label}"),
355                    description: if with_meta { join(head) } else { head },
356                    kind: EventKind::Expires,
357                    alarm_days_before: 30,
358                });
359            }
360        }
361    }
362
363    if kinds.contains(&EventKind::Rotation) {
364        if let Some(due) = rotation_due(entry) {
365            if let Some(date) = to_ics_date(Some(&due)) {
366                let days = entry
367                    .get("rotation_days")
368                    .and_then(|v| v.as_i64())
369                    .unwrap_or(0);
370                out.push(CalEvent {
371                    uid: format!("{id}-rotation@unenverse"),
372                    date,
373                    summary: format!("Rotate: {label}"),
374                    description: join(format!("{label} is due for rotation (every {days} days).")),
375                    kind: EventKind::Rotation,
376                    alarm_days_before: 3,
377                });
378            }
379        }
380    }
381
382    out
383}
384
385/// Builds the calendar. Byte-identical to `buildIcs` in `src/ts/calendar.ts`
386/// for the same input — that is what the parity fixture checks.
387pub fn build_ics(entries: &[Value], opts: &IcsOptions) -> String {
388    let stamp = to_ics_stamp(&opts.now);
389
390    let mut events: Vec<CalEvent> = entries
391        .iter()
392        .flat_map(|e| events_for_entry(e, &opts.kinds))
393        .collect();
394    // Sorted by date then UID so two runs over one vault produce the same bytes;
395    // otherwise the file's order follows the entry array and a reordered vault
396    // looks like a changed calendar to anything diffing it.
397    events.sort_by(|a, b| a.date.cmp(&b.date).then_with(|| a.uid.cmp(&b.uid)));
398
399    let mut lines: Vec<String> = vec![
400        "BEGIN:VCALENDAR".into(),
401        "VERSION:2.0".into(),
402        "PRODID:-//EnvVault//Secrets Calendar//EN".into(),
403        "CALSCALE:GREGORIAN".into(),
404        "METHOD:PUBLISH".into(),
405        format!("X-WR-CALNAME:{}", ics_escape(&opts.calendar_name)),
406        "X-WR-TIMEZONE:UTC".into(),
407    ];
408
409    for ev in &events {
410        lines.push("BEGIN:VEVENT".into());
411        lines.push(format!("UID:{}", ics_escape(&ev.uid)));
412        lines.push(format!("DTSTAMP:{stamp}"));
413        lines.push(format!("DTSTART;VALUE=DATE:{}", ev.date));
414        lines.push(format!("DTEND;VALUE=DATE:{}", next_day(&ev.date)));
415        lines.push(format!("SUMMARY:{}", ics_escape(&ev.summary)));
416        lines.push(format!("DESCRIPTION:{}", ics_escape(&ev.description)));
417        lines.push(format!("CATEGORIES:{}", ev.kind.category()));
418        // Markers, not commitments: three expiries on one day must not show the
419        // owner as busy all day.
420        lines.push("TRANSP:TRANSPARENT".into());
421        if ev.alarm_days_before > 0 {
422            lines.push("BEGIN:VALARM".into());
423            lines.push("ACTION:DISPLAY".into());
424            lines.push(format!("DESCRIPTION:{}", ics_escape(&ev.summary)));
425            lines.push(format!("TRIGGER:-P{}D", ev.alarm_days_before));
426            lines.push("END:VALARM".into());
427        }
428        lines.push("END:VEVENT".into());
429    }
430    lines.push("END:VCALENDAR".into());
431
432    let folded: Vec<String> = lines.iter().map(|l| ics_fold(l)).collect();
433    // CRLF is not optional in RFC 5545, and the trailing one is what makes the
434    // last line a line.
435    format!("{}\r\n", folded.join("\r\n"))
436}
437
438/// Number of `VEVENT` blocks in a rendered calendar — for the CLI's summary
439/// line, which reports a count rather than printing the file.
440pub fn event_count(ics: &str) -> usize {
441    ics.matches("BEGIN:VEVENT").count()
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447    use serde_json::json;
448
449    #[test]
450    fn escapes_the_four_reserved_characters() {
451        assert_eq!(ics_escape("a,b;c\\d\ne"), "a\\,b\\;c\\\\d\\ne");
452    }
453
454    #[test]
455    fn folds_on_octets_not_characters() {
456        // Ninety é characters: 90 chars, 180 bytes. Folding by character count
457        // would leave the first line legal-looking and 180 octets long.
458        let line = "é".repeat(90);
459        let folded = ics_fold(&line);
460        for part in folded.split("\r\n") {
461            let content = part.strip_prefix(' ').unwrap_or(part);
462            assert!(
463                content.len() <= 75,
464                "folded segment is {} octets",
465                content.len()
466            );
467        }
468        // Folding must be reversible: unfolding restores the original exactly.
469        assert_eq!(folded.replace("\r\n ", ""), line);
470    }
471
472    #[test]
473    fn rotation_falls_back_to_the_creation_date() {
474        // A 90-day key that has never been rotated is due 90 days after it was
475        // issued. Reporting "never" for it is how a cadence silently does
476        // nothing.
477        let e =
478            json!({ "provider": "X", "created_at": "2026-01-01T00:00:00Z", "rotation_days": 90 });
479        assert_eq!(
480            to_ics_date(rotation_due(&e).as_deref()),
481            Some("20260401".to_string())
482        );
483    }
484
485    #[test]
486    fn a_licence_and_an_identity_document_put_their_own_dates_on_the_calendar() {
487        let lic = json!({ "id": "l1", "provider": "Editor", "secretType": "license_key",
488            "extra_vars": [{ "key": "maintenance_until", "value": "2027-03-01" }] });
489        let doc = json!({ "id": "d1", "provider": "Passport", "secretType": "identity_document",
490            "account_name": "Holder Name", "api_key": "X1234567",
491            "extra_vars": [{ "key": "expires", "value": "2031-05-09" }] });
492        let ics = build_ics(&[lic, doc], &IcsOptions::default());
493        assert!(ics.contains("SUMMARY:Maintenance ends: Editor"), "{ics}");
494        assert!(ics.contains("DTSTART;VALUE=DATE:20270301"));
495        assert!(ics.contains("SUMMARY:Expires: Passport"));
496        assert!(ics.contains("20310509"));
497        // PII stays out of the feed: not the number, not the holder.
498        assert!(
499            !ics.contains("X1234567") && !ics.contains("Holder Name"),
500            "{ics}"
501        );
502    }
503
504    #[test]
505    fn an_entry_with_no_anchor_gets_no_rotation_event() {
506        let e = json!({ "provider": "X", "rotation_days": 90 });
507        assert!(rotation_due(&e).is_none());
508    }
509
510    #[test]
511    fn no_secret_value_reaches_the_calendar() {
512        // The guarantee the whole module exists to keep. An .ics is handed to a
513        // third-party calendar; a value in it is disclosed to that service.
514        let e = json!({
515            "id": "e1",
516            "provider": "GitHub",
517            "api_key": "ghp_SUPERSECRETVALUE",
518            "api_secret": "second-secret",
519            "created_at": "2026-01-01T00:00:00Z",
520            "expires_at": "2026-06-01T00:00:00Z"
521        });
522        let ics = build_ics(&[e], &IcsOptions::default());
523        assert!(!ics.contains("ghp_SUPERSECRETVALUE"));
524        assert!(!ics.contains("second-secret"));
525        assert!(ics.contains("SUMMARY:Created: GitHub"));
526    }
527
528    #[test]
529    fn uids_are_stable_so_a_re_import_updates_rather_than_duplicates() {
530        let e = json!({ "id": "abc", "provider": "X", "expires_at": "2026-06-01T00:00:00Z" });
531        let a = build_ics(std::slice::from_ref(&e), &IcsOptions::default());
532        let b = build_ics(&[e], &IcsOptions::default());
533        assert!(a.contains("UID:abc-expires@unenverse"));
534        assert_eq!(event_count(&a), 1);
535        assert_eq!(event_count(&b), 1);
536    }
537
538    #[test]
539    fn all_day_events_end_on_the_following_day() {
540        // An all-day DTEND is exclusive. Ending on the same day makes the event
541        // zero-length, and several clients then drop it entirely.
542        assert_eq!(next_day("20261231"), "20270101");
543        assert_eq!(next_day("20260228"), "20260301");
544    }
545}