-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcredentials.rs
More file actions
139 lines (121 loc) · 4.51 KB
/
credentials.rs
File metadata and controls
139 lines (121 loc) · 4.51 KB
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
// Copyright 2023 Helsing GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use miette::{Context, IntoDiagnostic};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, io::ErrorKind, path::PathBuf};
use tokio::fs;
use crate::{
errors::{DeserializationError, FileExistsError, ReadError, SerializationError, WriteError},
registry::Registry,
ManagedFile,
};
/// Filename of the credential store
pub const CREDENTIALS_FILE: &str = "credentials.toml";
/// Credential store for storing authentication data
///
/// This type represents a snapshot of the read credential store.
#[derive(Debug, Default, Clone)]
pub struct Credentials {
/// A mapping from registry to their corresponding tokens
pub tokens: HashMap<Registry, String>,
}
impl Credentials {
fn location() -> miette::Result<PathBuf> {
Ok(crate::home().into_diagnostic()?.join(CREDENTIALS_FILE))
}
/// Checks if the credentials exists
pub async fn exists() -> miette::Result<bool> {
fs::try_exists(Self::location()?)
.await
.into_diagnostic()
.wrap_err(FileExistsError(CREDENTIALS_FILE))
}
/// Reads the credentials from the file system
pub async fn read() -> miette::Result<Option<Self>> {
// if the file does not exist, we don't need to treat it as an error.
match fs::read_to_string(Self::location()?).await {
Ok(contents) => {
let raw: RawCredentialCollection = toml::from_str(&contents)
.into_diagnostic()
.wrap_err(DeserializationError(ManagedFile::Credentials))?;
Ok(Some(raw.into()))
}
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(error)
.into_diagnostic()
.wrap_err(ReadError(CREDENTIALS_FILE)),
}
}
/// Writes the credentials to the file system
pub async fn write(&self) -> miette::Result<()> {
let location = Self::location()?;
if let Some(parent) = location.parent() {
// if directory already exists, error is returned but that is fine
fs::create_dir(parent).await.ok();
}
let data: RawCredentialCollection = self.clone().into();
fs::write(
location,
toml::to_string(&data)
.into_diagnostic()
.wrap_err(SerializationError(ManagedFile::Credentials))?
.into_bytes(),
)
.await
.into_diagnostic()
.wrap_err(WriteError(CREDENTIALS_FILE))
}
/// Loads the credentials from the file system, returning default credentials if
/// they do not exist.
///
/// Note, this should not create files in the user's home directory, as we should
/// not be performing global stateful operations in absence of a user instruction.
pub async fn load() -> miette::Result<Self> {
Ok(Self::read().await?.unwrap_or_else(Credentials::default))
}
}
/// Credential store for storing authentication data. Serialization type.
#[derive(Serialize, Deserialize)]
struct RawCredentialCollection {
#[serde(skip_serializing_if = "Vec::is_empty", default)]
credentials: Vec<RawRegistryCredentials>,
}
/// Credentials for a single registry. Serialization type.
#[derive(Serialize, Deserialize)]
struct RawRegistryCredentials {
registry: Registry,
token: String,
}
impl From<RawCredentialCollection> for Credentials {
fn from(value: RawCredentialCollection) -> Self {
let credentials = value
.credentials
.into_iter()
.map(|it| (it.registry, it.token))
.collect();
Self {
tokens: credentials,
}
}
}
impl From<Credentials> for RawCredentialCollection {
fn from(value: Credentials) -> Self {
let credentials = value
.tokens
.into_iter()
.map(|(registry, token)| RawRegistryCredentials { registry, token })
.collect();
Self { credentials }
}
}