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
#[cfg(unix)]
use std::fs::File;
use std::{
    fs,
    io::Write as _,
    path::{Path, PathBuf},
};

use base64ct::{Base64UrlUnpadded, Encoding as _};
use miette::Diagnostic;
use sha2::{Digest as _, Sha256};
use thiserror::Error;

use crate::{
    config::{CredentialStore, config_path},
    error::CliConfigError,
};

const KEYRING_SERVICE: &str = "s2-cli";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialKind {
    AccessToken,
    OAuth,
}

impl CredentialKind {
    fn storage_key_prefix(self) -> &'static str {
        match self {
            Self::AccessToken => "access-token",
            Self::OAuth => "oauth",
        }
    }
}

#[derive(Debug, Error, Diagnostic)]
pub enum CredentialStoreError {
    #[error("The OS credential store is unavailable: {0}")]
    #[diagnostic(help(
        "Unlock or enable the OS credential store and retry. To explicitly use a private plaintext file, pass `--insecure-storage`."
    ))]
    SecureStorageUnavailable(String),

    #[error("Failed to access the OS credential store: {0}")]
    CredentialStore(String),

    #[error("Stored credential was not found")]
    #[diagnostic(help(
        "Run `s2 login` again for browser authentication, or `s2 auth access-token set` for an access token."
    ))]
    CredentialNotFound,

    #[error("Failed to {action} the credentials file")]
    CredentialFile {
        action: &'static str,
        #[source]
        source: std::io::Error,
    },

    #[error("Invalid credential path")]
    InvalidPath,

    #[cfg(unix)]
    #[error("The private credential file is not safely protected: {0}")]
    #[diagnostic(help(
        "Restrict the credential directory to the current user and the file to mode 0600, or remove it and authenticate again."
    ))]
    UnsafeCredentialFile(&'static str),

    #[error(transparent)]
    #[diagnostic(transparent)]
    Config(#[from] CliConfigError),
}

impl CredentialStoreError {
    pub fn is_transient(&self) -> bool {
        matches!(
            self,
            Self::SecureStorageUnavailable(_)
                | Self::CredentialStore(_)
                | Self::CredentialFile { .. }
        )
    }
}

pub fn save(
    kind: CredentialKind,
    credential_id: &str,
    store: CredentialStore,
    bytes: &[u8],
) -> Result<(), CredentialStoreError> {
    match store {
        CredentialStore::Keyring => {
            let value = std::str::from_utf8(bytes)
                .expect("credential JSON serialization always produces valid UTF-8");
            let entry = keyring_entry(kind, credential_id).map_err(|error| {
                CredentialStoreError::SecureStorageUnavailable(error.to_string())
            })?;
            entry
                .set_password(value)
                .map_err(|error| CredentialStoreError::SecureStorageUnavailable(error.to_string()))
        }
        CredentialStore::File => {
            write_private_file(&credential_file_path(kind, credential_id)?, bytes)
        }
    }
}

pub fn load(
    kind: CredentialKind,
    credential_id: &str,
    store: CredentialStore,
) -> Result<Vec<u8>, CredentialStoreError> {
    match store {
        CredentialStore::Keyring => {
            let entry = keyring_entry(kind, credential_id)
                .map_err(|error| CredentialStoreError::CredentialStore(error.to_string()))?;
            entry
                .get_password()
                .map(String::into_bytes)
                .map_err(|error| match error {
                    keyring::Error::NoEntry => CredentialStoreError::CredentialNotFound,
                    error => CredentialStoreError::CredentialStore(error.to_string()),
                })
        }
        CredentialStore::File => {
            let path = credential_file_path(kind, credential_id)?;
            secure_private_file_for_read(&path)?;
            fs::read(path).map_err(|source| {
                if source.kind() == std::io::ErrorKind::NotFound {
                    CredentialStoreError::CredentialNotFound
                } else {
                    CredentialStoreError::CredentialFile {
                        action: "read",
                        source,
                    }
                }
            })
        }
    }
}

pub fn delete(
    kind: CredentialKind,
    credential_id: &str,
    store: CredentialStore,
) -> Result<(), CredentialStoreError> {
    match store {
        CredentialStore::Keyring => {
            let entry = keyring_entry(kind, credential_id)
                .map_err(|error| CredentialStoreError::CredentialStore(error.to_string()))?;
            match entry.delete_credential() {
                Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
                Err(error) => Err(CredentialStoreError::CredentialStore(error.to_string())),
            }
        }
        CredentialStore::File => {
            let path = credential_file_path(kind, credential_id)?;
            match fs::remove_file(&path) {
                Ok(()) => {
                    let parent = path.parent().ok_or(CredentialStoreError::InvalidPath)?;
                    // Deletion already committed; a directory-sync failure is not recoverable.
                    let _ = sync_directory(parent);
                    Ok(())
                }
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
                Err(source) => Err(CredentialStoreError::CredentialFile {
                    action: "delete",
                    source,
                }),
            }
        }
    }
}

pub fn credential_file_path(
    kind: CredentialKind,
    credential_id: &str,
) -> Result<PathBuf, CredentialStoreError> {
    let digest = Sha256::digest(credential_id.as_bytes());
    let filename = format!(
        "{}-{}.json",
        kind.storage_key_prefix(),
        Base64UrlUnpadded::encode_string(digest.as_slice())
    );
    Ok(config_path()?.with_file_name(filename))
}

pub fn credential_location(
    kind: CredentialKind,
    credential_id: &str,
    store: CredentialStore,
) -> String {
    match store {
        CredentialStore::Keyring => format!(
            "OS credential store service `{KEYRING_SERVICE}`, account `{}`",
            keyring_account(kind, credential_id)
        ),
        CredentialStore::File => credential_file_path(kind, credential_id)
            .map(|path| path.display().to_string())
            .unwrap_or_else(|_| format!("credential ID `{credential_id}`")),
    }
}

fn keyring_entry(
    kind: CredentialKind,
    credential_id: &str,
) -> Result<keyring::Entry, keyring::Error> {
    keyring::Entry::new(KEYRING_SERVICE, &keyring_account(kind, credential_id))
}

fn keyring_account(kind: CredentialKind, credential_id: &str) -> String {
    format!("{}:{credential_id}", kind.storage_key_prefix())
}

fn write_private_file(path: &Path, bytes: &[u8]) -> Result<(), CredentialStoreError> {
    let parent = path.parent().ok_or(CredentialStoreError::InvalidPath)?;
    fs::create_dir_all(parent).map_err(|source| CredentialStoreError::CredentialFile {
        action: "create the parent directory for",
        source,
    })?;
    secure_directory(parent)?;

    let mut temp = tempfile::NamedTempFile::new_in(parent).map_err(|source| {
        CredentialStoreError::CredentialFile {
            action: "create",
            source,
        }
    })?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        temp.as_file()
            .set_permissions(fs::Permissions::from_mode(0o600))
            .map_err(|source| CredentialStoreError::CredentialFile {
                action: "secure",
                source,
            })?;
    }
    temp.write_all(bytes)
        .and_then(|()| temp.as_file_mut().sync_all())
        .map_err(|source| CredentialStoreError::CredentialFile {
            action: "write",
            source,
        })?;
    temp.persist(path)
        .map_err(|error| CredentialStoreError::CredentialFile {
            action: "replace",
            source: error.error,
        })?;
    // Rename committed the credential; a directory-sync failure cannot be rolled back.
    let _ = sync_directory(parent);
    Ok(())
}

#[cfg(unix)]
fn secure_private_file_for_read(path: &Path) -> Result<(), CredentialStoreError> {
    use std::os::unix::fs::PermissionsExt as _;

    let parent = path.parent().ok_or(CredentialStoreError::InvalidPath)?;
    let directory = fs::symlink_metadata(parent).map_err(|source| {
        if source.kind() == std::io::ErrorKind::NotFound {
            CredentialStoreError::CredentialNotFound
        } else {
            CredentialStoreError::CredentialFile {
                action: "inspect the parent directory for",
                source,
            }
        }
    })?;
    if !directory.file_type().is_dir() {
        return Err(CredentialStoreError::UnsafeCredentialFile(
            "the parent path is not a directory",
        ));
    }
    if directory.permissions().mode() & 0o077 != 0 {
        fs::set_permissions(parent, fs::Permissions::from_mode(0o700)).map_err(|source| {
            CredentialStoreError::CredentialFile {
                action: "secure the parent directory for",
                source,
            }
        })?;
    }

    let file = fs::symlink_metadata(path).map_err(|source| {
        if source.kind() == std::io::ErrorKind::NotFound {
            CredentialStoreError::CredentialNotFound
        } else {
            CredentialStoreError::CredentialFile {
                action: "inspect",
                source,
            }
        }
    })?;
    if !file.file_type().is_file() {
        return Err(CredentialStoreError::UnsafeCredentialFile(
            "the credential path is not a regular file",
        ));
    }
    if file.permissions().mode() & 0o077 != 0 {
        fs::set_permissions(path, fs::Permissions::from_mode(0o600)).map_err(|source| {
            CredentialStoreError::CredentialFile {
                action: "secure",
                source,
            }
        })?;
    }
    Ok(())
}

#[cfg(not(unix))]
fn secure_private_file_for_read(_path: &Path) -> Result<(), CredentialStoreError> {
    Ok(())
}

#[cfg(unix)]
fn secure_directory(path: &Path) -> Result<(), CredentialStoreError> {
    use std::os::unix::fs::PermissionsExt as _;

    fs::set_permissions(path, fs::Permissions::from_mode(0o700)).map_err(|source| {
        CredentialStoreError::CredentialFile {
            action: "secure the parent directory for",
            source,
        }
    })
}

#[cfg(not(unix))]
fn secure_directory(_path: &Path) -> Result<(), CredentialStoreError> {
    Ok(())
}

#[cfg(unix)]
fn sync_directory(path: &Path) -> Result<(), CredentialStoreError> {
    File::open(path)
        .and_then(|directory| directory.sync_all())
        .map_err(|source| CredentialStoreError::CredentialFile {
            action: "sync the parent directory for",
            source,
        })
}

#[cfg(not(unix))]
fn sync_directory(_path: &Path) -> Result<(), CredentialStoreError> {
    Ok(())
}

#[cfg(all(test, unix))]
mod tests {
    use std::os::unix::fs::{PermissionsExt as _, symlink};

    use super::*;

    #[test]
    fn private_file_is_atomically_replaced_with_user_only_permissions() {
        let directory = tempfile::tempdir().unwrap();
        let credential_directory = directory.path().join("s2");
        let path = credential_directory.join("credential.json");

        write_private_file(&path, b"first").unwrap();
        write_private_file(&path, b"second").unwrap();

        assert_eq!(fs::read(&path).unwrap(), b"second");
        assert_eq!(
            fs::metadata(&credential_directory)
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o700
        );
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert_eq!(fs::read_dir(&credential_directory).unwrap().count(), 1);
    }

    #[test]
    fn private_file_permissions_are_repaired_before_reading() {
        let directory = tempfile::tempdir().unwrap();
        let credential_directory = directory.path().join("s2");
        let path = credential_directory.join("credential.json");
        write_private_file(&path, b"secret").unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
        fs::set_permissions(&credential_directory, fs::Permissions::from_mode(0o755)).unwrap();

        secure_private_file_for_read(&path).unwrap();

        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert_eq!(
            fs::metadata(&credential_directory)
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o700
        );
    }

    #[test]
    fn private_file_symlinks_are_rejected() {
        let directory = tempfile::tempdir().unwrap();
        let credential_directory = directory.path().join("s2");
        fs::create_dir(&credential_directory).unwrap();
        fs::set_permissions(&credential_directory, fs::Permissions::from_mode(0o700)).unwrap();
        let target = credential_directory.join("target.json");
        fs::write(&target, b"secret").unwrap();
        fs::set_permissions(&target, fs::Permissions::from_mode(0o600)).unwrap();
        let link = credential_directory.join("credential.json");
        symlink(&target, &link).unwrap();

        assert!(matches!(
            secure_private_file_for_read(&link),
            Err(CredentialStoreError::UnsafeCredentialFile(_))
        ));
    }
}