key 1.2.6

Cli to a local or remote keepass database
Documentation
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
422
423
424
425
426
427
428
429
430
431
432
433
extern crate copypasta;

use anyhow::Result;
use clap::{CommandFactory, Parser, Subcommand};
use colored::Colorize;
use copypasta::{ClipboardContext, ClipboardProvider};
use demand::{DemandOption, Input, Select};
use keepass::{db::Node, Database, DatabaseKey};
use key::{
  db::{get_database, write_database, KeeOptions},
  delete_entry, get_entry, get_entry_file, get_entry_otp, rename_entry, to_json,
};
use key::{generate_password, set_entry};
use log::debug;
use std::{env, fmt, fs::File};
use url::Url;

/// Command Line Interface to a local or remote keepass database.
#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
  /// Path to the keyfile
  #[arg(short = 'k', long, env = "KEY_KEYFILE")]
  keyfile: Option<String>,

  /// Url to the keepass database file (supports file:// and s3:// schemas)
  #[arg(long, env = "KEY_DATABASE_URL")]
  kdbx: Option<String>,

  /// Database password [env: KEY_PASSWORD]
  #[arg(short = 'p', long)]
  password: Option<String>,

  /// S3 access key [env: KEY_S3_ACCESS_KEY]
  #[arg(long)]
  s3_access_key: Option<String>,

  /// S3 secret key [env: KEY_S3_SECRET_KEY]
  #[arg(long)]
  s3_secret_key: Option<String>,

  #[command(subcommand)]
  command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
  /// Generate a One time password
  OTP {
    /// Name of entry
    name: String,

    /// Field to get
    #[arg(long, default_value = "otp")]
    field: String,

    /// Copy value to system clipboard
    #[arg(long)]
    clipboard: bool,
  },

  /// Generate a new password
  Gen {
    /// Length of password
    #[arg(long, default_value = "18")]
    length: usize,
  },

  /// List all entries of the database
  List {
    /// Output format (json, yaml, toml)
    #[arg(short = 'o', long)]
    output: Option<String>,
  },

  /// Get a specific entry from the database
  Get {
    /// Name of entry
    name: String,

    /// Extract as file
    #[arg(long)]
    file: bool,

    /// Copy value to system clipboard
    #[arg(long)]
    clipboard: bool,

    /// Field to get
    #[arg(long, default_value = "Password")]
    field: String,
  },

  /// Set the value of a specific entry in the database
  Set {
    /// Name of entry
    name: String,
    /// Password to set
    value: String,

    /// Field to set
    #[arg(long, default_value = "Password")]
    field: String,
  },

  /// Delete a specific entry from the database
  Delete {
    /// Name of entry
    name: String,
  },

  /// Rename a specific entry in the database
  Rename {
    /// Name of entry
    name: String,

    /// New name of entry
    new_name: String,
  },

  /// Chooser terminal ui
  Choose {
    /// Copy value to system clipboard
    #[arg(long)]
    clipboard: bool,

    /// Calculate OTP for entry
    #[arg(long)]
    otp: bool,

    /// Field to get
    #[arg(long, default_value = "Password")]
    field: String,
  },
}

fn options_from_cli(cli: &Cli) -> Result<KeeOptions> {
  let keepassdb = cli.kdbx.clone();
  let keepassdb_keyfile = cli.keyfile.clone();
  let keepassdb_password = cli.password.clone().or(env::var("KEY_PASSWORD").ok());
  let s3_access_key = cli
    .s3_access_key
    .clone()
    .or(env::var("KEY_S3_ACCESS_KEY").ok());
  let s3_secret_key = cli
    .s3_secret_key
    .clone()
    .or(env::var("KEY_S3_SECRET_KEY").ok());

  if keepassdb.is_none() {
    return Err(anyhow::format_err!("No database url provided."));
  }

  Ok(KeeOptions {
    keepassdb: keepassdb.unwrap(),
    keepassdb_keyfile,
    keepassdb_password,
    s3_access_key,
    s3_secret_key,
  })
}

fn read_password(title: String) -> String {
  let t = Input::new(title).placeholder("Password").password(true);
  t.run().expect("error running input")
}

fn get_database_key(options: &KeeOptions) -> Result<DatabaseKey> {
  let dburl_parsed = Url::parse(&options.keepassdb.as_str())?;
  let name = dburl_parsed.path().split('/').last().unwrap().to_string();

  let mut key = DatabaseKey::new();

  let keypath = &options.keepassdb_keyfile;
  if let Some(keypath) = keypath {
    key = key.with_keyfile(&mut File::open(keypath)?)?;
  }

  let password = &options.keepassdb_password;
  if let Some(password) = password {
    key = key.with_password(password.as_str())
  } else {
    key = key.with_password(read_password(format!("Password for {}", name)).as_str());
  }

  Ok(key)
}

async fn command_list(options: &KeeOptions, format: &str) -> Result<()> {
  let db = get_database(&options, &get_database_key(&options)?).await?;

  match format {
    "json" => {
      println!("{}", to_json(db)?);
    }
    _ => {
      for entry in db.root.children.iter() {
        match entry {
          Node::Group(g) => {
            for child in g.children.iter() {
              match child {
                Node::Entry(e) => {
                  println!("{}/{}", g.name, e.get_title().unwrap().to_string());
                }
                _ => continue,
              }
            }
          }
          Node::Entry(e) => {
            println!("{}", e.get_title().unwrap().to_string());
          }
        };
      }
    }
  }

  Ok(())
}

struct ChooseEntry {
  value: String,
  user: Option<String>,
}

impl fmt::Display for ChooseEntry {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
      "{} ({})",
      self.value,
      self.user.clone().unwrap_or("".to_string()).bright_black()
    )
  }
}

fn choose_key_ui(db: &Database) -> ChooseEntry {
  let ms: Select<ChooseEntry> = Select::new("Keys")
    .description("Select a key")
    .filterable(true);

  let mut options: Vec<DemandOption<ChooseEntry>> = Vec::new();

  db.root.children.iter().for_each(|entry| match entry {
    Node::Entry(e) => {
      options.push(DemandOption::new(ChooseEntry {
        user: Some(e.get_username().unwrap_or("").to_string()),
        value: e.get_title().unwrap().to_string(),
      }));
    }
    Node::Group(g) => {
      for child in g.children.iter() {
        match child {
          Node::Entry(e) => {
            options.push(DemandOption::new(ChooseEntry {
              user: Some(e.get_username().unwrap_or("").to_string()),
              value: e.get_title().unwrap().to_string(),
            }));
          }
          _ => continue,
        }
      }
    }
  });

  ms.options(options).run().expect("error running select")
}

async fn command_choose(
  options: &KeeOptions,
  field: &String,
  clipboard: &bool,
  otp: &bool,
) -> Result<()> {
  let db = get_database(&options, &get_database_key(&options)?).await?;

  let entry = if otp.to_owned() {
    get_entry_otp(&db, &choose_key_ui(&db).value, &"otp".to_string())?
  } else {
    get_entry(&db, &choose_key_ui(&db).value, &field)?
  };

  if clipboard.to_owned() {
    to_clipboard(entry)?;
    println!("Copied to clipboard");
    return Ok(());
  }

  println!("{}", entry);
  Ok(())
}

fn to_clipboard(entry: String) -> Result<()> {
  let mut ctx = ClipboardContext::new().unwrap();
  ctx.set_contents(entry).unwrap();
  return Ok(());
}

async fn command_get(
  options: &KeeOptions,
  name: &String,
  field: &String,
  clipboard: &bool,
) -> Result<()> {
  let db = get_database(&options, &get_database_key(&options)?).await?;
  let entry = get_entry(&db, name, field)?;

  if clipboard.to_owned() {
    to_clipboard(entry)?;
    println!("Copied {field} to clipboard");
    return Ok(());
  }

  println!("{}", entry);
  Ok(())
}

async fn command_get_file(
  options: &KeeOptions,
  name: &String,
  field: &String,
) -> Result<()> {
  let db = get_database(&options, &get_database_key(&options)?).await?;
  get_entry_file(&db, name, field)?;
  Ok(())
}

async fn command_otp(
  options: &KeeOptions,
  name: &String,
  field: &String,
  clipboard: &bool,
) -> Result<()> {
  let db = get_database(&options, &get_database_key(&options)?).await?;
  let val = get_entry_otp(&db, name, field)?;

  if clipboard.to_owned() {
    to_clipboard(val)?;
    println!("Copied {field} to clipboard");
    return Ok(());
  }

  println!("{}", val);
  Ok(())
}

async fn command_set(
  options: &KeeOptions,
  name: &String,
  value: &String,
  field: &String,
) -> Result<()> {
  let key = get_database_key(&options)?;
  let mut db = get_database(&options, &key).await?;
  set_entry(&mut db, name, value, field)?;
  debug!("Set entry field {} to {}", field, value);
  write_database(&options, &mut db, &key).await?;
  Ok(())
}

async fn command_rename(
  options: &KeeOptions,
  name: &String,
  new_name: &String,
) -> Result<()> {
  let key = get_database_key(&options)?;
  let mut db = get_database(&options, &key).await?;
  rename_entry(&mut db, name, new_name)?;
  debug!("Set Title of field {} to {}", name, new_name);
  write_database(&options, &mut db, &key).await?;
  Ok(())
}

async fn command_delete(options: &KeeOptions, name: &String) -> Result<()> {
  let key = get_database_key(&options)?;
  let mut db = get_database(&options, &key).await?;
  delete_entry(&mut db, name)?;
  debug!("Deleted entry {}", name);
  write_database(&options, &mut db, &key).await?;
  Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
  env_logger::init();

  let cli = Cli::parse();
  let options = options_from_cli(&cli)?;

  debug!("options {:?}", options);

  match &cli.command {
    Some(Commands::List { output }) => {
      command_list(&options, output.as_deref().unwrap_or("text")).await
    }
    Some(Commands::Get {
      name,
      field,
      file,
      clipboard,
    }) => {
      if file.clone() == true {
        return command_get_file(&options, name, field).await;
      }
      return command_get(&options, name, field, clipboard).await;
    }
    Some(Commands::Choose {
      clipboard,
      field,
      otp,
    }) => command_choose(&options, field, clipboard, otp).await,
    Some(Commands::OTP {
      name,
      field,
      clipboard,
    }) => command_otp(&options, name, field, clipboard).await,
    Some(Commands::Set { name, value, field }) => {
      command_set(&options, name, value, field).await
    }
    Some(Commands::Delete { name }) => command_delete(&options, name).await,
    Some(Commands::Rename { name, new_name }) => {
      command_rename(&options, name, new_name).await
    }
    Some(Commands::Gen { length }) => {
      println!("{}", generate_password(length));
      Ok(())
    }
    None => {
      Cli::command().print_help()?;
      println!("No command provided.");
      Ok(())
    }
  }
}