1use serde_json::Value;
23use time::OffsetDateTime;
24
25#[derive(Clone, Copy, PartialEq, Eq, Debug)]
27pub enum EventKind {
28 Created,
29 Expires,
30 Rotation,
31}
32
33impl EventKind {
34 fn category(self) -> &'static str {
37 match self {
38 EventKind::Created => "CREATED",
39 EventKind::Expires => "EXPIRES",
40 EventKind::Rotation => "ROTATION",
41 }
42 }
43
44 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
55pub struct IcsOptions {
57 pub kinds: Vec<EventKind>,
58 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
86pub 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 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
110pub 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 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
141fn 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
160pub 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
171pub 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
186pub 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
209pub 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
223pub 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 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 alarm_days_before: 7,
318 });
319 }
320 }
321
322 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 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
385pub 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 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 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 format!("{}\r\n", folded.join("\r\n"))
436}
437
438pub 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 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 assert_eq!(folded.replace("\r\n ", ""), line);
470 }
471
472 #[test]
473 fn rotation_falls_back_to_the_creation_date() {
474 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 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 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 assert_eq!(next_day("20261231"), "20270101");
543 assert_eq!(next_day("20260228"), "20260301");
544 }
545}