27f9bd183d7b124ddf137b536d1063dd64db3c66
Marco Ricci Change the author e-mail ad...

Marco Ricci authored 2 months ago

1) # SPDX-FileCopyrightText: 2024 Marco Ricci <software@the13thletter.info>
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

2) #
3) # SPDX-License-Identifier: MIT
4) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

5) """Command-line interface for derivepassphrase."""
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

6) 
7) from __future__ import annotations
8) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

9) import base64
10) import collections
11) import contextlib
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

12) import copy
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

13) import importlib
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

14) import inspect
15) import json
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

16) import logging
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

17) import os
18) import socket
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

19) import unicodedata
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

20) from typing import (
21)     TYPE_CHECKING,
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

22)     Literal,
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

23)     NoReturn,
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

24)     TextIO,
25)     cast,
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

26) )
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

27) 
28) import click
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

29) from typing_extensions import (
30)     Any,
31)     assert_never,
32) )
33) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

34) import derivepassphrase as dpp
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

35) from derivepassphrase import _types, exporter, ssh_agent, vault
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

36) 
37) if TYPE_CHECKING:
38)     import pathlib
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

39)     import types
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

40)     from collections.abc import (
41)         Iterator,
42)         Sequence,
43)     )
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

44) 
45) __author__ = dpp.__author__
46) __version__ = dpp.__version__
47) 
48) __all__ = ('derivepassphrase',)
49) 
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

50) PROG_NAME = 'derivepassphrase'
51) KEY_DISPLAY_LENGTH = 30
52) 
53) # Error messages
54) _INVALID_VAULT_CONFIG = 'Invalid vault config'
55) _AGENT_COMMUNICATION_ERROR = 'Error communicating with the SSH agent'
56) _NO_USABLE_KEYS = 'No usable SSH keys were found'
57) _EMPTY_SELECTION = 'Empty selection'
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

58) 
59) 
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

60) # Top-level
61) # =========
62) 
63) 
64) @click.command(
65)     context_settings={
66)         'help_option_names': ['-h', '--help'],
67)         'ignore_unknown_options': True,
68)         'allow_interspersed_args': False,
69)     },
70)     epilog=r"""
71)         Configuration is stored in a directory according to the
72)         DERIVEPASSPHRASE_PATH variable, which defaults to
73)         `~/.derivepassphrase` on UNIX-like systems and
74)         `C:\Users\<user>\AppData\Roaming\Derivepassphrase` on Windows.
Marco Ricci Fix minor typo, formatting...

Marco Ricci authored 2 months ago

75)     """,
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

76) )
77) @click.version_option(version=dpp.__version__, prog_name=PROG_NAME)
78) @click.argument('subcommand_args', nargs=-1, type=click.UNPROCESSED)
79) def derivepassphrase(
80)     *,
81)     subcommand_args: list[str],
82) ) -> None:
83)     """Derive a strong passphrase, deterministically, from a master secret.
84) 
85)     Using a master secret, derive a passphrase for a named service,
86)     subject to constraints e.g. on passphrase length, allowed
87)     characters, etc.  The exact derivation depends on the selected
88)     derivation scheme.  For each scheme, it is computationally
89)     infeasible to discern the master secret from the derived passphrase.
90)     The derivations are also deterministic, given the same inputs, thus
91)     the resulting passphrases need not be stored explicitly.  The
92)     service name and constraints themselves also generally need not be
93)     kept secret, depending on the scheme.
94) 
95)     The currently implemented subcommands are "vault" (for the scheme
96)     used by vault) and "export" (for exporting foreign configuration
97)     data).  See the respective `--help` output for instructions.  If no
98)     subcommand is given, we default to "vault".
99) 
100)     Deprecation notice: Defaulting to "vault" is deprecated.  Starting
101)     in v1.0, the subcommand must be specified explicitly.\f
102) 
103)     This is a [`click`][CLICK]-powered command-line interface function,
104)     and not intended for programmatic use.  Call with arguments
105)     `['--help']` to see full documentation of the interface.  (See also
106)     [`click.testing.CliRunner`][] for controlled, programmatic
107)     invocation.)
108) 
Marco Ricci Update all URLs to stable a...

Marco Ricci authored 1 month ago

109)     [CLICK]: https://pypi.org/package/click/
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

110) 
111)     """  # noqa: D301
112)     if subcommand_args and subcommand_args[0] == 'export':
113)         return derivepassphrase_export.main(
114)             args=subcommand_args[1:],
115)             prog_name=f'{PROG_NAME} export',
116)             standalone_mode=False,
117)         )
118)     if not (subcommand_args and subcommand_args[0] == 'vault'):
119)         click.echo(
120)             (
121)                 f'{PROG_NAME}: Deprecation warning: A subcommand will be '
122)                 f'required in v1.0. See --help for available subcommands.'
123)             ),
124)             err=True,
125)         )
126)         click.echo(
127)             f'{PROG_NAME}: Warning: Defaulting to subcommand "vault".',
128)             err=True,
129)         )
130)     else:
131)         subcommand_args = subcommand_args[1:]
132)     return derivepassphrase_vault.main(
133)         args=subcommand_args,
134)         prog_name=f'{PROG_NAME} vault',
135)         standalone_mode=False,
136)     )
137) 
138) 
139) # Exporter
140) # ========
141) 
142) 
143) @click.command(
144)     context_settings={
145)         'help_option_names': ['-h', '--help'],
146)         'ignore_unknown_options': True,
147)         'allow_interspersed_args': False,
148)     }
149) )
150) @click.version_option(version=dpp.__version__, prog_name=PROG_NAME)
151) @click.argument('subcommand_args', nargs=-1, type=click.UNPROCESSED)
152) def derivepassphrase_export(
153)     *,
154)     subcommand_args: list[str],
155) ) -> None:
156)     """Export a foreign configuration to standard output.
157) 
158)     Read a foreign system configuration, extract all information from
159)     it, and export the resulting configuration to standard output.
160) 
161)     The only available subcommand is "vault", which implements the
162)     vault-native configuration scheme.  If no subcommand is given, we
163)     default to "vault".
164) 
165)     Deprecation notice: Defaulting to "vault" is deprecated.  Starting
166)     in v1.0, the subcommand must be specified explicitly.\f
167) 
168)     This is a [`click`][CLICK]-powered command-line interface function,
169)     and not intended for programmatic use.  Call with arguments
170)     `['--help']` to see full documentation of the interface.  (See also
171)     [`click.testing.CliRunner`][] for controlled, programmatic
172)     invocation.)
173) 
Marco Ricci Update all URLs to stable a...

Marco Ricci authored 1 month ago

174)     [CLICK]: https://pypi.org/package/click/
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

175) 
176)     """  # noqa: D301
177)     if not (subcommand_args and subcommand_args[0] == 'vault'):
178)         click.echo(
179)             (
180)                 f'{PROG_NAME}: Deprecation warning: A subcommand will be '
181)                 f'required in v1.0. See --help for available subcommands.'
182)             ),
183)             err=True,
184)         )
185)         click.echo(
186)             f'{PROG_NAME}: Warning: Defaulting to subcommand "vault".',
187)             err=True,
188)         )
189)     else:
190)         subcommand_args = subcommand_args[1:]
191)     return derivepassphrase_export_vault.main(
192)         args=subcommand_args,
193)         prog_name=f'{PROG_NAME} export vault',
194)         standalone_mode=False,
195)     )
196) 
197) 
198) def _load_data(
199)     fmt: Literal['v0.2', 'v0.3', 'storeroom'],
200)     path: str | bytes | os.PathLike[str],
201)     key: bytes,
202) ) -> Any:  # noqa: ANN401
203)     contents: bytes
204)     module: types.ModuleType
Marco Ricci Add support for Python 3.9

Marco Ricci authored 1 month ago

205)     # Use match/case here once Python 3.9 becomes unsupported.
206)     if fmt == 'v0.2':
207)         module = importlib.import_module(
208)             'derivepassphrase.exporter.vault_native'
209)         )
210)         if module.STUBBED:
211)             raise ModuleNotFoundError
212)         with open(path, 'rb') as infile:
213)             contents = base64.standard_b64decode(infile.read())
214)         return module.export_vault_native_data(
215)             contents, key, try_formats=['v0.2']
216)         )
217)     elif fmt == 'v0.3':  # noqa: RET505
218)         module = importlib.import_module(
219)             'derivepassphrase.exporter.vault_native'
220)         )
221)         if module.STUBBED:
222)             raise ModuleNotFoundError
223)         with open(path, 'rb') as infile:
224)             contents = base64.standard_b64decode(infile.read())
225)         return module.export_vault_native_data(
226)             contents, key, try_formats=['v0.3']
227)         )
228)     elif fmt == 'storeroom':
229)         module = importlib.import_module('derivepassphrase.exporter.storeroom')
230)         if module.STUBBED:
231)             raise ModuleNotFoundError
232)         return module.export_storeroom_data(path, key)
233)     else:  # pragma: no cover
234)         assert_never(fmt)
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

235) 
236) 
237) @click.command(
238)     context_settings={'help_option_names': ['-h', '--help']},
239) )
240) @click.option(
241)     '-f',
242)     '--format',
243)     'formats',
244)     metavar='FMT',
245)     multiple=True,
246)     default=('v0.3', 'v0.2', 'storeroom'),
247)     type=click.Choice(['v0.2', 'v0.3', 'storeroom']),
248)     help='try the following storage formats, in order (default: v0.3, v0.2)',
249) )
250) @click.option(
251)     '-k',
252)     '--key',
253)     metavar='K',
254)     help=(
255)         'use K as the storage master key '
256)         '(default: check the `VAULT_KEY`, `LOGNAME`, `USER` or '
257)         '`USERNAME` environment variables)'
258)     ),
259) )
260) @click.argument('path', metavar='PATH', required=True)
261) @click.pass_context
262) def derivepassphrase_export_vault(
263)     ctx: click.Context,
264)     /,
265)     *,
266)     path: str | bytes | os.PathLike[str],
267)     formats: Sequence[Literal['v0.2', 'v0.3', 'storeroom']] = (),
268)     key: str | bytes | None = None,
269) ) -> None:
270)     """Export a vault-native configuration to standard output.
271) 
272)     Read the vault-native configuration at PATH, extract all information
273)     from it, and export the resulting configuration to standard output.
274)     Depending on the configuration format, PATH may either be a file or
275)     a directory.  Supports the vault "v0.2", "v0.3" and "storeroom"
276)     formats.
277) 
278)     If PATH is explicitly given as `VAULT_PATH`, then use the
279)     `VAULT_PATH` environment variable to determine the correct path.
280)     (Use `./VAULT_PATH` or similar to indicate a file/directory actually
281)     named `VAULT_PATH`.)
282) 
283)     """
284)     logging.basicConfig()
285)     if path in {'VAULT_PATH', b'VAULT_PATH'}:
286)         path = exporter.get_vault_path()
287)     if key is None:
288)         key = exporter.get_vault_key()
289)     elif isinstance(key, str):  # pragma: no branch
290)         key = key.encode('utf-8')
291)     for fmt in formats:
292)         try:
293)             config = _load_data(fmt, path, key)
294)         except (
295)             IsADirectoryError,
296)             NotADirectoryError,
297)             ValueError,
298)             RuntimeError,
299)         ):
300)             logging.info('Cannot load as %s: %s', fmt, path)
301)             continue
302)         except OSError as exc:
303)             click.echo(
304)                 (
305)                     f'{PROG_NAME}: ERROR: Cannot parse {path!r} as '
306)                     f'a valid config: {exc.strerror}: {exc.filename!r}'
307)                 ),
308)                 err=True,
309)             )
310)             ctx.exit(1)
311)         except ModuleNotFoundError:
312)             # TODO(the-13th-letter): Use backslash continuation.
313)             # https://github.com/nedbat/coveragepy/issues/1836
314)             msg = f"""
315) {PROG_NAME}: ERROR: Cannot load the required Python module "cryptography".
316) {PROG_NAME}: INFO: pip users: see the "export" extra.
317) """.lstrip('\n')
318)             click.echo(msg, nl=False, err=True)
319)             ctx.exit(1)
320)         else:
321)             if not _types.is_vault_config(config):
322)                 click.echo(
323)                     f'{PROG_NAME}: ERROR: Invalid vault config: {config!r}',
324)                     err=True,
325)                 )
326)                 ctx.exit(1)
327)             click.echo(json.dumps(config, indent=2, sort_keys=True))
328)             break
329)     else:
330)         click.echo(
331)             f'{PROG_NAME}: ERROR: Cannot parse {path!r} as a valid config.',
332)             err=True,
333)         )
334)         ctx.exit(1)
335) 
336) 
337) # Vault
338) # =====
339) 
340) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

341) def _config_filename(
342)     subsystem: str | None = 'settings',
343) ) -> str | bytes | pathlib.Path:
344)     """Return the filename of the configuration file for the subsystem.
345) 
346)     The (implicit default) file is currently named `settings.json`,
347)     located within the configuration directory as determined by the
348)     `DERIVEPASSPHRASE_PATH` environment variable, or by
349)     [`click.get_app_dir`][] in POSIX mode.  Depending on the requested
350)     subsystem, this will usually be a different file within that
351)     directory.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

352) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

353)     Args:
354)         subsystem:
355)             Name of the configuration subsystem whose configuration
356)             filename to return.  If not given, return the old filename
357)             from before the subcommand migration.  If `None`, return the
358)             configuration directory instead.
359) 
360)     Raises:
361)         AssertionError:
362)             An unknown subsystem was passed.
363) 
364)     Deprecated:
365)         Since v0.2.0: The implicit default subsystem and the old
366)         configuration filename are deprecated, and will be removed in v1.0.
367)         The subsystem will be mandatory to specify.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

368) 
369)     """
370)     path: str | bytes | pathlib.Path
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

371)     path = os.getenv(PROG_NAME.upper() + '_PATH') or click.get_app_dir(
372)         PROG_NAME, force_posix=True
373)     )
Marco Ricci Add support for Python 3.9

Marco Ricci authored 1 month ago

374)     # Use match/case here once Python 3.9 becomes unsupported.
375)     if subsystem is None:
376)         return path
377)     elif subsystem in {'vault', 'settings'}:  # noqa: RET505
378)         filename = f'{subsystem}.json'
379)     else:  # pragma: no cover
380)         msg = f'Unknown configuration subsystem: {subsystem!r}'
381)         raise AssertionError(msg)
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

382)     return os.path.join(path, filename)
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

383) 
384) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

385) def _load_config() -> _types.VaultConfig:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

386)     """Load a vault(1)-compatible config from the application directory.
387) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

388)     The filename is obtained via [`_config_filename`][].  This must be
389)     an unencrypted JSON file.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

390) 
391)     Returns:
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

392)         The vault settings.  See [`_types.VaultConfig`][] for details.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

393) 
394)     Raises:
395)         OSError:
396)             There was an OS error accessing the file.
397)         ValueError:
398)             The data loaded from the file is not a vault(1)-compatible
399)             config.
400) 
401)     """
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

402)     filename = _config_filename(subsystem='vault')
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

403)     with open(filename, 'rb') as fileobj:
404)         data = json.load(fileobj)
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

405)     if not _types.is_vault_config(data):
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

406)         raise ValueError(_INVALID_VAULT_CONFIG)
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

407)     return data
408) 
409) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

410) def _migrate_and_load_old_config() -> (
411)     tuple[_types.VaultConfig, OSError | None]
412) ):
413)     """Load and migrate a vault(1)-compatible config.
414) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

415)     The (old) filename is obtained via [`_config_filename`][].  This
416)     must be an unencrypted JSON file.  After loading, the file is
417)     migrated to the new standard filename.
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

418) 
419)     Returns:
420)         The vault settings, and an optional exception encountered during
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

421)         migration.  See [`_types.VaultConfig`][] for details on the
422)         former.
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

423) 
424)     Raises:
425)         OSError:
426)             There was an OS error accessing the old file.
427)         ValueError:
428)             The data loaded from the file is not a vault(1)-compatible
429)             config.
430) 
431)     """
432)     new_filename = _config_filename(subsystem='vault')
433)     old_filename = _config_filename()
434)     with open(old_filename, 'rb') as fileobj:
435)         data = json.load(fileobj)
436)     if not _types.is_vault_config(data):
437)         raise ValueError(_INVALID_VAULT_CONFIG)
438)     try:
439)         os.replace(old_filename, new_filename)
440)     except OSError as exc:
441)         return data, exc
442)     else:
443)         return data, None
444) 
445) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

446) def _save_config(config: _types.VaultConfig, /) -> None:
Marco Ricci Create the configuration di...

Marco Ricci authored 3 months ago

447)     """Save a vault(1)-compatible config to the application directory.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

448) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

449)     The filename is obtained via [`_config_filename`][].  The config
450)     will be stored as an unencrypted JSON file.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

451) 
452)     Args:
453)         config:
454)             vault configuration to save.
455) 
456)     Raises:
457)         OSError:
458)             There was an OS error accessing or writing the file.
459)         ValueError:
460)             The data cannot be stored as a vault(1)-compatible config.
461) 
462)     """
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

463)     if not _types.is_vault_config(config):
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

464)         raise ValueError(_INVALID_VAULT_CONFIG)
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

465)     filename = _config_filename(subsystem='vault')
Marco Ricci Create the configuration di...

Marco Ricci authored 3 months ago

466)     filedir = os.path.dirname(os.path.abspath(filename))
467)     try:
468)         os.makedirs(filedir, exist_ok=False)
469)     except FileExistsError:
470)         if not os.path.isdir(filedir):
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

471)             raise  # noqa: DOC501
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

472)     with open(filename, 'w', encoding='UTF-8') as fileobj:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

473)         json.dump(config, fileobj)
474) 
475) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

476) def _get_suitable_ssh_keys(
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

477)     conn: ssh_agent.SSHAgentClient | socket.socket | None = None, /
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

478) ) -> Iterator[_types.KeyCommentPair]:
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

479)     """Yield all SSH keys suitable for passphrase derivation.
480) 
481)     Suitable SSH keys are queried from the running SSH agent (see
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

482)     [`ssh_agent.SSHAgentClient.list_keys`][]).
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

483) 
484)     Args:
485)         conn:
486)             An optional connection hint to the SSH agent; specifically,
487)             an SSH agent client, or a socket connected to an SSH agent.
488) 
489)             If an existing SSH agent client, then this client will be
490)             queried for the SSH keys, and otherwise left intact.
491) 
492)             If a socket, then a one-shot client will be constructed
493)             based on the socket to query the agent, and deconstructed
494)             afterwards.
495) 
496)             If neither are given, then the agent's socket location is
497)             looked up in the `SSH_AUTH_SOCK` environment variable, and
498)             used to construct/deconstruct a one-shot client, as in the
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 1 month ago

499)             previous case.  This requires the [`socket.AF_UNIX`][]
500)             symbol to exist.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

501) 
502)     Yields:
Marco Ricci Convert old syntax for Yiel...

Marco Ricci authored 1 month ago

503)         Every SSH key from the SSH agent that is suitable for passphrase
504)         derivation.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

505) 
506)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

507)         KeyError:
508)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
509)             variable was not found.
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 1 month ago

510)         NotImplementedError:
511)             `conn` was `None`, and this Python does not support
512)             [`socket.AF_UNIX`][], so the SSH agent client cannot be
513)             automatically set up.
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

514)         OSError:
515)             `conn` was a socket or `None`, and there was an error
516)             setting up a socket connection to the agent.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 4 months ago

517)         LookupError:
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

518)             No keys usable for passphrase derivation are loaded into the
519)             SSH agent.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 4 months ago

520)         RuntimeError:
521)             There was an error communicating with the SSH agent.
Marco Ricci Fix miscellaneous small doc...

Marco Ricci authored 2 months ago

522)         ssh_agent.SSHAgentFailedError:
Marco Ricci Add a specific error class...

Marco Ricci authored 2 months ago

523)             The agent failed to supply a list of loaded keys.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

524) 
525)     """
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

526)     client: ssh_agent.SSHAgentClient
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 3 months ago

527)     client_context: contextlib.AbstractContextManager[Any]
Marco Ricci Add support for Python 3.9

Marco Ricci authored 1 month ago

528)     # Use match/case here once Python 3.9 becomes unsupported.
529)     if isinstance(conn, ssh_agent.SSHAgentClient):
530)         client = conn
531)         client_context = contextlib.nullcontext()
532)     elif isinstance(conn, socket.socket) or conn is None:
533)         client = ssh_agent.SSHAgentClient(socket=conn)
534)         client_context = client
535)     else:  # pragma: no cover
536)         assert_never(conn)
537)         msg = f'invalid connection hint: {conn!r}'
538)         raise TypeError(msg)  # noqa: DOC501
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

539)     with client_context:
540)         try:
541)             all_key_comment_pairs = list(client.list_keys())
542)         except EOFError as e:  # pragma: no cover
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

543)             raise RuntimeError(_AGENT_COMMUNICATION_ERROR) from e
544)     suitable_keys = copy.copy(all_key_comment_pairs)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

545)     for pair in all_key_comment_pairs:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

546)         key, _comment = pair
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

547)         if vault.Vault._is_suitable_ssh_key(key):  # noqa: SLF001
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

548)             yield pair
549)     if not suitable_keys:  # pragma: no cover
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

550)         raise LookupError(_NO_USABLE_KEYS)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

551) 
552) 
553) def _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

554)     items: Sequence[str | bytes],
555)     heading: str = 'Possible choices:',
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

556)     single_choice_prompt: str = 'Confirm this choice?',
557) ) -> int:
558)     """Prompt user for a choice among the given items.
559) 
560)     Print the heading, if any, then present the items to the user.  If
561)     there are multiple items, prompt the user for a selection, validate
562)     the choice, then return the list index of the selected item.  If
563)     there is only a single item, request confirmation for that item
564)     instead, and return the correct index.
565) 
566)     Args:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

567)         items:
568)             The list of items to choose from.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

569)         heading:
570)             A heading for the list of items, to print immediately
571)             before.  Defaults to a reasonable standard heading.  If
572)             explicitly empty, print no heading.
573)         single_choice_prompt:
574)             The confirmation prompt if there is only a single possible
575)             choice.  Defaults to a reasonable standard prompt.
576) 
577)     Returns:
578)         An index into the items sequence, indicating the user's
579)         selection.
580) 
581)     Raises:
582)         IndexError:
583)             The user made an invalid or empty selection, or requested an
584)             abort.
585) 
586)     """
587)     n = len(items)
588)     if heading:
589)         click.echo(click.style(heading, bold=True))
590)     for i, x in enumerate(items, start=1):
591)         click.echo(click.style(f'[{i}]', bold=True), nl=False)
592)         click.echo(' ', nl=False)
593)         click.echo(x)
594)     if n > 1:
595)         choices = click.Choice([''] + [str(i) for i in range(1, n + 1)])
596)         choice = click.prompt(
597)             f'Your selection? (1-{n}, leave empty to abort)',
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

598)             err=True,
599)             type=choices,
600)             show_choices=False,
601)             show_default=False,
602)             default='',
603)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

604)         if not choice:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

605)             raise IndexError(_EMPTY_SELECTION)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

606)         return int(choice) - 1
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

607)     prompt_suffix = (
608)         ' ' if single_choice_prompt.endswith(tuple('?.!')) else ': '
609)     )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

610)     try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

611)         click.confirm(
612)             single_choice_prompt,
613)             prompt_suffix=prompt_suffix,
614)             err=True,
615)             abort=True,
616)             default=False,
617)             show_default=False,
618)         )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

619)     except click.Abort:
620)         raise IndexError(_EMPTY_SELECTION) from None
621)     return 0
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

622) 
623) 
624) def _select_ssh_key(
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

625)     conn: ssh_agent.SSHAgentClient | socket.socket | None = None, /
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

626) ) -> bytes | bytearray:
627)     """Interactively select an SSH key for passphrase derivation.
628) 
629)     Suitable SSH keys are queried from the running SSH agent (see
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

630)     [`ssh_agent.SSHAgentClient.list_keys`][]), then the user is prompted
631)     interactively (see [`click.prompt`][]) for a selection.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

632) 
633)     Args:
634)         conn:
635)             An optional connection hint to the SSH agent; specifically,
636)             an SSH agent client, or a socket connected to an SSH agent.
637) 
638)             If an existing SSH agent client, then this client will be
639)             queried for the SSH keys, and otherwise left intact.
640) 
641)             If a socket, then a one-shot client will be constructed
642)             based on the socket to query the agent, and deconstructed
643)             afterwards.
644) 
645)             If neither are given, then the agent's socket location is
646)             looked up in the `SSH_AUTH_SOCK` environment variable, and
647)             used to construct/deconstruct a one-shot client, as in the
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 1 month ago

648)             previous case.  This requires the [`socket.AF_UNIX`][]
649)             symbol to exist.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

650) 
651)     Returns:
652)         The selected SSH key.
653) 
654)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

655)         KeyError:
656)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
657)             variable was not found.
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 1 month ago

658)         NotImplementedError:
659)             `conn` was `None`, and this Python does not support
660)             [`socket.AF_UNIX`][], so the SSH agent client cannot be
661)             automatically set up.
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

662)         OSError:
663)             `conn` was a socket or `None`, and there was an error
664)             setting up a socket connection to the agent.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

665)         IndexError:
666)             The user made an invalid or empty selection, or requested an
667)             abort.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 4 months ago

668)         LookupError:
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

669)             No keys usable for passphrase derivation are loaded into the
670)             SSH agent.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 4 months ago

671)         RuntimeError:
672)             There was an error communicating with the SSH agent.
Marco Ricci Add a specific error class...

Marco Ricci authored 2 months ago

673)         SSHAgentFailedError:
674)             The agent failed to supply a list of loaded keys.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

675)     """
676)     suitable_keys = list(_get_suitable_ssh_keys(conn))
677)     key_listing: list[str] = []
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

678)     unstring_prefix = ssh_agent.SSHAgentClient.unstring_prefix
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

679)     for key, comment in suitable_keys:
680)         keytype = unstring_prefix(key)[0].decode('ASCII')
681)         key_str = base64.standard_b64encode(key).decode('ASCII')
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

682)         key_prefix = (
683)             key_str
684)             if len(key_str) < KEY_DISPLAY_LENGTH + len('...')
685)             else key_str[:KEY_DISPLAY_LENGTH] + '...'
686)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

687)         comment_str = comment.decode('UTF-8', errors='replace')
688)         key_listing.append(f'{keytype} {key_prefix} {comment_str}')
689)     choice = _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

690)         key_listing,
691)         heading='Suitable SSH keys:',
692)         single_choice_prompt='Use this key?',
693)     )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

694)     return suitable_keys[choice].key
695) 
696) 
697) def _prompt_for_passphrase() -> str:
698)     """Interactively prompt for the passphrase.
699) 
700)     Calls [`click.prompt`][] internally.  Moved into a separate function
701)     mainly for testing/mocking purposes.
702) 
703)     Returns:
704)         The user input.
705) 
706)     """
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 3 months ago

707)     return cast(
708)         str,
709)         click.prompt(
710)             'Passphrase',
711)             default='',
712)             hide_input=True,
713)             show_default=False,
714)             err=True,
715)         ),
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

716)     )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

717) 
718) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

719) def _check_for_misleading_passphrase(
720)     key: tuple[str, ...],
721)     value: dict[str, Any],
722)     *,
723)     form: Literal['NFC', 'NFD', 'NFKC', 'NFKD'] = 'NFC',
724) ) -> None:
725)     def is_json_identifier(x: str) -> bool:
726)         return not x.startswith(tuple('0123456789')) and not any(
727)             c.lower() not in set('0123456789abcdefghijklmnopqrstuvwxyz_')
728)             for c in x
729)         )
730) 
731)     if 'phrase' in value:
732)         phrase = value['phrase']
733)         if not unicodedata.is_normalized(form, phrase):
734)             key_path = '.'.join(
735)                 x if is_json_identifier(x) else repr(x) for x in key
736)             )
737)             click.echo(
738)                 (
739)                     f'{PROG_NAME}: Warning: the {key_path} passphrase '
740)                     f'is not {form}-normalized. Make sure to double-check '
741)                     f'this is really the passphrase you want.'
742)                 ),
743)                 err=True,
744)             )
745) 
746) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

747) class OptionGroupOption(click.Option):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

748)     """A [`click.Option`][] with an associated group name and group epilog.
749) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

750)     Used by [`CommandWithHelpGroups`][] to print help sections.  Each
751)     subclass contains its own group name and epilog.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

752) 
753)     Attributes:
754)         option_group_name:
755)             The name of the option group.  Used as a heading on the help
756)             text for options in this section.
757)         epilog:
758)             An epilog to print after listing the options in this
759)             section.
760) 
761)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

762) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

763)     option_group_name: str = ''
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

764)     """"""
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

765)     epilog: str = ''
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

766)     """"""
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

767) 
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

768)     def __init__(self, *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 3 months ago

769)         if self.__class__ == __class__:  # type: ignore[name-defined]
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

770)             raise NotImplementedError
771)         super().__init__(*args, **kwargs)
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

772) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

773) 
774) class CommandWithHelpGroups(click.Command):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

775)     """A [`click.Command`][] with support for help/option groups.
776) 
777)     Inspired by [a comment on `pallets/click#373`][CLICK_ISSUE], and
778)     further modified to support group epilogs.
779) 
780)     [CLICK_ISSUE]: https://github.com/pallets/click/issues/373#issuecomment-515293746
781) 
782)     """
783) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

784)     def format_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

785)         self,
786)         ctx: click.Context,
787)         formatter: click.HelpFormatter,
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

788)     ) -> None:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

789)         r"""Format options on the help listing, grouped into sections.
790) 
Marco Ricci Add minor documentation rew...

Marco Ricci authored 4 months ago

791)         This is a callback for [`click.Command.get_help`][] that
792)         implements the `--help` listing, by calling appropriate methods
793)         of the `formatter`.  We list all options (like the base
794)         implementation), but grouped into sections according to the
795)         concrete [`click.Option`][] subclass being used.  If the option
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

796)         is an instance of some subclass of [`OptionGroupOption`][], then
797)         the section heading and the epilog are taken from the
798)         [`option_group_name`] [OptionGroupOption.option_group_name] and
799)         [`epilog`] [OptionGroupOption.epilog] attributes; otherwise, the
800)         section heading is "Options" (or "Other options" if there are
801)         other option groups) and the epilog is empty.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

802) 
803)         Args:
804)             ctx:
805)                 The click context.
806)             formatter:
807)                 The formatter for the `--help` listing.
808) 
809)         """
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

810)         help_records: dict[str, list[tuple[str, str]]] = {}
811)         epilogs: dict[str, str] = {}
812)         params = self.params[:]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

813)         if (  # pragma: no branch
814)             (help_opt := self.get_help_option(ctx)) is not None
815)             and help_opt not in params
816)         ):
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

817)             params.append(help_opt)
818)         for param in params:
819)             rec = param.get_help_record(ctx)
820)             if rec is not None:
821)                 if isinstance(param, OptionGroupOption):
822)                     group_name = param.option_group_name
823)                     epilogs.setdefault(group_name, param.epilog)
824)                 else:
825)                     group_name = ''
826)                 help_records.setdefault(group_name, []).append(rec)
827)         default_group = help_records.pop('')
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

828)         default_group_name = (
829)             'Other Options' if len(default_group) > 1 else 'Options'
830)         )
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

831)         help_records[default_group_name] = default_group
832)         for group_name, records in help_records.items():
833)             with formatter.section(group_name):
834)                 formatter.write_dl(records)
835)             epilog = inspect.cleandoc(epilogs.get(group_name, ''))
836)             if epilog:
837)                 formatter.write_paragraph()
838)                 with formatter.indentation():
839)                     formatter.write_text(epilog)
840) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

841) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

842) # Concrete option groups used by this command-line interface.
843) class PasswordGenerationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

844)     """Password generation options for the CLI."""
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

845) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

846)     option_group_name = 'Password generation'
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

847)     epilog = """
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

848)         Use NUMBER=0, e.g. "--symbol 0", to exclude a character type
849)         from the output.
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

850)     """
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

851) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

852) 
853) class ConfigurationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

854)     """Configuration options for the CLI."""
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

855) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

856)     option_group_name = 'Configuration'
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

857)     epilog = """
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

858)         Use $VISUAL or $EDITOR to configure the spawned editor.
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

859)     """
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

860) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

861) 
862) class StorageManagementOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

863)     """Storage management options for the CLI."""
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

864) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

865)     option_group_name = 'Storage management'
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

866)     epilog = """
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

867)         Using "-" as PATH for standard input/standard output is
868)         supported.
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

869)     """
870) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

871) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

872) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

873)     ctx: click.Context,
874)     param: click.Parameter,
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

875)     value: Any,  # noqa: ANN401
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

876) ) -> int | None:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

877)     """Check that the occurrence constraint is valid (int, 0 or larger).
878) 
879)     Args:
880)         ctx: The `click` context.
881)         param: The current command-line parameter.
882)         value: The parameter value to be checked.
883) 
884)     Returns:
885)         The parsed parameter value.
886) 
887)     Raises:
888)         click.BadParameter: The parameter value is invalid.
889) 
890)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

891)     del ctx  # Unused.
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

892)     del param  # Unused.
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

893)     if value is None:
894)         return value
895)     if isinstance(value, int):
896)         int_value = value
897)     else:
898)         try:
899)             int_value = int(value, 10)
900)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

901)             msg = 'not an integer'
902)             raise click.BadParameter(msg) from e
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

903)     if int_value < 0:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

904)         msg = 'not a non-negative integer'
905)         raise click.BadParameter(msg)
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

906)     return int_value
907) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

908) 
909) def _validate_length(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

910)     ctx: click.Context,
911)     param: click.Parameter,
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

912)     value: Any,  # noqa: ANN401
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

913) ) -> int | None:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

914)     """Check that the length is valid (int, 1 or larger).
915) 
916)     Args:
917)         ctx: The `click` context.
918)         param: The current command-line parameter.
919)         value: The parameter value to be checked.
920) 
921)     Returns:
922)         The parsed parameter value.
923) 
924)     Raises:
925)         click.BadParameter: The parameter value is invalid.
926) 
927)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

928)     del ctx  # Unused.
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

929)     del param  # Unused.
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

930)     if value is None:
931)         return value
932)     if isinstance(value, int):
933)         int_value = value
934)     else:
935)         try:
936)             int_value = int(value, 10)
937)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

938)             msg = 'not an integer'
939)             raise click.BadParameter(msg) from e
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

940)     if int_value < 1:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

941)         msg = 'not a positive integer'
942)         raise click.BadParameter(msg)
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

943)     return int_value
944) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

945) 
946) DEFAULT_NOTES_TEMPLATE = """\
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

947) # Enter notes below the line with the cut mark (ASCII scissors and
948) # dashes).  Lines above the cut mark (such as this one) will be ignored.
949) #
950) # If you wish to clear the notes, leave everything beyond the cut mark
951) # blank.  However, if you leave the *entire* file blank, also removing
952) # the cut mark, then the edit is aborted, and the old notes contents are
953) # retained.
954) #
955) # - - - - - >8 - - - - - >8 - - - - - >8 - - - - - >8 - - - - -
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

956) """
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

957) DEFAULT_NOTES_MARKER = '# - - - - - >8 - - - - -'
958) 
959) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

960) @click.command(
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

961)     # 'vault',
962)     # help="derivation scheme compatible with James Coglan's vault(1)",
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

963)     context_settings={'help_option_names': ['-h', '--help']},
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

964)     cls=CommandWithHelpGroups,
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

965)     epilog=r"""
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

966)         WARNING: There is NO WAY to retrieve the generated passphrases
967)         if the master passphrase, the SSH key, or the exact passphrase
968)         settings are lost, short of trying out all possible
969)         combinations.  You are STRONGLY advised to keep independent
970)         backups of the settings and the SSH key, if any.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

971) 
972)         The configuration is NOT encrypted, and you are STRONGLY
973)         discouraged from using a stored passphrase.
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

974)     """,
975) )
976) @click.option(
977)     '-p',
978)     '--phrase',
979)     'use_phrase',
980)     is_flag=True,
981)     help='prompts you for your passphrase',
982)     cls=PasswordGenerationOption,
983) )
984) @click.option(
985)     '-k',
986)     '--key',
987)     'use_key',
988)     is_flag=True,
989)     help='uses your SSH private key to generate passwords',
990)     cls=PasswordGenerationOption,
991) )
992) @click.option(
993)     '-l',
994)     '--length',
995)     metavar='NUMBER',
996)     callback=_validate_length,
997)     help='emits password of length NUMBER',
998)     cls=PasswordGenerationOption,
999) )
1000) @click.option(
1001)     '-r',
1002)     '--repeat',
1003)     metavar='NUMBER',
1004)     callback=_validate_occurrence_constraint,
1005)     help='allows maximum of NUMBER repeated adjacent chars',
1006)     cls=PasswordGenerationOption,
1007) )
1008) @click.option(
1009)     '--lower',
1010)     metavar='NUMBER',
1011)     callback=_validate_occurrence_constraint,
1012)     help='includes at least NUMBER lowercase letters',
1013)     cls=PasswordGenerationOption,
1014) )
1015) @click.option(
1016)     '--upper',
1017)     metavar='NUMBER',
1018)     callback=_validate_occurrence_constraint,
1019)     help='includes at least NUMBER uppercase letters',
1020)     cls=PasswordGenerationOption,
1021) )
1022) @click.option(
1023)     '--number',
1024)     metavar='NUMBER',
1025)     callback=_validate_occurrence_constraint,
1026)     help='includes at least NUMBER digits',
1027)     cls=PasswordGenerationOption,
1028) )
1029) @click.option(
1030)     '--space',
1031)     metavar='NUMBER',
1032)     callback=_validate_occurrence_constraint,
1033)     help='includes at least NUMBER spaces',
1034)     cls=PasswordGenerationOption,
1035) )
1036) @click.option(
1037)     '--dash',
1038)     metavar='NUMBER',
1039)     callback=_validate_occurrence_constraint,
1040)     help='includes at least NUMBER "-" or "_"',
1041)     cls=PasswordGenerationOption,
1042) )
1043) @click.option(
1044)     '--symbol',
1045)     metavar='NUMBER',
1046)     callback=_validate_occurrence_constraint,
1047)     help='includes at least NUMBER symbol chars',
1048)     cls=PasswordGenerationOption,
1049) )
1050) @click.option(
1051)     '-n',
1052)     '--notes',
1053)     'edit_notes',
1054)     is_flag=True,
1055)     help='spawn an editor to edit notes for SERVICE',
1056)     cls=ConfigurationOption,
1057) )
1058) @click.option(
1059)     '-c',
1060)     '--config',
1061)     'store_config_only',
1062)     is_flag=True,
1063)     help='saves the given settings for SERVICE or global',
1064)     cls=ConfigurationOption,
1065) )
1066) @click.option(
1067)     '-x',
1068)     '--delete',
1069)     'delete_service_settings',
1070)     is_flag=True,
1071)     help='deletes settings for SERVICE',
1072)     cls=ConfigurationOption,
1073) )
1074) @click.option(
1075)     '--delete-globals',
1076)     is_flag=True,
1077)     help='deletes the global shared settings',
1078)     cls=ConfigurationOption,
1079) )
1080) @click.option(
1081)     '-X',
1082)     '--clear',
1083)     'clear_all_settings',
1084)     is_flag=True,
1085)     help='deletes all settings',
1086)     cls=ConfigurationOption,
1087) )
1088) @click.option(
1089)     '-e',
1090)     '--export',
1091)     'export_settings',
1092)     metavar='PATH',
1093)     help='export all saved settings into file PATH',
1094)     cls=StorageManagementOption,
1095) )
1096) @click.option(
1097)     '-i',
1098)     '--import',
1099)     'import_settings',
1100)     metavar='PATH',
1101)     help='import saved settings from file PATH',
1102)     cls=StorageManagementOption,
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1103) )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1104) @click.version_option(version=dpp.__version__, prog_name=PROG_NAME)
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1105) @click.argument('service', required=False)
1106) @click.pass_context
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

1107) def derivepassphrase_vault(  # noqa: C901,PLR0912,PLR0913,PLR0914,PLR0915
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1108)     ctx: click.Context,
1109)     /,
1110)     *,
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1111)     service: str | None = None,
1112)     use_phrase: bool = False,
1113)     use_key: bool = False,
1114)     length: int | None = None,
1115)     repeat: int | None = None,
1116)     lower: int | None = None,
1117)     upper: int | None = None,
1118)     number: int | None = None,
1119)     space: int | None = None,
1120)     dash: int | None = None,
1121)     symbol: int | None = None,
1122)     edit_notes: bool = False,
1123)     store_config_only: bool = False,
1124)     delete_service_settings: bool = False,
1125)     delete_globals: bool = False,
1126)     clear_all_settings: bool = False,
1127)     export_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
1128)     import_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1129) ) -> None:
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 2 months ago

1130)     """Derive a passphrase using the vault(1) derivation scheme.
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1131) 
Marco Ricci Fill out README and documen...

Marco Ricci authored 4 months ago

1132)     Using a master passphrase or a master SSH key, derive a passphrase
1133)     for SERVICE, subject to length, character and character repetition
1134)     constraints.  The derivation is cryptographically strong, meaning
1135)     that even if a single passphrase is compromised, guessing the master
1136)     passphrase or a different service's passphrase is computationally
1137)     infeasible.  The derivation is also deterministic, given the same
1138)     inputs, thus the resulting passphrase need not be stored explicitly.
1139)     The service name and constraints themselves also need not be kept
1140)     secret; the latter are usually stored in a world-readable file.
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1141) 
1142)     If operating on global settings, or importing/exporting settings,
1143)     then SERVICE must be omitted.  Otherwise it is required.\f
1144) 
1145)     This is a [`click`][CLICK]-powered command-line interface function,
1146)     and not intended for programmatic use.  Call with arguments
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1147)     `['--help']` to see full documentation of the interface.  (See also
1148)     [`click.testing.CliRunner`][] for controlled, programmatic
1149)     invocation.)
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1150) 
Marco Ricci Update all URLs to stable a...

Marco Ricci authored 1 month ago

1151)     [CLICK]: https://pypi.org/package/click/
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1152) 
1153)     Parameters:
1154)         ctx (click.Context):
1155)             The `click` context.
1156) 
1157)     Other Parameters:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1158)         service:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1159)             A service name.  Required, unless operating on global
1160)             settings or importing/exporting settings.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1161)         use_phrase:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1162)             Command-line argument `-p`/`--phrase`.  If given, query the
1163)             user for a passphrase instead of an SSH key.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1164)         use_key:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1165)             Command-line argument `-k`/`--key`.  If given, query the
1166)             user for an SSH key instead of a passphrase.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1167)         length:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1168)             Command-line argument `-l`/`--length`.  Override the default
1169)             length of the generated passphrase.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1170)         repeat:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1171)             Command-line argument `-r`/`--repeat`.  Override the default
1172)             repetition limit if positive, or disable the repetition
1173)             limit if 0.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1174)         lower:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1175)             Command-line argument `--lower`.  Require a given amount of
1176)             ASCII lowercase characters if positive, else forbid ASCII
1177)             lowercase characters if 0.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1178)         upper:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1179)             Command-line argument `--upper`.  Same as `lower`, but for
1180)             ASCII uppercase characters.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1181)         number:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1182)             Command-line argument `--number`.  Same as `lower`, but for
1183)             ASCII digits.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1184)         space:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

1185)             Command-line argument `--space`.  Same as `lower`, but for
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1186)             the space character.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1187)         dash:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

1188)             Command-line argument `--dash`.  Same as `lower`, but for
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1189)             the hyphen-minus and underscore characters.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1190)         symbol:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

1191)             Command-line argument `--symbol`.  Same as `lower`, but for
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1192)             all other ASCII printable characters (except backquote).
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1193)         edit_notes:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1194)             Command-line argument `-n`/`--notes`.  If given, spawn an
1195)             editor to edit notes for `service`.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1196)         store_config_only:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1197)             Command-line argument `-c`/`--config`.  If given, saves the
1198)             other given settings (`--key`, ..., `--symbol`) to the
1199)             configuration file, either specifically for `service` or as
1200)             global settings.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1201)         delete_service_settings:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1202)             Command-line argument `-x`/`--delete`.  If given, removes
1203)             the settings for `service` from the configuration file.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1204)         delete_globals:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1205)             Command-line argument `--delete-globals`.  If given, removes
1206)             the global settings from the configuration file.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1207)         clear_all_settings:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1208)             Command-line argument `-X`/`--clear`.  If given, removes all
1209)             settings from the configuration file.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1210)         export_settings:
1211)             Command-line argument `-e`/`--export`.  If a file object,
1212)             then it must be open for writing and accept `str` inputs.
1213)             Otherwise, a filename to open for writing.  Using `-` for
1214)             standard output is supported.
1215)         import_settings:
1216)             Command-line argument `-i`/`--import`.  If a file object, it
1217)             must be open for reading and yield `str` values.  Otherwise,
1218)             a filename to open for reading.  Using `-` for standard
1219)             input is supported.
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1220) 
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

1221)     """  # noqa: D301
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1222)     options_in_group: dict[type[click.Option], list[click.Option]] = {}
1223)     params_by_str: dict[str, click.Parameter] = {}
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1224)     for param in ctx.command.params:
1225)         if isinstance(param, click.Option):
1226)             group: type[click.Option]
Marco Ricci Add support for Python 3.9

Marco Ricci authored 1 month ago

1227)             # Use match/case here once Python 3.9 becomes unsupported.
1228)             if isinstance(param, PasswordGenerationOption):
1229)                 group = PasswordGenerationOption
1230)             elif isinstance(param, ConfigurationOption):
1231)                 group = ConfigurationOption
1232)             elif isinstance(param, StorageManagementOption):
1233)                 group = StorageManagementOption
1234)             elif isinstance(param, OptionGroupOption):
1235)                 raise AssertionError(  # noqa: DOC501,TRY003,TRY004
1236)                     f'Unknown option group for {param!r}'  # noqa: EM102
1237)                 )
1238)             else:
1239)                 group = click.Option
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1240)             options_in_group.setdefault(group, []).append(param)
1241)         params_by_str[param.human_readable_name] = param
1242)         for name in param.opts + param.secondary_opts:
1243)             params_by_str[name] = param
1244) 
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 3 months ago

1245)     def is_param_set(param: click.Parameter) -> bool:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1246)         return bool(ctx.params.get(param.human_readable_name))
1247) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1248)     def check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1249)         param: click.Parameter | str,
1250)         *incompatible: click.Parameter | str,
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1251)     ) -> None:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1252)         if isinstance(param, str):
1253)             param = params_by_str[param]
1254)         assert isinstance(param, click.Parameter)
1255)         if not is_param_set(param):
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1256)             return
1257)         for other in incompatible:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1258)             if isinstance(other, str):
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1259)                 other = params_by_str[other]  # noqa: PLW2901
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1260)             assert isinstance(other, click.Parameter)
1261)             if other != param and is_param_set(other):
1262)                 opt_str = param.opts[0]
1263)                 other_str = other.opts[0]
1264)                 raise click.BadOptionUsage(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1265)                     opt_str, f'mutually exclusive with {other_str}', ctx=ctx
1266)                 )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1267) 
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1268)     def err(msg: str) -> NoReturn:
1269)         click.echo(f'{PROG_NAME}: {msg}', err=True)
1270)         ctx.exit(1)
1271) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

1272)     def get_config() -> _types.VaultConfig:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1273)         try:
1274)             return _load_config()
1275)         except FileNotFoundError:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

1276)             try:
1277)                 backup_config, exc = _migrate_and_load_old_config()
1278)             except FileNotFoundError:
1279)                 return {'services': {}}
1280)             old_name = os.path.basename(_config_filename())
1281)             new_name = os.path.basename(_config_filename(subsystem='vault'))
1282)             click.echo(
1283)                 (
1284)                     f'{PROG_NAME}: Using deprecated v0.1-style config file '
1285)                     f'{old_name!r}, instead of v0.2-style {new_name!r}.  '
1286)                     f'Support for v0.1-style config filenames will be '
1287)                     f'removed in v1.0.'
1288)                 ),
1289)                 err=True,
1290)             )
1291)             if isinstance(exc, OSError):
1292)                 click.echo(
1293)                     (
1294)                         f'{PROG_NAME}: Warning: Failed to migrate to '
1295)                         f'{new_name!r}: {exc.strerror}: {exc.filename!r}'
1296)                     ),
1297)                     err=True,
1298)                 )
1299)             else:
1300)                 click.echo(
1301)                     f'{PROG_NAME}: Successfully migrated to {new_name!r}.',
1302)                     err=True,
1303)                 )
1304)             return backup_config
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

1305)         except OSError as e:
1306)             err(f'Cannot load config: {e.strerror}: {e.filename!r}')
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1307)         except Exception as e:  # noqa: BLE001
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1308)             err(f'Cannot load config: {e}')
1309) 
1310)     def put_config(config: _types.VaultConfig, /) -> None:
1311)         try:
1312)             _save_config(config)
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

1313)         except OSError as exc:
1314)             err(f'Cannot store config: {exc.strerror}: {exc.filename!r}')
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1315)         except Exception as exc:  # noqa: BLE001
1316)             err(f'Cannot store config: {exc}')
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1317) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

1318)     configuration: _types.VaultConfig
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1319) 
1320)     check_incompatible_options('--phrase', '--key')
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1321)     for group in (ConfigurationOption, StorageManagementOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1322)         for opt in options_in_group[group]:
1323)             if opt != params_by_str['--config']:
1324)                 check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1325)                     opt, *options_in_group[PasswordGenerationOption]
1326)                 )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1327) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1328)     for group in (ConfigurationOption, StorageManagementOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1329)         for opt in options_in_group[group]:
1330)             check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1331)                 opt,
1332)                 *options_in_group[ConfigurationOption],
1333)                 *options_in_group[StorageManagementOption],
1334)             )
1335)     sv_options = options_in_group[PasswordGenerationOption] + [
1336)         params_by_str['--notes'],
1337)         params_by_str['--delete'],
1338)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1339)     sv_options.remove(params_by_str['--key'])
1340)     sv_options.remove(params_by_str['--phrase'])
1341)     for param in sv_options:
1342)         if is_param_set(param) and not service:
1343)             opt_str = param.opts[0]
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1344)             msg = f'{opt_str} requires a SERVICE'
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

1345)             raise click.UsageError(msg)  # noqa: DOC501
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1346)     for param in [params_by_str['--key'], params_by_str['--phrase']]:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1347)         if is_param_set(param) and not (
1348)             service or is_param_set(params_by_str['--config'])
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1349)         ):
1350)             opt_str = param.opts[0]
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1351)             msg = f'{opt_str} requires a SERVICE or --config'
1352)             raise click.UsageError(msg)
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1353)     no_sv_options = [
1354)         params_by_str['--delete-globals'],
1355)         params_by_str['--clear'],
1356)         *options_in_group[StorageManagementOption],
1357)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1358)     for param in no_sv_options:
1359)         if is_param_set(param) and service:
1360)             opt_str = param.opts[0]
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1361)             msg = f'{opt_str} does not take a SERVICE argument'
1362)             raise click.UsageError(msg)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1363) 
1364)     if edit_notes:
1365)         assert service is not None
1366)         configuration = get_config()
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1367)         text = DEFAULT_NOTES_TEMPLATE + configuration['services'].get(
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

1368)             service, cast(_types.VaultConfigServicesSettings, {})
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1369)         ).get('notes', '')
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1370)         notes_value = click.edit(text=text)
1371)         if notes_value is not None:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

1372)             notes_lines = collections.deque(notes_value.splitlines(True))  # noqa: FBT003
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1373)             while notes_lines:
1374)                 line = notes_lines.popleft()
1375)                 if line.startswith(DEFAULT_NOTES_MARKER):
1376)                     notes_value = ''.join(notes_lines)
1377)                     break
1378)             else:
1379)                 if not notes_value.strip():
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 2 months ago

1380)                     err('Not saving new notes: user aborted request')
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1381)             configuration['services'].setdefault(service, {})['notes'] = (
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1382)                 notes_value.strip('\n')
1383)             )
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1384)             put_config(configuration)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1385)     elif delete_service_settings:
1386)         assert service is not None
1387)         configuration = get_config()
1388)         if service in configuration['services']:
1389)             del configuration['services'][service]
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1390)             put_config(configuration)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1391)     elif delete_globals:
1392)         configuration = get_config()
1393)         if 'global' in configuration:
1394)             del configuration['global']
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1395)             put_config(configuration)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1396)     elif clear_all_settings:
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1397)         put_config({'services': {}})
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1398)     elif import_settings:
1399)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

1400)             # TODO(the-13th-letter): keep track of auto-close; try
1401)             # os.dup if feasible
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1402)             infile = (
1403)                 cast(TextIO, import_settings)
1404)                 if hasattr(import_settings, 'close')
1405)                 else click.open_file(os.fspath(import_settings), 'rt')
1406)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1407)             with infile:
1408)                 maybe_config = json.load(infile)
1409)         except json.JSONDecodeError as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1410)             err(f'Cannot load config: cannot decode JSON: {e}')
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1411)         except OSError as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1412)             err(f'Cannot load config: {e.strerror}: {e.filename!r}')
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

1413)         if _types.is_vault_config(maybe_config):
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

1414)             form = cast(
1415)                 Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1416)                 maybe_config.get('global', {}).get(
1417)                     'unicode_normalization_form', 'NFC'
1418)                 ),
1419)             )
1420)             assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1421)             _check_for_misleading_passphrase(
1422)                 ('global',),
1423)                 cast(dict[str, Any], maybe_config.get('global', {})),
1424)                 form=form,
1425)             )
1426)             for key, value in maybe_config['services'].items():
1427)                 _check_for_misleading_passphrase(
1428)                     ('services', key),
1429)                     cast(dict[str, Any], value),
1430)                     form=form,
1431)                 )
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1432)             put_config(maybe_config)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1433)         else:
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1434)             err(f'Cannot load config: {_INVALID_VAULT_CONFIG}')
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1435)     elif export_settings:
1436)         configuration = get_config()
1437)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

1438)             # TODO(the-13th-letter): keep track of auto-close; try
1439)             # os.dup if feasible
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1440)             outfile = (
1441)                 cast(TextIO, export_settings)
1442)                 if hasattr(export_settings, 'close')
1443)                 else click.open_file(os.fspath(export_settings), 'wt')
1444)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1445)             with outfile:
1446)                 json.dump(configuration, outfile)
1447)         except OSError as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1448)             err(f'Cannot store config: {e.strerror}: {e.filename!r}')
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1449)     else:
1450)         configuration = get_config()
1451)         # This block could be type checked more stringently, but this
1452)         # would probably involve a lot of code repetition.  Since we
1453)         # have a type guarding function anyway, assert that we didn't
1454)         # make any mistakes at the end instead.
1455)         global_keys = {'key', 'phrase'}
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1456)         service_keys = {
1457)             'key',
1458)             'phrase',
1459)             'length',
1460)             'repeat',
1461)             'lower',
1462)             'upper',
1463)             'number',
1464)             'space',
1465)             'dash',
1466)             'symbol',
1467)         }
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1468)         settings: collections.ChainMap[str, Any] = collections.ChainMap(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1469)             {
1470)                 k: v
1471)                 for k, v in locals().items()
1472)                 if k in service_keys and v is not None
1473)             },
1474)             cast(
1475)                 dict[str, Any],
1476)                 configuration['services'].get(service or '', {}),
1477)             ),
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1478)             {},
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1479)             cast(dict[str, Any], configuration.get('global', {})),
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1480)         )
1481)         if use_key:
1482)             try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1483)                 key = base64.standard_b64encode(_select_ssh_key()).decode(
1484)                     'ASCII'
1485)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1486)             except IndexError:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 2 months ago

1487)                 err('No valid SSH key selected')
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

1488)             except KeyError:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 2 months ago

1489)                 err('Cannot find running SSH agent; check SSH_AUTH_SOCK')
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 1 month ago

1490)             except NotImplementedError:
1491)                 err(
1492)                     'Cannot connect to SSH agent because '
1493)                     'this Python version does not support UNIX domain sockets'
1494)                 )
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

1495)             except OSError as e:
1496)                 err(
1497)                     f'Cannot connect to SSH agent: {e.strerror}: '
1498)                     f'{e.filename!r}'
1499)                 )
Marco Ricci Add a specific error class...

Marco Ricci authored 2 months ago

1500)             except (
1501)                 LookupError,
1502)                 RuntimeError,
1503)                 ssh_agent.SSHAgentFailedError,
1504)             ) as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

1505)                 err(str(e))
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1506)         elif use_phrase:
1507)             maybe_phrase = _prompt_for_passphrase()
1508)             if not maybe_phrase:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 2 months ago

1509)                 err('No passphrase given')
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1510)             else:
1511)                 phrase = maybe_phrase
1512)         if store_config_only:
1513)             view: collections.ChainMap[str, Any]
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1514)             view = (
1515)                 collections.ChainMap(*settings.maps[:2])
1516)                 if service
1517)                 else settings.parents.parents
1518)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1519)             if use_key:
1520)                 view['key'] = key
1521)                 for m in view.maps:
1522)                     m.pop('phrase', '')
1523)             elif use_phrase:
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

1524)                 _check_for_misleading_passphrase(
1525)                     ('services', service) if service else ('global',),
1526)                     {'phrase': phrase},
1527)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1528)                 view['phrase'] = phrase
1529)                 for m in view.maps:
1530)                     m.pop('key', '')
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1531)             if not view.maps[0]:
1532)                 settings_type = 'service' if service else 'global'
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1533)                 msg = (
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 2 months ago

1534)                     f'Cannot update {settings_type} settings without '
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1535)                     f'actual settings'
1536)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1537)                 raise click.UsageError(msg)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1538)             if service:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1539)                 configuration['services'].setdefault(service, {}).update(view)  # type: ignore[typeddict-item]
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1540)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1541)                 configuration.setdefault('global', {}).update(view)  # type: ignore[typeddict-item]
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

1542)             assert _types.is_vault_config(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1543)                 configuration
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 2 months ago

1544)             ), f'Invalid vault configuration: {configuration!r}'
Marco Ricci Fix error bubbling in outda...

Marco Ricci authored 2 months ago

1545)             put_config(configuration)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1546)         else:
1547)             if not service:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1548)                 msg = 'SERVICE is required'
1549)                 raise click.UsageError(msg)
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1550)             kwargs: dict[str, Any] = {
1551)                 k: v
1552)                 for k, v in settings.items()
1553)                 if k in service_keys and v is not None
1554)             }
1555) 
Marco Ricci Shift misplaced local function

Marco Ricci authored 3 months ago

1556)             def key_to_phrase(
1557)                 key: str | bytes | bytearray,
1558)             ) -> bytes | bytearray:
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

1559)                 return vault.Vault.phrase_from_key(
Marco Ricci Shift misplaced local function

Marco Ricci authored 3 months ago

1560)                     base64.standard_b64decode(key)
1561)                 )
1562) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

1563)             if use_phrase:
1564)                 form = cast(
1565)                     Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1566)                     configuration.get('global', {}).get(
1567)                         'unicode_normalization_form', 'NFC'
1568)                     ),
1569)                 )
1570)                 assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1571)                 _check_for_misleading_passphrase(
1572)                     ('interactive',), {'phrase': phrase}, form=form
1573)                 )
1574) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1575)             # If either --key or --phrase are given, use that setting.
1576)             # Otherwise, if both key and phrase are set in the config,
1577)             # one must be global (ignore it) and one must be
1578)             # service-specific (use that one). Otherwise, if only one of
1579)             # key and phrase is set in the config, use that one.  In all
1580)             # these above cases, set the phrase via
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

1581)             # derivepassphrase.vault.Vault.phrase_from_key if a key is
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1582)             # given. Finally, if nothing is set, error out.
1583)             if use_key or use_phrase:
Marco Ricci Avoid crashing when overrid...

Marco Ricci authored 3 months ago

1584)                 kwargs['phrase'] = key_to_phrase(key) if use_key else phrase
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1585)             elif kwargs.get('phrase') and kwargs.get('key'):
1586)                 if any('key' in m for m in settings.maps[:2]):
Marco Ricci Avoid crashing when overrid...

Marco Ricci authored 3 months ago

1587)                     kwargs['phrase'] = key_to_phrase(kwargs['key'])
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1588)             elif kwargs.get('key'):
Marco Ricci Avoid crashing when overrid...

Marco Ricci authored 3 months ago

1589)                 kwargs['phrase'] = key_to_phrase(kwargs['key'])
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1590)             elif kwargs.get('phrase'):
1591)                 pass
1592)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1593)                 msg = (
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 2 months ago

1594)                     'No passphrase or key given on command-line '
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1595)                     'or in configuration'
1596)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

1597)                 raise click.UsageError(msg)
Marco Ricci Avoid crashing when overrid...

Marco Ricci authored 3 months ago

1598)             kwargs.pop('key', '')
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

1599)             result = vault.Vault(**kwargs).generate(service)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1600)             click.echo(result.decode('ASCII'))