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 = nils_common::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    nils_common::fs::write_atomic(path, contents, mode).map_err(io_error_from_atomic_write)
39}
40
41pub(crate) fn write_timestamp(path: &Path, iso: Option<&str>) -> io::Result<()> {
42    nils_common::fs::write_timestamp(path, iso).map_err(io_error_from_timestamp_write)
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 io_error_from_atomic_write(err: nils_common::fs::AtomicWriteError) -> io::Error {
141    match err {
142        nils_common::fs::AtomicWriteError::CreateParentDir { source, .. }
143        | nils_common::fs::AtomicWriteError::CreateTempFile { source, .. }
144        | nils_common::fs::AtomicWriteError::WriteTempFile { source, .. }
145        | nils_common::fs::AtomicWriteError::SetPermissions { source, .. }
146        | nils_common::fs::AtomicWriteError::ReplaceFile { source, .. } => source,
147        nils_common::fs::AtomicWriteError::TempPathExhausted { target, .. } => io::Error::new(
148            io::ErrorKind::AlreadyExists,
149            format!("failed to create unique temp file for {}", target.display()),
150        ),
151    }
152}
153
154fn io_error_from_timestamp_write(err: nils_common::fs::TimestampError) -> io::Error {
155    match err {
156        nils_common::fs::TimestampError::CreateParentDir { source, .. }
157        | nils_common::fs::TimestampError::WriteFile { source, .. }
158        | nils_common::fs::TimestampError::RemoveFile { source, .. } => source,
159    }
160}
161
162fn parse_u32(raw: &str) -> Option<u32> {
163    raw.parse::<u32>().ok()
164}
165
166fn parse_i64(raw: &str) -> Option<i64> {
167    raw.parse::<i64>().ok()
168}
169
170fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
171    let adjusted_year = year - i64::from(month <= 2);
172    let era = if adjusted_year >= 0 {
173        adjusted_year / 400
174    } else {
175        (adjusted_year - 399) / 400
176    };
177    let year_of_era = adjusted_year - era * 400;
178    let month_prime = month + if month > 2 { -3 } else { 9 };
179    let day_of_year = (153 * month_prime + 2) / 5 + day - 1;
180    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
181    era * 146_097 + day_of_era - 719_468
182}
183
184fn epoch_to_utc_iso(epoch: i64) -> String {
185    let days = epoch.div_euclid(86_400);
186    let seconds_of_day = epoch.rem_euclid(86_400);
187
188    let (year, month, day) = civil_from_days(days);
189    let hour = seconds_of_day / 3_600;
190    let minute = (seconds_of_day % 3_600) / 60;
191    let second = seconds_of_day % 60;
192
193    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
194}
195
196fn civil_from_days(days_since_epoch: i64) -> (i64, i64, i64) {
197    let z = days_since_epoch + 719_468;
198    let era = if z >= 0 {
199        z / 146_097
200    } else {
201        (z - 146_096) / 146_097
202    };
203    let day_of_era = z - era * 146_097;
204    let year_of_era =
205        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
206    let year = year_of_era + era * 400;
207    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
208    let month_prime = (5 * day_of_year + 2) / 153;
209    let day = day_of_year - (153 * month_prime + 2) / 5 + 1;
210    let month = month_prime + if month_prime < 10 { 3 } else { -9 };
211    let full_year = year + i64::from(month <= 2);
212
213    (full_year, month, day)
214}
215
216#[cfg(test)]
217mod tests {
218    use super::{normalize_iso, parse_rfc3339_epoch};
219
220    #[test]
221    fn normalize_iso_removes_fractional_seconds() {
222        assert_eq!(
223            normalize_iso("2025-01-20T12:34:56.789Z"),
224            "2025-01-20T12:34:56Z"
225        );
226    }
227
228    #[test]
229    fn parse_rfc3339_epoch_supports_zulu_and_offsets() {
230        assert_eq!(parse_rfc3339_epoch("1970-01-01T00:00:00Z"), Some(0));
231        assert_eq!(parse_rfc3339_epoch("1970-01-01T01:00:00+01:00"), Some(0));
232    }
233}