c527a293dda94e4b9569daf369191fea4e9d01e2
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'
51) KEY_DISPLAY_LENGTH = 30
52) 
53) # Error messages
54) _INVALID_VAULT_CONFIG = 'Invalid vault config'
55) _AGENT_COMMUNICATION_ERROR = 'Error communicating with the SSH agent'
56) _NO_USABLE_KEYS = 'No usable SSH keys were found'
57) _EMPTY_SELECTION = 'Empty selection'
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

352) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

407)     return data
408) 
409) 
Marco Ricci 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 Reformat everything with ruff

Marco Ricci authored 5 months ago

643)         key_prefix = (
644)             key_str
645)             if len(key_str) < KEY_DISPLAY_LENGTH + len('...')
646)             else key_str[:KEY_DISPLAY_LENGTH] + '...'
647)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

723) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

745)     def format_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

832) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

833) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1209)     def check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1557)             if service:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1559)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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