Skip to main content

gemini_cli/auth/
mod.rs

1pub mod auto_refresh;
2pub mod current;
3pub mod login;
4pub mod output;
5pub mod refresh;
6pub mod remove;
7pub mod save;
8pub mod sync;
9pub mod use_secret;
10
11use std::io;
12use std::path::{Path, PathBuf};
13use std::time::{SystemTime, UNIX_EPOCH};
14
15pub(crate) const SECRET_FILE_MODE: u32 = crate::fs::SECRET_FILE_MODE;
16
17pub fn identity_from_auth_file(path: &Path) -> io::Result<Option<String>> {
18    crate::runtime::auth::identity_from_auth_file(path).map_err(core_error_to_io)
19}
20
21pub fn email_from_auth_file(path: &Path) -> io::Result<Option<String>> {
22    crate::runtime::auth::email_from_auth_file(path).map_err(core_error_to_io)
23}
24
25pub fn account_id_from_auth_file(path: &Path) -> io::Result<Option<String>> {
26    crate::runtime::auth::account_id_from_auth_file(path).map_err(core_error_to_io)
27}
28
29pub fn last_refresh_from_auth_file(path: &Path) -> io::Result<Option<String>> {
30    crate::runtime::auth::last_refresh_from_auth_file(path).map_err(core_error_to_io)
31}
32
33pub fn identity_key_from_auth_file(path: &Path) -> io::Result<Option<String>> {
34    crate::runtime::auth::identity_key_from_auth_file(path).map_err(core_error_to_io)
35}
36
37pub(crate) fn write_atomic(path: &Path, contents: &[u8], mode: u32) -> io::Result<()> {
38    crate::fs::write_atomic(path, contents, mode)
39}
40
41pub(crate) fn write_timestamp(path: &Path, iso: Option<&str>) -> io::Result<()> {
42    crate::fs::write_timestamp(path, iso)
43}
44
45pub(crate) fn normalize_iso(raw: &str) -> String {
46    let mut trimmed = crate::json::strip_newlines(raw);
47    if let Some(dot) = trimmed.find('.')
48        && trimmed.ends_with('Z')
49    {
50        trimmed.truncate(dot);
51        trimmed.push('Z');
52    }
53    trimmed
54}
55
56pub(crate) fn parse_rfc3339_epoch(raw: &str) -> Option<i64> {
57    let normalized = normalize_iso(raw);
58    let (datetime, offset_seconds) = if normalized.ends_with('Z') {
59        (&normalized[..normalized.len().saturating_sub(1)], 0i64)
60    } else {
61        if normalized.len() < 6 {
62            return None;
63        }
64        let tail_index = normalized.len() - 6;
65        let sign = normalized.as_bytes().get(tail_index).copied()? as char;
66        if sign != '+' && sign != '-' {
67            return None;
68        }
69        if normalized.as_bytes().get(tail_index + 3).copied()? as char != ':' {
70            return None;
71        }
72        let hours = parse_u32(&normalized[tail_index + 1..tail_index + 3])? as i64;
73        let minutes = parse_u32(&normalized[tail_index + 4..])? as i64;
74        let mut offset = hours * 3600 + minutes * 60;
75        if sign == '-' {
76            offset = -offset;
77        }
78        (&normalized[..tail_index], offset)
79    };
80
81    if datetime.len() != 19 {
82        return None;
83    }
84    if datetime.as_bytes().get(4).copied()? as char != '-'
85        || datetime.as_bytes().get(7).copied()? as char != '-'
86        || datetime.as_bytes().get(10).copied()? as char != 'T'
87        || datetime.as_bytes().get(13).copied()? as char != ':'
88        || datetime.as_bytes().get(16).copied()? as char != ':'
89    {
90        return None;
91    }
92
93    let year = parse_i64(&datetime[0..4])?;
94    let month = parse_u32(&datetime[5..7])? as i64;
95    let day = parse_u32(&datetime[8..10])? as i64;
96    let hour = parse_u32(&datetime[11..13])? as i64;
97    let minute = parse_u32(&datetime[14..16])? as i64;
98    let second = parse_u32(&datetime[17..19])? as i64;
99
100    if !(1..=12).contains(&month)
101        || !(1..=31).contains(&day)
102        || hour > 23
103        || minute > 59
104        || second > 60
105    {
106        return None;
107    }
108
109    let days = days_from_civil(year, month, day);
110    let local_epoch = days * 86_400 + hour * 3_600 + minute * 60 + second;
111    Some(local_epoch - offset_seconds)
112}
113
114pub(crate) fn now_epoch_seconds() -> i64 {
115    SystemTime::now()
116        .duration_since(UNIX_EPOCH)
117        .map(|duration| duration.as_secs() as i64)
118        .unwrap_or(0)
119}
120
121pub(crate) fn now_utc_iso() -> String {
122    epoch_to_utc_iso(now_epoch_seconds())
123}
124
125pub(crate) fn temp_file_path(prefix: &str) -> PathBuf {
126    let mut path = std::env::temp_dir();
127    let pid = std::process::id();
128    let nanos = SystemTime::now()
129        .duration_since(UNIX_EPOCH)
130        .map(|duration| duration.as_nanos())
131        .unwrap_or(0);
132    path.push(format!("{prefix}-{pid}-{nanos}.json"));
133    path
134}
135
136fn core_error_to_io(err: crate::runtime::CoreError) -> io::Error {
137    io::Error::other(err.to_string())
138}
139
140fn parse_u32(raw: &str) -> Option<u32> {
141    raw.parse::<u32>().ok()
142}
143
144fn parse_i64(raw: &str) -> Option<i64> {
145    raw.parse::<i64>().ok()
146}
147
148fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
149    let adjusted_year = year - i64::from(month <= 2);
150    let era = if adjusted_year >= 0 {
151        adjusted_year / 400
152    } else {
153        (adjusted_year - 399) / 400
154    };
155    let year_of_era = adjusted_year - era * 400;
156    let month_prime = month + if month > 2 { -3 } else { 9 };
157    let day_of_year = (153 * month_prime + 2) / 5 + day - 1;
158    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
159    era * 146_097 + day_of_era - 719_468
160}
161
162fn epoch_to_utc_iso(epoch: i64) -> String {
163    let days = epoch.div_euclid(86_400);
164    let seconds_of_day = epoch.rem_euclid(86_400);
165
166    let (year, month, day) = civil_from_days(days);
167    let hour = seconds_of_day / 3_600;
168    let minute = (seconds_of_day % 3_600) / 60;
169    let second = seconds_of_day % 60;
170
171    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
172}
173
174fn civil_from_days(days_since_epoch: i64) -> (i64, i64, i64) {
175    let z = days_since_epoch + 719_468;
176    let era = if z >= 0 {
177        z / 146_097
178    } else {
179        (z - 146_096) / 146_097
180    };
181    let day_of_era = z - era * 146_097;
182    let year_of_era =
183        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
184    let year = year_of_era + era * 400;
185    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
186    let month_prime = (5 * day_of_year + 2) / 153;
187    let day = day_of_year - (153 * month_prime + 2) / 5 + 1;
188    let month = month_prime + if month_prime < 10 { 3 } else { -9 };
189    let full_year = year + i64::from(month <= 2);
190
191    (full_year, month, day)
192}
193
194#[cfg(test)]
195mod tests {
196    use super::{normalize_iso, parse_rfc3339_epoch};
197
198    #[test]
199    fn normalize_iso_removes_fractional_seconds() {
200        assert_eq!(
201            normalize_iso("2025-01-20T12:34:56.789Z"),
202            "2025-01-20T12:34:56Z"
203        );
204    }
205
206    #[test]
207    fn parse_rfc3339_epoch_supports_zulu_and_offsets() {
208        assert_eq!(parse_rfc3339_epoch("1970-01-01T00:00:00Z"), Some(0));
209        assert_eq!(parse_rfc3339_epoch("1970-01-01T01:00:00+01:00"), Some(0));
210    }
211}