|
| 1 | +use clap::{arg, Args, Subcommand}; |
| 2 | +use home; |
| 3 | +use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE}; |
| 4 | +use std::fs; |
| 5 | +use std::fs::File; |
| 6 | +use std::io; |
| 7 | +use std::io::{BufRead, BufReader}; |
| 8 | +use std::os::unix::fs::PermissionsExt; |
| 9 | +use std::path::{Path, PathBuf}; |
| 10 | + |
| 11 | +const DEFAULT_JWT_FILE: &str = ".agama/agama-jwt"; |
| 12 | +const DEFAULT_AUTH_URL: &str = "http://localhost:3000/api/authenticate"; |
| 13 | +const DEFAULT_FILE_MODE: u32 = 0o600; |
| 14 | + |
| 15 | +#[derive(Subcommand, Debug)] |
| 16 | +pub enum AuthCommands { |
| 17 | + /// Login with defined server. Result is JWT stored locally and made available to |
| 18 | + /// further use. Password can be provided by commandline option, from a file or it fallbacks |
| 19 | + /// into an interactive prompt. |
| 20 | + Login(LoginArgs), |
| 21 | + /// Release currently stored JWT |
| 22 | + Logout, |
| 23 | + /// Prints currently stored JWT to stdout |
| 24 | + Show, |
| 25 | +} |
| 26 | + |
| 27 | +/// Main entry point called from agama CLI main loop |
| 28 | +pub async fn run(subcommand: AuthCommands) -> anyhow::Result<()> { |
| 29 | + match subcommand { |
| 30 | + AuthCommands::Login(options) => login(LoginArgs::proceed(options).password()?).await, |
| 31 | + AuthCommands::Logout => logout(), |
| 32 | + AuthCommands::Show => show(), |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +/// Reads stored token and returns it |
| 37 | +fn jwt() -> anyhow::Result<String> { |
| 38 | + if let Some(file) = jwt_file() { |
| 39 | + if let Ok(token) = read_line_from_file(&file.as_path()) { |
| 40 | + return Ok(token); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + Err(anyhow::anyhow!("Authentication token not available")) |
| 45 | +} |
| 46 | + |
| 47 | +/// Stores user provided configuration for login command |
| 48 | +#[derive(Args, Debug)] |
| 49 | +pub struct LoginArgs { |
| 50 | + #[arg(long, short = 'p')] |
| 51 | + password: Option<String>, |
| 52 | + #[arg(long, short = 'f')] |
| 53 | + file: Option<PathBuf>, |
| 54 | +} |
| 55 | + |
| 56 | +impl LoginArgs { |
| 57 | + /// Transforms user provided options into internal representation |
| 58 | + /// See Credentials trait |
| 59 | + fn proceed(options: LoginArgs) -> Box<dyn Credentials> { |
| 60 | + if let Some(password) = options.password { |
| 61 | + Box::new(KnownCredentials { password }) |
| 62 | + } else if let Some(path) = options.file { |
| 63 | + Box::new(FileCredentials { path }) |
| 64 | + } else { |
| 65 | + Box::new(MissingCredentials {}) |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +/// Placeholder for no configuration provided by user |
| 71 | +struct MissingCredentials; |
| 72 | + |
| 73 | +/// Stores whatever is needed for reading credentials from a file |
| 74 | +struct FileCredentials { |
| 75 | + path: PathBuf, |
| 76 | +} |
| 77 | + |
| 78 | +/// Stores credentials as provided by the user directly |
| 79 | +struct KnownCredentials { |
| 80 | + password: String, |
| 81 | +} |
| 82 | + |
| 83 | +/// Transforms credentials from user's input into format used internaly |
| 84 | +trait Credentials { |
| 85 | + fn password(&self) -> io::Result<String>; |
| 86 | +} |
| 87 | + |
| 88 | +impl Credentials for KnownCredentials { |
| 89 | + fn password(&self) -> io::Result<String> { |
| 90 | + Ok(self.password.clone()) |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +impl Credentials for FileCredentials { |
| 95 | + fn password(&self) -> io::Result<String> { |
| 96 | + read_line_from_file(&self.path.as_path()) |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +impl Credentials for MissingCredentials { |
| 101 | + fn password(&self) -> io::Result<String> { |
| 102 | + let password = read_credential("Password".to_string())?; |
| 103 | + |
| 104 | + Ok(password) |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +/// Path to file where JWT is stored |
| 109 | +fn jwt_file() -> Option<PathBuf> { |
| 110 | + Some(home::home_dir()?.join(DEFAULT_JWT_FILE)) |
| 111 | +} |
| 112 | + |
| 113 | +/// Reads first line from given file |
| 114 | +fn read_line_from_file(path: &Path) -> io::Result<String> { |
| 115 | + if !path.exists() { |
| 116 | + return Err(io::Error::new( |
| 117 | + io::ErrorKind::Other, |
| 118 | + "Cannot find the file containing the credentials.", |
| 119 | + )); |
| 120 | + } |
| 121 | + |
| 122 | + if let Ok(file) = File::open(&path) { |
| 123 | + // cares only of first line, take everything. No comments |
| 124 | + // or something like that supported |
| 125 | + let raw = BufReader::new(file).lines().next(); |
| 126 | + |
| 127 | + if let Some(line) = raw { |
| 128 | + return line; |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + Err(io::Error::new( |
| 133 | + io::ErrorKind::Other, |
| 134 | + "Failed to open the file", |
| 135 | + )) |
| 136 | +} |
| 137 | + |
| 138 | +/// Asks user to provide a line of input. Displays a prompt. |
| 139 | +fn read_credential(caption: String) -> io::Result<String> { |
| 140 | + let mut cred = String::new(); |
| 141 | + |
| 142 | + println!("{}: ", caption); |
| 143 | + |
| 144 | + io::stdin().read_line(&mut cred)?; |
| 145 | + if cred.pop().is_none() || cred.is_empty() { |
| 146 | + return Err(io::Error::new( |
| 147 | + io::ErrorKind::Other, |
| 148 | + format!("Failed to read {}", caption), |
| 149 | + )); |
| 150 | + } |
| 151 | + |
| 152 | + Ok(cred) |
| 153 | +} |
| 154 | + |
| 155 | +/// Sets the archive owner to root:root. Also sets the file permissions to read/write for the |
| 156 | +/// owner only. |
| 157 | +fn set_file_permissions(file: &Path) -> io::Result<()> { |
| 158 | + let attr = fs::metadata(file)?; |
| 159 | + let mut permissions = attr.permissions(); |
| 160 | + |
| 161 | + // set the file file permissions to -rw------- |
| 162 | + permissions.set_mode(DEFAULT_FILE_MODE); |
| 163 | + fs::set_permissions(file, permissions)?; |
| 164 | + |
| 165 | + Ok(()) |
| 166 | +} |
| 167 | + |
| 168 | +/// Necessary http request header for authenticate |
| 169 | +fn authenticate_headers() -> HeaderMap { |
| 170 | + let mut headers = HeaderMap::new(); |
| 171 | + |
| 172 | + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); |
| 173 | + |
| 174 | + headers |
| 175 | +} |
| 176 | + |
| 177 | +/// Query web server for JWT |
| 178 | +async fn get_jwt(url: String, password: String) -> anyhow::Result<String> { |
| 179 | + let client = reqwest::Client::new(); |
| 180 | + let response = client |
| 181 | + .post(url) |
| 182 | + .headers(authenticate_headers()) |
| 183 | + .body(format!("{{\"password\": \"{}\"}}", password)) |
| 184 | + .send() |
| 185 | + .await?; |
| 186 | + let body = response |
| 187 | + .json::<std::collections::HashMap<String, String>>() |
| 188 | + .await?; |
| 189 | + let value = body.get(&"token".to_string()); |
| 190 | + |
| 191 | + if let Some(token) = value { |
| 192 | + return Ok(token.clone()); |
| 193 | + } |
| 194 | + |
| 195 | + Err(anyhow::anyhow!("Failed to get authentication token")) |
| 196 | +} |
| 197 | + |
| 198 | +/// Logs into the installation web server and stores JWT for later use. |
| 199 | +async fn login(password: String) -> anyhow::Result<()> { |
| 200 | + // 1) ask web server for JWT |
| 201 | + let res = get_jwt(DEFAULT_AUTH_URL.to_string(), password).await?; |
| 202 | + |
| 203 | + // 2) if successful store the JWT for later use |
| 204 | + if let Some(path) = jwt_file() { |
| 205 | + if let Some(dir) = path.parent() { |
| 206 | + fs::create_dir_all(dir)?; |
| 207 | + } else { |
| 208 | + return Err(anyhow::anyhow!("Cannot store the authentication token")); |
| 209 | + } |
| 210 | + |
| 211 | + fs::write(path.as_path(), res)?; |
| 212 | + set_file_permissions(path.as_path())?; |
| 213 | + } |
| 214 | + |
| 215 | + Ok(()) |
| 216 | +} |
| 217 | + |
| 218 | +/// Releases JWT |
| 219 | +fn logout() -> anyhow::Result<()> { |
| 220 | + let path = jwt_file(); |
| 221 | + |
| 222 | + if !&path.clone().is_some_and(|p| p.exists()) { |
| 223 | + // mask if the file with the JWT doesn't exist (most probably no login before logout) |
| 224 | + return Ok(()); |
| 225 | + } |
| 226 | + |
| 227 | + // panicking is right thing to do if expect fails, becase it was already checked twice that |
| 228 | + // the path exists |
| 229 | + let file = path.expect("Cannot locate stored JWT"); |
| 230 | + |
| 231 | + Ok(fs::remove_file(file)?) |
| 232 | +} |
| 233 | + |
| 234 | +/// Shows stored JWT on stdout |
| 235 | +fn show() -> anyhow::Result<()> { |
| 236 | + // we do not care if jwt() fails or not. If there is something to print, show it otherwise |
| 237 | + // stay silent |
| 238 | + if let Ok(token) = jwt() { |
| 239 | + println!("{}", token); |
| 240 | + } |
| 241 | + |
| 242 | + Ok(()) |
| 243 | +} |
0 commit comments