eea542a5c4507c46f795152b3e6577b1408df4bd
Marco Ricci Change the author e-mail ad...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 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 5 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 6 months ago

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

Marco Ricci authored 3 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 3 months ago

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

Marco Ricci authored 3 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 3 months ago

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

Marco Ricci authored 3 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 3 months ago

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

Marco Ricci authored 3 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 2 months 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 3 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 3 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 6 months ago

352) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 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 6 months ago

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

Marco Ricci authored 5 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 2 months 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 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months 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 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 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 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 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 2 months 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 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 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 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

448) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 2 months 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 6 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 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 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 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 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 2 months ago

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

Marco Ricci authored 6 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
499)             previous case.
500) 
501)     Yields:
Marco Ricci Convert old syntax for Yiel...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

506)         KeyError:
507)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
508)             variable was not found.
509)         OSError:
510)             `conn` was a socket or `None`, and there was an error
511)             setting up a socket connection to the agent.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

519) 
520)     """
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

534)     with client_context:
535)         try:
536)             all_key_comment_pairs = list(client.list_keys())
537)         except EOFError as e:  # pragma: no cover
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

546) 
547) 
548) def _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

593)             err=True,
594)             type=choices,
595)             show_choices=False,
596)             show_default=False,
597)             default='',
598)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

602)     prompt_suffix = (
603)         ' ' if single_choice_prompt.endswith(tuple('?.!')) else ': '
604)     )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

605)     try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

606)         click.confirm(
607)             single_choice_prompt,
608)             prompt_suffix=prompt_suffix,
609)             err=True,
610)             abort=True,
611)             default=False,
612)             show_default=False,
613)         )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

614)     except click.Abort:
615)         raise IndexError(_EMPTY_SELECTION) from None
616)     return 0
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

617) 
618) 
619) def _select_ssh_key(
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

627) 
628)     Args:
629)         conn:
630)             An optional connection hint to the SSH agent; specifically,
631)             an SSH agent client, or a socket connected to an SSH agent.
632) 
633)             If an existing SSH agent client, then this client will be
634)             queried for the SSH keys, and otherwise left intact.
635) 
636)             If a socket, then a one-shot client will be constructed
637)             based on the socket to query the agent, and deconstructed
638)             afterwards.
639) 
640)             If neither are given, then the agent's socket location is
641)             looked up in the `SSH_AUTH_SOCK` environment variable, and
642)             used to construct/deconstruct a one-shot client, as in the
643)             previous case.
644) 
645)     Returns:
646)         The selected SSH key.
647) 
648)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

649)         KeyError:
650)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
651)             variable was not found.
652)         OSError:
653)             `conn` was a socket or `None`, and there was an error
654)             setting up a socket connection to the agent.
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

655)         IndexError:
656)             The user made an invalid or empty selection, or requested an
657)             abort.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

665)     """
666)     suitable_keys = list(_get_suitable_ssh_keys(conn))
667)     key_listing: list[str] = []
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

672)         key_prefix = (
673)             key_str
674)             if len(key_str) < KEY_DISPLAY_LENGTH + len('...')
675)             else key_str[:KEY_DISPLAY_LENGTH] + '...'
676)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

680)         key_listing,
681)         heading='Suitable SSH keys:',
682)         single_choice_prompt='Use this key?',
683)     )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

684)     return suitable_keys[choice].key
685) 
686) 
687) def _prompt_for_passphrase() -> str:
688)     """Interactively prompt for the passphrase.
689) 
690)     Calls [`click.prompt`][] internally.  Moved into a separate function
691)     mainly for testing/mocking purposes.
692) 
693)     Returns:
694)         The user input.
695) 
696)     """
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

697)     return cast(
698)         str,
699)         click.prompt(
700)             'Passphrase',
701)             default='',
702)             hide_input=True,
703)             show_default=False,
704)             err=True,
705)         ),
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

707) 
708) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

742) 
743)     Attributes:
744)         option_group_name:
745)             The name of the option group.  Used as a heading on the help
746)             text for options in this section.
747)         epilog:
748)             An epilog to print after listing the options in this
749)             section.
750) 
751)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

752) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

763) 
764) class CommandWithHelpGroups(click.Command):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

765)     """A [`click.Command`][] with support for help/option groups.
766) 
767)     Inspired by [a comment on `pallets/click#373`][CLICK_ISSUE], and
768)     further modified to support group epilogs.
769) 
770)     [CLICK_ISSUE]: https://github.com/pallets/click/issues/373#issuecomment-515293746
771) 
772)     """
773) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

774)     def format_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

775)         self,
776)         ctx: click.Context,
777)         formatter: click.HelpFormatter,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

786)         is an instance of some subclass of [`OptionGroupOption`][], then
787)         the section heading and the epilog are taken from the
788)         [`option_group_name`] [OptionGroupOption.option_group_name] and
789)         [`epilog`] [OptionGroupOption.epilog] attributes; otherwise, the
790)         section heading is "Options" (or "Other options" if there are
791)         other option groups) and the epilog is empty.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

792) 
793)         Args:
794)             ctx:
795)                 The click context.
796)             formatter:
797)                 The formatter for the `--help` listing.
798) 
799)         """
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

800)         help_records: dict[str, list[tuple[str, str]]] = {}
801)         epilogs: dict[str, str] = {}
802)         params = self.params[:]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

803)         if (  # pragma: no branch
804)             (help_opt := self.get_help_option(ctx)) is not None
805)             and help_opt not in params
806)         ):
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

807)             params.append(help_opt)
808)         for param in params:
809)             rec = param.get_help_record(ctx)
810)             if rec is not None:
811)                 if isinstance(param, OptionGroupOption):
812)                     group_name = param.option_group_name
813)                     epilogs.setdefault(group_name, param.epilog)
814)                 else:
815)                     group_name = ''
816)                 help_records.setdefault(group_name, []).append(rec)
817)         default_group = help_records.pop('')
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

818)         default_group_name = (
819)             'Other Options' if len(default_group) > 1 else 'Options'
820)         )
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

821)         help_records[default_group_name] = default_group
822)         for group_name, records in help_records.items():
823)             with formatter.section(group_name):
824)                 formatter.write_dl(records)
825)             epilog = inspect.cleandoc(epilogs.get(group_name, ''))
826)             if epilog:
827)                 formatter.write_paragraph()
828)                 with formatter.indentation():
829)                     formatter.write_text(epilog)
830) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

842) 
843) class ConfigurationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

851) 
852) class StorageManagementOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

861) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

862) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

867)     """Check that the occurrence constraint is valid (int, 0 or larger).
868) 
869)     Args:
870)         ctx: The `click` context.
871)         param: The current command-line parameter.
872)         value: The parameter value to be checked.
873) 
874)     Returns:
875)         The parsed parameter value.
876) 
877)     Raises:
878)         click.BadParameter: The parameter value is invalid.
879) 
880)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

883)     if value is None:
884)         return value
885)     if isinstance(value, int):
886)         int_value = value
887)     else:
888)         try:
889)             int_value = int(value, 10)
890)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

896)     return int_value
897) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

898) 
899) def _validate_length(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

904)     """Check that the length is valid (int, 1 or larger).
905) 
906)     Args:
907)         ctx: The `click` context.
908)         param: The current command-line parameter.
909)         value: The parameter value to be checked.
910) 
911)     Returns:
912)         The parsed parameter value.
913) 
914)     Raises:
915)         click.BadParameter: The parameter value is invalid.
916) 
917)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

920)     if value is None:
921)         return value
922)     if isinstance(value, int):
923)         int_value = value
924)     else:
925)         try:
926)             int_value = int(value, 10)
927)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

933)     return int_value
934) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

935) 
936) DEFAULT_NOTES_TEMPLATE = """\
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

937) # Enter notes below the line with the cut mark (ASCII scissors and
938) # dashes).  Lines above the cut mark (such as this one) will be ignored.
939) #
940) # If you wish to clear the notes, leave everything beyond the cut mark
941) # blank.  However, if you leave the *entire* file blank, also removing
942) # the cut mark, then the edit is aborted, and the old notes contents are
943) # retained.
944) #
945) # - - - - - >8 - - - - - >8 - - - - - >8 - - - - - >8 - - - - -
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

947) DEFAULT_NOTES_MARKER = '# - - - - - >8 - - - - -'
948) 
949) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1098)     ctx: click.Context,
1099)     /,
1100)     *,
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1101)     service: str | None = None,
1102)     use_phrase: bool = False,
1103)     use_key: bool = False,
1104)     length: int | None = None,
1105)     repeat: int | None = None,
1106)     lower: int | None = None,
1107)     upper: int | None = None,
1108)     number: int | None = None,
1109)     space: int | None = None,
1110)     dash: int | None = None,
1111)     symbol: int | None = None,
1112)     edit_notes: bool = False,
1113)     store_config_only: bool = False,
1114)     delete_service_settings: bool = False,
1115)     delete_globals: bool = False,
1116)     clear_all_settings: bool = False,
1117)     export_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
1118)     import_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1122)     Using a master passphrase or a master SSH key, derive a passphrase
1123)     for SERVICE, subject to length, character and character repetition
1124)     constraints.  The derivation is cryptographically strong, meaning
1125)     that even if a single passphrase is compromised, guessing the master
1126)     passphrase or a different service's passphrase is computationally
1127)     infeasible.  The derivation is also deterministic, given the same
1128)     inputs, thus the resulting passphrase need not be stored explicitly.
1129)     The service name and constraints themselves also need not be kept
1130)     secret; the latter are usually stored in a world-readable file.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1142) 
1143)     Parameters:
1144)         ctx (click.Context):
1145)             The `click` context.
1146) 
1147)     Other Parameters:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1200)         export_settings:
1201)             Command-line argument `-e`/`--export`.  If a file object,
1202)             then it must be open for writing and accept `str` inputs.
1203)             Otherwise, a filename to open for writing.  Using `-` for
1204)             standard output is supported.
1205)         import_settings:
1206)             Command-line argument `-i`/`--import`.  If a file object, it
1207)             must be open for reading and yield `str` values.  Otherwise,
1208)             a filename to open for reading.  Using `-` for standard
1209)             input is supported.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

1217)             # Use match/case here once Python 3.9 becomes unsupported.
1218)             if isinstance(param, PasswordGenerationOption):
1219)                 group = PasswordGenerationOption
1220)             elif isinstance(param, ConfigurationOption):
1221)                 group = ConfigurationOption
1222)             elif isinstance(param, StorageManagementOption):
1223)                 group = StorageManagementOption
1224)             elif isinstance(param, OptionGroupOption):
1225)                 raise AssertionError(  # noqa: DOC501,TRY003,TRY004
1226)                     f'Unknown option group for {param!r}'  # noqa: EM102
1227)                 )
1228)             else:
1229)                 group = click.Option
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1230)             options_in_group.setdefault(group, []).append(param)
1231)         params_by_str[param.human_readable_name] = param
1232)         for name in param.opts + param.secondary_opts:
1233)             params_by_str[name] = param
1234) 
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1238)     def check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1242)         if isinstance(param, str):
1243)             param = params_by_str[param]
1244)         assert isinstance(param, click.Parameter)
1245)         if not is_param_set(param):
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

1246)             return
1247)         for other in incompatible:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1250)             assert isinstance(other, click.Parameter)
1251)             if other != param and is_param_set(other):
1252)                 opt_str = param.opts[0]
1253)                 other_str = other.opts[0]
1254)                 raise click.BadOptionUsage(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1258)     def err(msg: str) -> NoReturn:
1259)         click.echo(f'{PROG_NAME}: {msg}', err=True)
1260)         ctx.exit(1)
1261) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1263)         try:
1264)             return _load_config()
1265)         except FileNotFoundError:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

1298)             err(f'Cannot load config: {e}')
1299) 
1300)     def put_config(config: _types.VaultConfig, /) -> None:
1301)         try:
1302)             _save_config(config)
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1309) 
1310)     check_incompatible_options('--phrase', '--key')
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1315)                     opt, *options_in_group[PasswordGenerationOption]
1316)                 )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1321)                 opt,
1322)                 *options_in_group[ConfigurationOption],
1323)                 *options_in_group[StorageManagementOption],
1324)             )
1325)     sv_options = options_in_group[PasswordGenerationOption] + [
1326)         params_by_str['--notes'],
1327)         params_by_str['--delete'],
1328)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1329)     sv_options.remove(params_by_str['--key'])
1330)     sv_options.remove(params_by_str['--phrase'])
1331)     for param in sv_options:
1332)         if is_param_set(param) and not service:
1333)             opt_str = param.opts[0]
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

1343)     no_sv_options = [
1344)         params_by_str['--delete-globals'],
1345)         params_by_str['--clear'],
1346)         *options_in_group[StorageManagementOption],
1347)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1353) 
1354)     if edit_notes:
1355)         assert service is not None
1356)         configuration = get_config()
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1363)             while notes_lines:
1364)                 line = notes_lines.popleft()
1365)                 if line.startswith(DEFAULT_NOTES_MARKER):
1366)                     notes_value = ''.join(notes_lines)
1367)                     break
1368)             else:
1369)                 if not notes_value.strip():
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1372)                 notes_value.strip('\n')
1373)             )
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1375)     elif delete_service_settings:
1376)         assert service is not None
1377)         configuration = get_config()
1378)         if service in configuration['services']:
1379)             del configuration['services'][service]
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1381)     elif delete_globals:
1382)         configuration = get_config()
1383)         if 'global' in configuration:
1384)             del configuration['global']
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1388)     elif import_settings:
1389)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1392)             infile = (
1393)                 cast(TextIO, import_settings)
1394)                 if hasattr(import_settings, 'close')
1395)                 else click.open_file(os.fspath(import_settings), 'rt')
1396)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1397)             with infile:
1398)                 maybe_config = json.load(infile)
1399)         except json.JSONDecodeError as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

1404)             form = cast(
1405)                 Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1406)                 maybe_config.get('global', {}).get(
1407)                     'unicode_normalization_form', 'NFC'
1408)                 ),
1409)             )
1410)             assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1411)             _check_for_misleading_passphrase(
1412)                 ('global',),
1413)                 cast(dict[str, Any], maybe_config.get('global', {})),
1414)                 form=form,
1415)             )
1416)             for key, value in maybe_config['services'].items():
1417)                 _check_for_misleading_passphrase(
1418)                     ('services', key),
1419)                     cast(dict[str, Any], value),
1420)                     form=form,
1421)                 )
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1425)     elif export_settings:
1426)         configuration = get_config()
1427)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1430)             outfile = (
1431)                 cast(TextIO, export_settings)
1432)                 if hasattr(export_settings, 'close')
1433)                 else click.open_file(os.fspath(export_settings), 'wt')
1434)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1435)             with outfile:
1436)                 json.dump(configuration, outfile)
1437)         except OSError as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1446)         service_keys = {
1447)             'key',
1448)             'phrase',
1449)             'length',
1450)             'repeat',
1451)             'lower',
1452)             'upper',
1453)             'number',
1454)             'space',
1455)             'dash',
1456)             'symbol',
1457)         }
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1459)             {
1460)                 k: v
1461)                 for k, v in locals().items()
1462)                 if k in service_keys and v is not None
1463)             },
1464)             cast(
1465)                 dict[str, Any],
1466)                 configuration['services'].get(service or '', {}),
1467)             ),
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1468)             {},
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1470)         )
1471)         if use_key:
1472)             try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1473)                 key = base64.standard_b64encode(_select_ssh_key()).decode(
1474)                     'ASCII'
1475)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

1479)                 err('Cannot find running SSH agent; check SSH_AUTH_SOCK')
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

1480)             except OSError as e:
1481)                 err(
1482)                     f'Cannot connect to SSH agent: {e.strerror}: '
1483)                     f'{e.filename!r}'
1484)                 )
Marco Ricci Add a specific error class...

Marco Ricci authored 4 months ago

1485)             except (
1486)                 LookupError,
1487)                 RuntimeError,
1488)                 ssh_agent.SSHAgentFailedError,
1489)             ) as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1491)         elif use_phrase:
1492)             maybe_phrase = _prompt_for_passphrase()
1493)             if not maybe_phrase:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1495)             else:
1496)                 phrase = maybe_phrase
1497)         if store_config_only:
1498)             view: collections.ChainMap[str, Any]
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1499)             view = (
1500)                 collections.ChainMap(*settings.maps[:2])
1501)                 if service
1502)                 else settings.parents.parents
1503)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1504)             if use_key:
1505)                 view['key'] = key
1506)                 for m in view.maps:
1507)                     m.pop('phrase', '')
1508)             elif use_phrase:
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

1509)                 _check_for_misleading_passphrase(
1510)                     ('services', service) if service else ('global',),
1511)                     {'phrase': phrase},
1512)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

1520)                     f'actual settings'
1521)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1523)             if service:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1525)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1531)         else:
1532)             if not service:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

1535)             kwargs: dict[str, Any] = {
1536)                 k: v
1537)                 for k, v in settings.items()
1538)                 if k in service_keys and v is not None
1539)             }
1540) 
Marco Ricci Shift misplaced local function

Marco Ricci authored 4 months ago

1541)             def key_to_phrase(
1542)                 key: str | bytes | bytearray,
1543)             ) -> bytes | bytearray:
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

1545)                     base64.standard_b64decode(key)
1546)                 )
1547) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

1548)             if use_phrase:
1549)                 form = cast(
1550)                     Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1551)                     configuration.get('global', {}).get(
1552)                         'unicode_normalization_form', 'NFC'
1553)                     ),
1554)                 )
1555)                 assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1556)                 _check_for_misleading_passphrase(
1557)                     ('interactive',), {'phrase': phrase}, form=form
1558)                 )
1559) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1560)             # If either --key or --phrase are given, use that setting.
1561)             # Otherwise, if both key and phrase are set in the config,
1562)             # one must be global (ignore it) and one must be
1563)             # service-specific (use that one). Otherwise, if only one of
1564)             # key and phrase is set in the config, use that one.  In all
1565)             # these above cases, set the phrase via
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1575)             elif kwargs.get('phrase'):
1576)                 pass
1577)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

1580)                     'or in configuration'
1581)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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