29b26ee3335a21a4e5ef5760cc8b705456d8f78d
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
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

11) import copy
Marco Ricci Signal and list falsy value...

Marco Ricci authored 2 months ago

12) import enum
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
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

35) 
36) if TYPE_CHECKING:
37)     import pathlib
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

38)     import socket
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'
Marco Ricci Make suitable SSH key listi...

Marco Ricci authored 3 weeks ago

51) KEY_DISPLAY_LENGTH = 50
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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 Permit one flaky test and f...

Marco Ricci authored 2 months ago

410) def _migrate_and_load_old_config() -> tuple[
411)     _types.VaultConfig, OSError | None
412) ]:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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:
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

486)             An optional connection hint to the SSH agent.  See
487)             [`ssh_agent.SSHAgentClient.ensure_agent_subcontext`][].
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

488) 
489)     Yields:
Marco Ricci Convert old syntax for Yiel...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

492) 
493)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

494)         KeyError:
495)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
496)             variable was not found.
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

511) 
512)     """
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

513)     with ssh_agent.SSHAgentClient.ensure_agent_subcontext(conn) as client:
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

514)         try:
515)             all_key_comment_pairs = list(client.list_keys())
516)         except EOFError as e:  # pragma: no cover
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

525) 
526) 
527) def _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

530)     single_choice_prompt: str = 'Confirm this choice?',
531) ) -> int:
532)     """Prompt user for a choice among the given items.
533) 
534)     Print the heading, if any, then present the items to the user.  If
535)     there are multiple items, prompt the user for a selection, validate
536)     the choice, then return the list index of the selected item.  If
537)     there is only a single item, request confirmation for that item
538)     instead, and return the correct index.
539) 
540)     Args:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

543)         heading:
544)             A heading for the list of items, to print immediately
545)             before.  Defaults to a reasonable standard heading.  If
546)             explicitly empty, print no heading.
547)         single_choice_prompt:
548)             The confirmation prompt if there is only a single possible
549)             choice.  Defaults to a reasonable standard prompt.
550) 
551)     Returns:
552)         An index into the items sequence, indicating the user's
553)         selection.
554) 
555)     Raises:
556)         IndexError:
557)             The user made an invalid or empty selection, or requested an
558)             abort.
559) 
560)     """
561)     n = len(items)
562)     if heading:
563)         click.echo(click.style(heading, bold=True))
564)     for i, x in enumerate(items, start=1):
565)         click.echo(click.style(f'[{i}]', bold=True), nl=False)
566)         click.echo(' ', nl=False)
567)         click.echo(x)
568)     if n > 1:
569)         choices = click.Choice([''] + [str(i) for i in range(1, n + 1)])
570)         choice = click.prompt(
571)             f'Your selection? (1-{n}, leave empty to abort)',
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

572)             err=True,
573)             type=choices,
574)             show_choices=False,
575)             show_default=False,
576)             default='',
577)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

581)     prompt_suffix = (
582)         ' ' if single_choice_prompt.endswith(tuple('?.!')) else ': '
583)     )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

584)     try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

585)         click.confirm(
586)             single_choice_prompt,
587)             prompt_suffix=prompt_suffix,
588)             err=True,
589)             abort=True,
590)             default=False,
591)             show_default=False,
592)         )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

593)     except click.Abort:
594)         raise IndexError(_EMPTY_SELECTION) from None
595)     return 0
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

596) 
597) 
598) def _select_ssh_key(
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

606) 
607)     Args:
608)         conn:
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

609)             An optional connection hint to the SSH agent.  See
610)             [`ssh_agent.SSHAgentClient.ensure_agent_subcontext`][].
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

611) 
612)     Returns:
613)         The selected SSH key.
614) 
615)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

616)         KeyError:
617)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
618)             variable was not found.
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

626)         IndexError:
627)             The user made an invalid or empty selection, or requested an
628)             abort.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

636)     """
637)     suitable_keys = list(_get_suitable_ssh_keys(conn))
638)     key_listing: list[str] = []
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

640)     for key, comment in suitable_keys:
641)         keytype = unstring_prefix(key)[0].decode('ASCII')
642)         key_str = base64.standard_b64encode(key).decode('ASCII')
Marco Ricci Make suitable SSH key listi...

Marco Ricci authored 3 weeks ago

643)         remaining_key_display_length = KEY_DISPLAY_LENGTH - 1 - len(keytype)
644)         key_extract = min(
645)             key_str,
646)             '...' + key_str[-remaining_key_display_length:],
647)             key=len,
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

649)         comment_str = comment.decode('UTF-8', errors='replace')
Marco Ricci Make suitable SSH key listi...

Marco Ricci authored 3 weeks ago

650)         key_listing.append(f'{keytype} {key_extract}  {comment_str}')
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

651)     choice = _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

652)         key_listing,
653)         heading='Suitable SSH keys:',
654)         single_choice_prompt='Use this key?',
655)     )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

656)     return suitable_keys[choice].key
657) 
658) 
659) def _prompt_for_passphrase() -> str:
660)     """Interactively prompt for the passphrase.
661) 
662)     Calls [`click.prompt`][] internally.  Moved into a separate function
663)     mainly for testing/mocking purposes.
664) 
665)     Returns:
666)         The user input.
667) 
668)     """
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

669)     return cast(
670)         str,
671)         click.prompt(
672)             'Passphrase',
673)             default='',
674)             hide_input=True,
675)             show_default=False,
676)             err=True,
677)         ),
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

679) 
680) 
Marco Ricci Signal and list falsy value...

Marco Ricci authored 2 months ago

681) class _ORIGIN(enum.Enum):
682)     INTERACTIVE: str = 'interactive'
683) 
684) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

685) def _check_for_misleading_passphrase(
Marco Ricci Signal and list falsy value...

Marco Ricci authored 2 months ago

686)     key: tuple[str, ...] | _ORIGIN,
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

687)     value: dict[str, Any],
688)     *,
689)     form: Literal['NFC', 'NFD', 'NFKC', 'NFKD'] = 'NFC',
690) ) -> None:
691)     if 'phrase' in value:
692)         phrase = value['phrase']
693)         if not unicodedata.is_normalized(form, phrase):
Marco Ricci Signal and list falsy value...

Marco Ricci authored 2 months ago

694)             formatted_key = (
695)                 key.value
696)                 if isinstance(key, _ORIGIN)
697)                 else _types.json_path(key)
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

698)             )
699)             click.echo(
700)                 (
Marco Ricci Signal and list falsy value...

Marco Ricci authored 2 months ago

701)                     f'{PROG_NAME}: Warning: the {formatted_key} '
702)                     f'passphrase is not {form}-normalized. Make sure to '
703)                     f'double-check this is really the passphrase you want.'
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

704)                 ),
705)                 err=True,
706)             )
707) 
708) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

714) 
715)     Attributes:
716)         option_group_name:
717)             The name of the option group.  Used as a heading on the help
718)             text for options in this section.
719)         epilog:
720)             An epilog to print after listing the options in this
721)             section.
722) 
723)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

724) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

735) 
736) class CommandWithHelpGroups(click.Command):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

737)     """A [`click.Command`][] with support for help/option groups.
738) 
739)     Inspired by [a comment on `pallets/click#373`][CLICK_ISSUE], and
740)     further modified to support group epilogs.
741) 
742)     [CLICK_ISSUE]: https://github.com/pallets/click/issues/373#issuecomment-515293746
743) 
744)     """
745) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

746)     def format_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

747)         self,
748)         ctx: click.Context,
749)         formatter: click.HelpFormatter,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

758)         is an instance of some subclass of [`OptionGroupOption`][], then
759)         the section heading and the epilog are taken from the
760)         [`option_group_name`] [OptionGroupOption.option_group_name] and
761)         [`epilog`] [OptionGroupOption.epilog] attributes; otherwise, the
762)         section heading is "Options" (or "Other options" if there are
763)         other option groups) and the epilog is empty.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

764) 
765)         Args:
766)             ctx:
767)                 The click context.
768)             formatter:
769)                 The formatter for the `--help` listing.
770) 
771)         """
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

772)         help_records: dict[str, list[tuple[str, str]]] = {}
773)         epilogs: dict[str, str] = {}
774)         params = self.params[:]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

775)         if (  # pragma: no branch
776)             (help_opt := self.get_help_option(ctx)) is not None
777)             and help_opt not in params
778)         ):
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

779)             params.append(help_opt)
780)         for param in params:
781)             rec = param.get_help_record(ctx)
782)             if rec is not None:
783)                 if isinstance(param, OptionGroupOption):
784)                     group_name = param.option_group_name
785)                     epilogs.setdefault(group_name, param.epilog)
786)                 else:
787)                     group_name = ''
788)                 help_records.setdefault(group_name, []).append(rec)
789)         default_group = help_records.pop('')
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

790)         default_group_name = (
791)             'Other Options' if len(default_group) > 1 else 'Options'
792)         )
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

793)         help_records[default_group_name] = default_group
794)         for group_name, records in help_records.items():
795)             with formatter.section(group_name):
796)                 formatter.write_dl(records)
797)             epilog = inspect.cleandoc(epilogs.get(group_name, ''))
798)             if epilog:
799)                 formatter.write_paragraph()
800)                 with formatter.indentation():
801)                     formatter.write_text(epilog)
802) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

814) 
815) class ConfigurationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

823) 
824) class StorageManagementOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

833) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

834) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

839)     """Check that the occurrence constraint is valid (int, 0 or larger).
840) 
841)     Args:
842)         ctx: The `click` context.
843)         param: The current command-line parameter.
844)         value: The parameter value to be checked.
845) 
846)     Returns:
847)         The parsed parameter value.
848) 
849)     Raises:
850)         click.BadParameter: The parameter value is invalid.
851) 
852)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

855)     if value is None:
856)         return value
857)     if isinstance(value, int):
858)         int_value = value
859)     else:
860)         try:
861)             int_value = int(value, 10)
862)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

868)     return int_value
869) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

870) 
871) def _validate_length(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

905)     return int_value
906) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

907) 
908) DEFAULT_NOTES_TEMPLATE = """\
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

909) # Enter notes below the line with the cut mark (ASCII scissors and
910) # dashes).  Lines above the cut mark (such as this one) will be ignored.
911) #
912) # If you wish to clear the notes, leave everything beyond the cut mark
913) # blank.  However, if you leave the *entire* file blank, also removing
914) # the cut mark, then the edit is aborted, and the old notes contents are
915) # retained.
916) #
917) # - - - - - >8 - - - - - >8 - - - - - >8 - - - - - >8 - - - - -
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

919) DEFAULT_NOTES_MARKER = '# - - - - - >8 - - - - -'
920) 
921) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

936)     """,
937) )
938) @click.option(
939)     '-p',
940)     '--phrase',
941)     'use_phrase',
942)     is_flag=True,
943)     help='prompts you for your passphrase',
944)     cls=PasswordGenerationOption,
945) )
946) @click.option(
947)     '-k',
948)     '--key',
949)     'use_key',
950)     is_flag=True,
951)     help='uses your SSH private key to generate passwords',
952)     cls=PasswordGenerationOption,
953) )
954) @click.option(
955)     '-l',
956)     '--length',
957)     metavar='NUMBER',
958)     callback=_validate_length,
959)     help='emits password of length NUMBER',
960)     cls=PasswordGenerationOption,
961) )
962) @click.option(
963)     '-r',
964)     '--repeat',
965)     metavar='NUMBER',
966)     callback=_validate_occurrence_constraint,
967)     help='allows maximum of NUMBER repeated adjacent chars',
968)     cls=PasswordGenerationOption,
969) )
970) @click.option(
971)     '--lower',
972)     metavar='NUMBER',
973)     callback=_validate_occurrence_constraint,
974)     help='includes at least NUMBER lowercase letters',
975)     cls=PasswordGenerationOption,
976) )
977) @click.option(
978)     '--upper',
979)     metavar='NUMBER',
980)     callback=_validate_occurrence_constraint,
981)     help='includes at least NUMBER uppercase letters',
982)     cls=PasswordGenerationOption,
983) )
984) @click.option(
985)     '--number',
986)     metavar='NUMBER',
987)     callback=_validate_occurrence_constraint,
988)     help='includes at least NUMBER digits',
989)     cls=PasswordGenerationOption,
990) )
991) @click.option(
992)     '--space',
993)     metavar='NUMBER',
994)     callback=_validate_occurrence_constraint,
995)     help='includes at least NUMBER spaces',
996)     cls=PasswordGenerationOption,
997) )
998) @click.option(
999)     '--dash',
1000)     metavar='NUMBER',
1001)     callback=_validate_occurrence_constraint,
1002)     help='includes at least NUMBER "-" or "_"',
1003)     cls=PasswordGenerationOption,
1004) )
1005) @click.option(
1006)     '--symbol',
1007)     metavar='NUMBER',
1008)     callback=_validate_occurrence_constraint,
1009)     help='includes at least NUMBER symbol chars',
1010)     cls=PasswordGenerationOption,
1011) )
1012) @click.option(
1013)     '-n',
1014)     '--notes',
1015)     'edit_notes',
1016)     is_flag=True,
1017)     help='spawn an editor to edit notes for SERVICE',
1018)     cls=ConfigurationOption,
1019) )
1020) @click.option(
1021)     '-c',
1022)     '--config',
1023)     'store_config_only',
1024)     is_flag=True,
1025)     help='saves the given settings for SERVICE or global',
1026)     cls=ConfigurationOption,
1027) )
1028) @click.option(
1029)     '-x',
1030)     '--delete',
1031)     'delete_service_settings',
1032)     is_flag=True,
1033)     help='deletes settings for SERVICE',
1034)     cls=ConfigurationOption,
1035) )
1036) @click.option(
1037)     '--delete-globals',
1038)     is_flag=True,
1039)     help='deletes the global shared settings',
1040)     cls=ConfigurationOption,
1041) )
1042) @click.option(
1043)     '-X',
1044)     '--clear',
1045)     'clear_all_settings',
1046)     is_flag=True,
1047)     help='deletes all settings',
1048)     cls=ConfigurationOption,
1049) )
1050) @click.option(
1051)     '-e',
1052)     '--export',
1053)     'export_settings',
1054)     metavar='PATH',
1055)     help='export all saved settings into file PATH',
1056)     cls=StorageManagementOption,
1057) )
1058) @click.option(
1059)     '-i',
1060)     '--import',
1061)     'import_settings',
1062)     metavar='PATH',
1063)     help='import saved settings from file PATH',
1064)     cls=StorageManagementOption,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1070)     ctx: click.Context,
1071)     /,
1072)     *,
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1073)     service: str | None = None,
1074)     use_phrase: bool = False,
1075)     use_key: bool = False,
1076)     length: int | None = None,
1077)     repeat: int | None = None,
1078)     lower: int | None = None,
1079)     upper: int | None = None,
1080)     number: int | None = None,
1081)     space: int | None = None,
1082)     dash: int | None = None,
1083)     symbol: int | None = None,
1084)     edit_notes: bool = False,
1085)     store_config_only: bool = False,
1086)     delete_service_settings: bool = False,
1087)     delete_globals: bool = False,
1088)     clear_all_settings: bool = False,
1089)     export_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
1090)     import_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1094)     Using a master passphrase or a master SSH key, derive a passphrase
1095)     for SERVICE, subject to length, character and character repetition
1096)     constraints.  The derivation is cryptographically strong, meaning
1097)     that even if a single passphrase is compromised, guessing the master
1098)     passphrase or a different service's passphrase is computationally
1099)     infeasible.  The derivation is also deterministic, given the same
1100)     inputs, thus the resulting passphrase need not be stored explicitly.
1101)     The service name and constraints themselves also need not be kept
1102)     secret; the latter are usually stored in a world-readable file.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1114) 
1115)     Parameters:
1116)         ctx (click.Context):
1117)             The `click` context.
1118) 
1119)     Other Parameters:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1172)         export_settings:
1173)             Command-line argument `-e`/`--export`.  If a file object,
1174)             then it must be open for writing and accept `str` inputs.
1175)             Otherwise, a filename to open for writing.  Using `-` for
1176)             standard output is supported.
1177)         import_settings:
1178)             Command-line argument `-i`/`--import`.  If a file object, it
1179)             must be open for reading and yield `str` values.  Otherwise,
1180)             a filename to open for reading.  Using `-` for standard
1181)             input is supported.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

1189)             # Use match/case here once Python 3.9 becomes unsupported.
1190)             if isinstance(param, PasswordGenerationOption):
1191)                 group = PasswordGenerationOption
1192)             elif isinstance(param, ConfigurationOption):
1193)                 group = ConfigurationOption
1194)             elif isinstance(param, StorageManagementOption):
1195)                 group = StorageManagementOption
1196)             elif isinstance(param, OptionGroupOption):
1197)                 raise AssertionError(  # noqa: DOC501,TRY003,TRY004
1198)                     f'Unknown option group for {param!r}'  # noqa: EM102
1199)                 )
1200)             else:
1201)                 group = click.Option
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1202)             options_in_group.setdefault(group, []).append(param)
1203)         params_by_str[param.human_readable_name] = param
1204)         for name in param.opts + param.secondary_opts:
1205)             params_by_str[name] = param
1206) 
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1210)     def check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1214)         if isinstance(param, str):
1215)             param = params_by_str[param]
1216)         assert isinstance(param, click.Parameter)
1217)         if not is_param_set(param):
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

1218)             return
1219)         for other in incompatible:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1222)             assert isinstance(other, click.Parameter)
1223)             if other != param and is_param_set(other):
1224)                 opt_str = param.opts[0]
1225)                 other_str = other.opts[0]
1226)                 raise click.BadOptionUsage(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1230)     def err(msg: str) -> NoReturn:
1231)         click.echo(f'{PROG_NAME}: {msg}', err=True)
1232)         ctx.exit(1)
1233) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1235)         try:
1236)             return _load_config()
1237)         except FileNotFoundError:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1238)             try:
1239)                 backup_config, exc = _migrate_and_load_old_config()
1240)             except FileNotFoundError:
1241)                 return {'services': {}}
1242)             old_name = os.path.basename(_config_filename())
1243)             new_name = os.path.basename(_config_filename(subsystem='vault'))
1244)             click.echo(
1245)                 (
1246)                     f'{PROG_NAME}: Using deprecated v0.1-style config file '
1247)                     f'{old_name!r}, instead of v0.2-style {new_name!r}.  '
1248)                     f'Support for v0.1-style config filenames will be '
1249)                     f'removed in v1.0.'
1250)                 ),
1251)                 err=True,
1252)             )
1253)             if isinstance(exc, OSError):
1254)                 click.echo(
1255)                     (
1256)                         f'{PROG_NAME}: Warning: Failed to migrate to '
1257)                         f'{new_name!r}: {exc.strerror}: {exc.filename!r}'
1258)                     ),
1259)                     err=True,
1260)                 )
1261)             else:
1262)                 click.echo(
1263)                     f'{PROG_NAME}: Successfully migrated to {new_name!r}.',
1264)                     err=True,
1265)                 )
1266)             return backup_config
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

1270)             err(f'Cannot load config: {e}')
1271) 
1272)     def put_config(config: _types.VaultConfig, /) -> None:
1273)         try:
1274)             _save_config(config)
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1281) 
1282)     check_incompatible_options('--phrase', '--key')
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1287)                     opt, *options_in_group[PasswordGenerationOption]
1288)                 )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1293)                 opt,
1294)                 *options_in_group[ConfigurationOption],
1295)                 *options_in_group[StorageManagementOption],
1296)             )
Marco Ricci Correctly model vault globa...

Marco Ricci authored 2 months ago

1297)     sv_or_global_options = options_in_group[PasswordGenerationOption]
1298)     for param in sv_or_global_options:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1303)             msg = f'{opt_str} requires a SERVICE or --config'
Marco Ricci Correctly model vault globa...

Marco Ricci authored 2 months ago

1304)             raise click.UsageError(msg)  # noqa: DOC501
1305)     sv_options = [params_by_str['--notes'], params_by_str['--delete']]
1306)     for param in sv_options:
1307)         if is_param_set(param) and not service:
1308)             opt_str = param.opts[0]
1309)             msg = f'{opt_str} requires a SERVICE'
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

1310)             raise click.UsageError(msg)
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1311)     no_sv_options = [
1312)         params_by_str['--delete-globals'],
1313)         params_by_str['--clear'],
1314)         *options_in_group[StorageManagementOption],
1315)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1321) 
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

1322)     if service == '':  # noqa: PLC1901
1323)         click.echo(
1324)             (
1325)                 f'{PROG_NAME}: Warning: An empty SERVICE is not '
1326)                 f'supported by vault(1).  For compatibility, this will be '
1327)                 f'treated as if SERVICE was not supplied, i.e., it will '
1328)                 f'error out, or operate on global settings.'
1329)             ),
1330)             err=True,
1331)         )
1332) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1333)     if edit_notes:
1334)         assert service is not None
1335)         configuration = get_config()
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1342)             while notes_lines:
1343)                 line = notes_lines.popleft()
1344)                 if line.startswith(DEFAULT_NOTES_MARKER):
1345)                     notes_value = ''.join(notes_lines)
1346)                     break
1347)             else:
1348)                 if not notes_value.strip():
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1351)                 notes_value.strip('\n')
1352)             )
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1354)     elif delete_service_settings:
1355)         assert service is not None
1356)         configuration = get_config()
1357)         if service in configuration['services']:
1358)             del configuration['services'][service]
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1360)     elif delete_globals:
1361)         configuration = get_config()
1362)         if 'global' in configuration:
1363)             del configuration['global']
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1367)     elif import_settings:
1368)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1371)             infile = (
1372)                 cast(TextIO, import_settings)
1373)                 if hasattr(import_settings, 'close')
1374)                 else click.open_file(os.fspath(import_settings), 'rt')
1375)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1376)             with infile:
1377)                 maybe_config = json.load(infile)
1378)         except json.JSONDecodeError as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1381)             err(f'Cannot load config: {e.strerror}: {e.filename!r}')
Marco Ricci Signal and list falsy value...

Marco Ricci authored 2 months ago

1382)         cleaned = _types.clean_up_falsy_vault_config_values(maybe_config)
1383)         if not _types.is_vault_config(maybe_config):
1384)             err(f'Cannot load config: {_INVALID_VAULT_CONFIG}')
1385)         assert cleaned is not None
1386)         for step in cleaned:
1387)             # These are never fatal errors, because the semantics of
1388)             # vault upon encountering these settings are ill-specified,
1389)             # but not ill-defined.
1390)             if step.action == 'replace':
1391)                 err_msg = (
1392)                     f'{PROG_NAME}: Warning: Replacing invalid value '
1393)                     f'{json.dumps(step.old_value)} for key '
1394)                     f'{_types.json_path(step.path)} with '
1395)                     f'{json.dumps(step.new_value)}.'
1396)                 )
1397)             else:
1398)                 err_msg = (
1399)                     f'{PROG_NAME}: Warning: Removing ineffective setting '
1400)                     f'{_types.json_path(step.path)} = '
1401)                     f'{json.dumps(step.old_value)}.'
1402)                 )
1403)             click.echo(err_msg, err=True)
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

1404)         if '' in maybe_config['services']:
1405)             err_msg = (
1406)                 f'{PROG_NAME}: Warning: An empty SERVICE is not '
1407)                 f'supported by vault(1), and the empty-string service '
1408)                 f'settings will be inaccessible and ineffective.  '
1409)                 f'To ensure that vault(1) and {PROG_NAME} see the settings, '
1410)                 f'move them into the "global" section.'
1411)             )
1412)             click.echo(err_msg, err=True)
Marco Ricci Signal and list falsy value...

Marco Ricci authored 2 months ago

1413)         form = cast(
1414)             Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1415)             maybe_config.get('global', {}).get(
1416)                 'unicode_normalization_form', 'NFC'
1417)             ),
1418)         )
1419)         assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1420)         _check_for_misleading_passphrase(
1421)             ('global',),
1422)             cast(dict[str, Any], maybe_config.get('global', {})),
1423)             form=form,
1424)         )
1425)         for key, value in maybe_config['services'].items():
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

1426)             _check_for_misleading_passphrase(
Marco Ricci Signal and list falsy value...

Marco Ricci authored 2 months ago

1427)                 ('services', key),
1428)                 cast(dict[str, Any], value),
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

1429)                 form=form,
1430)             )
Marco Ricci Align behavior with vault c...

Marco Ricci authored 2 months ago

1431)         configuration = get_config()
1432)         merged_config: collections.ChainMap[str, Any] = collections.ChainMap(
1433)             {
1434)                 'services': collections.ChainMap(
1435)                     maybe_config['services'],
1436)                     configuration['services'],
1437)                 ),
1438)             },
1439)             {'global': maybe_config['global']}
1440)             if 'global' in maybe_config
1441)             else {},
1442)             {'global': configuration['global']}
1443)             if 'global' in configuration
1444)             else {},
1445)         )
Marco Ricci Fix a typing issue

Marco Ricci authored 1 month ago

1446)         new_config: Any = {
Marco Ricci Align behavior with vault c...

Marco Ricci authored 2 months ago

1447)             k: dict(v) if isinstance(v, collections.ChainMap) else v
1448)             for k, v in sorted(merged_config.items())
1449)         }
1450)         assert _types.is_vault_config(new_config)
1451)         put_config(new_config)
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1452)     elif export_settings:
1453)         configuration = get_config()
1454)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1457)             outfile = (
1458)                 cast(TextIO, export_settings)
1459)                 if hasattr(export_settings, 'close')
1460)                 else click.open_file(os.fspath(export_settings), 'wt')
1461)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1462)             with outfile:
1463)                 json.dump(configuration, outfile)
1464)         except OSError as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1473)         service_keys = {
1474)             'key',
1475)             'phrase',
1476)             'length',
1477)             'repeat',
1478)             'lower',
1479)             'upper',
1480)             'number',
1481)             'space',
1482)             'dash',
1483)             'symbol',
1484)         }
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1486)             {
1487)                 k: v
1488)                 for k, v in locals().items()
1489)                 if k in service_keys and v is not None
1490)             },
1491)             cast(
1492)                 dict[str, Any],
1493)                 configuration['services'].get(service or '', {}),
1494)             ),
1495)             cast(dict[str, Any], configuration.get('global', {})),
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1496)         )
1497)         if use_key:
1498)             try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1499)                 key = base64.standard_b64encode(_select_ssh_key()).decode(
1500)                     'ASCII'
1501)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

1506)             except NotImplementedError:
1507)                 err(
1508)                     'Cannot connect to SSH agent because '
1509)                     'this Python version does not support UNIX domain sockets'
1510)                 )
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

1511)             except OSError as e:
1512)                 err(
1513)                     f'Cannot connect to SSH agent: {e.strerror}: '
1514)                     f'{e.filename!r}'
1515)                 )
Marco Ricci Add a specific error class...

Marco Ricci authored 4 months ago

1516)             except (
1517)                 LookupError,
1518)                 RuntimeError,
1519)                 ssh_agent.SSHAgentFailedError,
1520)             ) as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1522)         elif use_phrase:
1523)             maybe_phrase = _prompt_for_passphrase()
1524)             if not maybe_phrase:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1526)             else:
1527)                 phrase = maybe_phrase
1528)         if store_config_only:
1529)             view: collections.ChainMap[str, Any]
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1530)             view = (
1531)                 collections.ChainMap(*settings.maps[:2])
1532)                 if service
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

1533)                 else collections.ChainMap(settings.maps[0], settings.maps[2])
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1535)             if use_key:
1536)                 view['key'] = key
1537)             elif use_phrase:
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

1538)                 view['phrase'] = phrase
1539)                 settings_type = 'service' if service else 'global'
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

1540)                 _check_for_misleading_passphrase(
1541)                     ('services', service) if service else ('global',),
1542)                     {'phrase': phrase},
1543)                 )
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

1544)                 if 'key' in settings:
1545)                     err_msg = (
1546)                         f'{PROG_NAME}: Warning: Setting a {settings_type} '
1547)                         f'passphrase is ineffective because a key is also '
1548)                         f'set.'
1549)                     )
1550)                     click.echo(err_msg, err=True)
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

1555)                     f'actual settings'
1556)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1558)             if service:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1560)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1566)         else:
1567)             if not service:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

1570)             kwargs: dict[str, Any] = {
1571)                 k: v
1572)                 for k, v in settings.items()
1573)                 if k in service_keys and v is not None
1574)             }
1575) 
Marco Ricci Shift misplaced local function

Marco Ricci authored 4 months ago

1576)             def key_to_phrase(
1577)                 key: str | bytes | bytearray,
1578)             ) -> bytes | bytearray:
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

1580)                     base64.standard_b64decode(key)
1581)                 )
1582) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

1583)             if use_phrase:
1584)                 form = cast(
1585)                     Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1586)                     configuration.get('global', {}).get(
1587)                         'unicode_normalization_form', 'NFC'
1588)                     ),
1589)                 )
1590)                 assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1591)                 _check_for_misleading_passphrase(
Marco Ricci Signal and list falsy value...

Marco Ricci authored 2 months ago

1592)                     _ORIGIN.INTERACTIVE, {'phrase': phrase}, form=form
Marco Ricci Allow all textual strings,...

Marco Ricci authored 3 months ago

1593)                 )
1594) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1595)             # If either --key or --phrase are given, use that setting.
1596)             # Otherwise, if both key and phrase are set in the config,
Marco Ricci Align behavior with vault c...

Marco Ricci authored 2 months ago

1597)             # use the key.  Otherwise, if only one of key and phrase is
1598)             # set in the config, use that one.  In all these above
1599)             # cases, set the phrase via vault.Vault.phrase_from_key if
1600)             # a key is given.  Finally, if nothing is set, error out.
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1601)             if use_key or use_phrase:
Marco Ricci Avoid crashing when overrid...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1605)             elif kwargs.get('phrase'):
1606)                 pass
1607)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

1610)                     'or in configuration'
1611)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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