onepass 4.0.0-pre.0

A mostly-stateless deterministic password manager
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
mod seed_password;

use std::{
    fs,
    io::{BufWriter, IsTerminal, Write, stdout},
    num::NonZero,
    path::Path,
    process::exit,
    sync::Arc,
};

use anyhow::{Context as _Context, Result};
use clap::{CommandFactory, Parser, error::ErrorKind};
use onepass_conf::{Config, Error, KeyringSeed, RawSite};
use onepass_seed::{
    ExposeSecret, SecretBox, SecretString,
    dict::{BoxDict, Dict},
    expr::{Context, Eval, Expr},
    site::Site,
};
#[allow(deprecated)]
use onepass_seed::{LegacyCountError, check_legacy_count};
use readpassphrase_3::Flags as RpFlags;

#[derive(Debug, Parser)]
#[command(version, about, next_help_heading = "Site Options")]
struct Args {
    /// Site(s) for which to generate a password
    #[arg(value_name = "SITE", help_heading = None)]
    sites: Vec<String>,

    /// Override schema to use (may be a configured alias)
    #[arg(short, long)]
    schema: Option<String>,

    /// Override increment to use
    #[arg(short, long, value_name = "NUM")]
    increment: Option<u32>,

    /// Override username to use
    #[arg(short, long)]
    username: Option<String>,

    #[cfg(not(keyring = "no"))]
    /// Cache the seed password in the OS keyring
    #[arg(short = 'k', help_heading = "Keyring Integration")]
    keyring: bool,

    #[cfg(not(keyring = "no"))]
    /// Do not cache the seed password
    #[arg(
        short = 'K',
        conflicts_with = "keyring",
        help_heading = "Keyring Integration"
    )]
    no_keyring: bool,

    #[cfg(not(keyring = "no"))]
    /// Clear the seed password keyring entry
    #[arg(short, long, help_heading = "Keyring Integration")]
    reset_keyring: bool,

    /// Describe the site password instead of computing it
    #[arg(short, long, help_heading = "Password Entry")]
    describe: bool,

    /// Confirm seed password
    #[arg(short, long, help_heading = "Password Entry")]
    confirm: bool,

    /// Learn the site password by retyping it
    #[arg(
        short,
        long,
        value_name = "COUNT",
        default_missing_value = "1",
        num_args=0..=1,
        require_equals = true,
        help_heading = "Password Entry",
    )]
    learn: Option<u32>,

    /// Read seed password from stdin instead of /dev/tty
    #[arg(long, help_heading = "Password Entry")]
    stdin: bool,

    /// Accept empty password
    #[arg(long, help_heading = "Password Entry")]
    allow_empty: bool,

    /// Override word list
    #[arg(
        short,
        long = "words",
        env = "ONEPASS_WORDS_FILE",
        value_name = "WORDS_FILE",
        help_heading = "Configuration"
    )]
    words_path: Option<Box<Path>>,

    /// Override config file
    #[arg(
        short = 'f',
        long = "config",
        env = "ONEPASS_CONFIG_FILE",
        value_name = "CONFIG_FILE",
        help_heading = "Configuration"
    )]
    config_path: Option<Box<Path>>,

    /// Print site URLs for autocompletion
    #[arg(short, long, help_heading = "Configuration")]
    print_sites: bool,

    /// Generate passwords using the pre-v3.3.0 count rule, for recovery/rotation
    #[arg(long, help_heading = "Configuration")]
    legacy_count_rule: bool,

    /// Check if any sites need to be rotated for the new count rule as of v3.3.0
    #[arg(long, help_heading = "Diagnostics")]
    check_legacy_counts: bool,

    /// Print verbose site password entropy output
    #[arg(short, long)]
    verbose: bool,
}

fn main() -> Result<()> {
    let args = Args::parse();

    let config_path = args.config_path.as_deref();
    let config = Config::from_or_init(config_path).context("failed loading config")?;
    let seed_keyring = args
        .seed_keyring()
        .unwrap_or(match config.global.keyring.seed {
            KeyringSeed::Unspecified => !cfg!(keyring = "no"),
            KeyringSeed::Cache => true,
            KeyringSeed::Off => false,
        });
    let rp_flags = if args.stdin {
        RpFlags::STDIN
    } else {
        RpFlags::default()
    };

    if args.reset_keyring() {
        seed_password::delete()?;
    }
    if args.print_sites {
        if args.check_legacy_counts {
            Args::command()
                .error(
                    ErrorKind::ArgumentConflict,
                    "--check-legacy-counts and --print-sites are mutually exclusive",
                )
                .exit();
        }
        let mut urls = config
            .sites()
            .iter()
            .map(|site| site.url.as_str())
            .collect::<Vec<_>>();
        urls.dedup();
        for url in &urls {
            println!("{url}");
        }
        return Ok(());
    }

    if args.check_legacy_counts {
        exit(check_legacy_counts(&config, &args)?);
    }

    if args.sites.is_empty() && !args.describe {
        if args.confirm {
            let _ = seed_password::read(seed_keyring, true, rp_flags)?;
        }
        if args.reset_keyring() || args.confirm {
            return Ok(());
        }
        Args::command()
            .error(ErrorKind::TooFewValues, "specify at least one site")
            .exit();
    }

    let words: Option<_> = read_words_str(&args, &config)?;
    let dict = words
        .as_deref()
        .map(BoxDict::from_lines)
        .map(|d| -> Arc<dyn Dict + '_> { Arc::new(d) });
    let mut context = dict.map_or_else(Context::default, Context::with_dict);
    if args.legacy_count_rule {
        eprintln!("WARNING: using legacy count rule.");
        #[allow(deprecated)]
        {
            context = context.with_legacy_count_rule();
        }
    }

    if args.describe {
        if args.sites.is_empty()
            && let Some(schema) = args.schema.as_deref()
        {
            let schema = config.global.alias.get(schema).map_or(schema, |s| s);
            let expr = Expr::parse_with_context(schema, &context)?;
            println!("{expr}");
            println!("about {:.02} bits of entropy", expr.entropy());
        }
        for url in &args.sites {
            let site = lookup_site(url, &config, &args, &context)?;

            println!("{url}:");
            println!("{}", site.expr);

            let mut buf = BufWriter::new(Vec::new());
            site.expr.write_to(&mut buf, &mut SecretBox::default())?;
            let example = String::from_utf8(buf.into_inner()?)?;
            println!("Looks like: {example:?}");

            println!("about {:.02} bits of entropy", site.expr.entropy());
        }
        return Ok(());
    }

    let mut stdout = stdout();
    let mut seed = None;
    for url in &args.sites {
        // Check for schema validity before unlocking seed keyring.
        let site = lookup_site(url, &config, &args, &context)?;
        if seed.is_none() {
            let seed_ = seed_password::read(seed_keyring, args.confirm, rp_flags)?;
            if !args.allow_empty && seed_.expose_secret().is_empty() {
                anyhow::bail!("empty password not allowed (pass --allow-empty to use)");
            }
            seed = Some(seed_);
        }
        let res = gen_password_config(seed.as_ref().unwrap().expose_secret(), &site, url, &args)?;
        stdout.write_all(res.expose_secret().as_bytes())?;
        if stdout.is_terminal() || args.sites.len() > 1 {
            writeln!(stdout)?;
        }
        if let Some(count) = args.learn {
            let mut failures = 0;
            for _ in 0..count {
                if !seed_password::check_confirm(res.expose_secret())? {
                    failures += 1;
                    eprint!("✘ ");
                }
            }
            if failures != 0 {
                if count == 1 {
                    anyhow::bail!("password mismatch");
                }
                anyhow::bail!("{failures}/{count} attempts failed");
            }
        }
    }
    Ok(())
}

fn read_words_str(args: &Args, config: &Config) -> Result<Option<Box<str>>> {
    let path = args
        .words_path
        .as_deref()
        .or(config.global.words_path.as_deref());
    path.map(|p| fs::read_to_string(p).map(|s| s.into_boxed_str()))
        .transpose()
        .context("failed reading words file")
}

fn gen_password_config(seed: &str, site: &Site, url: &str, args: &Args) -> Result<SecretString> {
    let size = site.expr.size().to_string();
    let size = size.trim_start_matches('0');
    let entropy = site.expr.entropy();
    let salt = format!("{site}");

    if args.verbose {
        eprintln!(
            "schema for {} has about {:.02} bits of entropy (0x{} possible passwords)",
            url, entropy, size
        );
        eprintln!("salt: {salt:?}");
    }

    site.password(seed).context("failed generating password")
}

fn lookup_site(url: &str, config: &Config, args: &Args, context: &Context) -> Result<Site> {
    let username = args.username.as_deref();
    let mut site = match config.find_site(url, username) {
        Ok(site) => site,
        Err(Error::UrlNotFound) => RawSite::new(url, username, None, 0),
        Err(err) => return Err(err).context("failed finding site"),
    };
    if let Some(data) = site.data {
        anyhow::bail!("unknown data field on {url}:\n{data:?}");
    }
    if let Some(ref schema) = args.schema {
        site.schema = Some(config.resolve_schema(schema));
    }
    if let Some(increment) = args.increment {
        site.increment = NonZero::new(increment);
    }
    // TODO(soon): do something about redundant default_schema call here
    site.to_site_with_context(config.default_schema(), context)
        .context("failed generating site")
}

#[allow(deprecated)]
fn check_schema(context: &Context, schema: &str) -> Result<Option<LegacyCountError>> {
    match check_legacy_count(
        context,
        &schema
            .parse()
            .with_context(|| format!("failed parsing schema {schema:?}"))?,
    ) {
        Ok(()) => Ok(None),
        Err(err) => Ok(Some(err)),
    }
}

fn check_legacy_counts(config: &Config, args: &Args) -> Result<i32> {
    let mut rc = 0;

    let words: Option<_> = read_words_str(args, config)?;
    let dict = words
        .as_deref()
        .map(BoxDict::from_lines)
        .map(|d| -> Arc<dyn Dict + '_> { Arc::new(d) });
    let context = dict.map_or_else(Context::default, Context::with_dict);

    if let Some(schema) = args.schema.as_deref()
        && let Some(err) = check_schema(&context, schema)?
    {
        rc = 1;
        eprintln!("Schema {schema:?}: {err}");
    }

    for (site, schema) in config
        .sites()
        .iter()
        .filter_map(|s| Some((s.as_deref(), s.schema.as_deref()?)))
    {
        if let Some(err) = check_schema(&context, schema).with_context(|| {
            format!(
                "failed checking url: {:?} username: {:?}",
                site.url, site.username
            )
        })? {
            rc = 1;
            let url = site.url;
            eprint!("Site {url:?}");
            if let Some(username) = site.username {
                eprint!(" (username {username:?})");
            }
            eprintln!(", schema {schema:?}: {err}");
        }
    }

    for (alias, schema) in config.global.alias.iter() {
        if let Some(err) = check_schema(&context, schema)
            .with_context(|| format!("failed checking alias: {alias}"))?
        {
            rc = 1;
            eprintln!("Alias {alias} (schema {schema:?}): {err}");
        }
    }

    let schema = config.default_schema();
    if let Some(err) = check_schema(&context, schema).context("failed checking default schema")? {
        rc = 1;
        eprintln!("Default schema {schema:?}: {err}");
    }

    Ok(rc)
}

impl Args {
    fn seed_keyring(&self) -> Option<bool> {
        #[cfg(keyring = "no")]
        {
            None
        }
        #[cfg(not(keyring = "no"))]
        if self.no_keyring {
            Some(false)
        } else if self.keyring {
            Some(true)
        } else if self.stdin {
            Some(false)
        } else {
            None
        }
    }

    fn reset_keyring(&self) -> bool {
        #[cfg(keyring = "no")]
        {
            false
        }
        #[cfg(not(keyring = "no"))]
        {
            self.reset_keyring
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{fs::File, path::PathBuf};

    use onepass_seed::{dict::BoxDict, site::Site};
    use tempfile::TempDir;

    use super::*;

    #[test]
    #[ignore] // too slow
    fn test_passwords() -> Result<()> {
        let tests = [
            (
                "impeach-duckling-outage-spur",
                "arst",
                "google.com",
                "{words:4:-}",
                0,
            ),
            ("(%\")&#+(&!/$", "password", "apple.com", "[!-/]{12}", 1),
        ];
        for (want, seed, url, schema, increment) in tests {
            let site = Site::new(url, None, schema, increment)?;
            let got = site.password(seed)?;
            assert_eq!(want, got.expose_secret());
        }
        Ok(())
    }

    #[test]
    fn test_words_file() -> Result<()> {
        let dir = TempDir::new()?;
        let mut dir_path = PathBuf::from(dir.path());
        dir_path.push("config");
        let config_path = dir_path.clone().into_boxed_path();
        dir_path.pop();
        dir_path.push("words");
        let words_path = dir_path.into_boxed_path();

        let mut config_file = File::create(&config_path)?;
        writeln!(config_file, "[global]")?;
        writeln!(config_file, "words_path = {words_path:?}")?;
        drop(config_file);

        let mut words_file = File::create(&words_path)?;
        writeln!(words_file, "bob")?;
        writeln!(words_file, "  dole")?;
        writeln!(words_file, "bob  ")?;
        writeln!(words_file, "a")?;
        drop(words_file);

        let config = Config::from_file(&config_path)?;
        let args: [&str; 0] = [];
        let words = read_words_str(&Args::parse_from(args.iter()), &config)?
            .context("failed reading words file")?;
        let dict = BoxDict::from_lines(words);
        assert_eq!(3, dict.len());
        assert_eq!("a", dict.word(0));
        assert_eq!("bob", dict.word(1));
        assert_eq!("dole", dict.word(2));

        Ok(())
    }

    // We do not translate CR/LF on Windows.
    #[cfg(not(target_os = "windows"))]
    #[test]
    fn test_example_config() {
        // Test belongs in `onepass-conf` but that crate does not have access to the examples dir
        // from this crate.
        let example_config = include_str!("../example/config.toml");
        assert_eq!(onepass_conf::EXAMPLE_CONFIG, example_config);
    }
}