3fe3634dc06a5339cfd939ba01062d4778f4f064
Marco Ricci Change the author e-mail ad...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 2 months ago

175) 
176)     """  # noqa: D301
177)     if not (subcommand_args and subcommand_args[0] == 'vault'):
178)         click.echo(
179)             (
180)                 f'{PROG_NAME}: Deprecation warning: A subcommand will be '
181)                 f'required in v1.0. See --help for available subcommands.'
182)             ),
183)             err=True,
184)         )
185)         click.echo(
186)             f'{PROG_NAME}: Warning: Defaulting to subcommand "vault".',
187)             err=True,
188)         )
189)     else:
190)         subcommand_args = subcommand_args[1:]
191)     return derivepassphrase_export_vault.main(
192)         args=subcommand_args,
193)         prog_name=f'{PROG_NAME} export vault',
194)         standalone_mode=False,
195)     )
196) 
197) 
198) def _load_data(
199)     fmt: Literal['v0.2', 'v0.3', 'storeroom'],
200)     path: str | bytes | os.PathLike[str],
201)     key: bytes,
202) ) -> Any:  # noqa: ANN401
203)     contents: bytes
204)     module: types.ModuleType
205)     match fmt:
206)         case '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)         case 'v0.3':
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)         case 'storeroom':
229)             module = importlib.import_module(
230)                 'derivepassphrase.exporter.storeroom'
231)             )
232)             if module.STUBBED:
233)                 raise ModuleNotFoundError
234)             return module.export_storeroom_data(path, key)
235)         case _:  # pragma: no cover
236)             assert_never(fmt)
237) 
238) 
239) @click.command(
240)     context_settings={'help_option_names': ['-h', '--help']},
241) )
242) @click.option(
243)     '-f',
244)     '--format',
245)     'formats',
246)     metavar='FMT',
247)     multiple=True,
248)     default=('v0.3', 'v0.2', 'storeroom'),
249)     type=click.Choice(['v0.2', 'v0.3', 'storeroom']),
250)     help='try the following storage formats, in order (default: v0.3, v0.2)',
251) )
252) @click.option(
253)     '-k',
254)     '--key',
255)     metavar='K',
256)     help=(
257)         'use K as the storage master key '
258)         '(default: check the `VAULT_KEY`, `LOGNAME`, `USER` or '
259)         '`USERNAME` environment variables)'
260)     ),
261) )
262) @click.argument('path', metavar='PATH', required=True)
263) @click.pass_context
264) def derivepassphrase_export_vault(
265)     ctx: click.Context,
266)     /,
267)     *,
268)     path: str | bytes | os.PathLike[str],
269)     formats: Sequence[Literal['v0.2', 'v0.3', 'storeroom']] = (),
270)     key: str | bytes | None = None,
271) ) -> None:
272)     """Export a vault-native configuration to standard output.
273) 
274)     Read the vault-native configuration at PATH, extract all information
275)     from it, and export the resulting configuration to standard output.
276)     Depending on the configuration format, PATH may either be a file or
277)     a directory.  Supports the vault "v0.2", "v0.3" and "storeroom"
278)     formats.
279) 
280)     If PATH is explicitly given as `VAULT_PATH`, then use the
281)     `VAULT_PATH` environment variable to determine the correct path.
282)     (Use `./VAULT_PATH` or similar to indicate a file/directory actually
283)     named `VAULT_PATH`.)
284) 
285)     """
286)     logging.basicConfig()
287)     if path in {'VAULT_PATH', b'VAULT_PATH'}:
288)         path = exporter.get_vault_path()
289)     if key is None:
290)         key = exporter.get_vault_key()
291)     elif isinstance(key, str):  # pragma: no branch
292)         key = key.encode('utf-8')
293)     for fmt in formats:
294)         try:
295)             config = _load_data(fmt, path, key)
296)         except (
297)             IsADirectoryError,
298)             NotADirectoryError,
299)             ValueError,
300)             RuntimeError,
301)         ):
302)             logging.info('Cannot load as %s: %s', fmt, path)
303)             continue
304)         except OSError as exc:
305)             click.echo(
306)                 (
307)                     f'{PROG_NAME}: ERROR: Cannot parse {path!r} as '
308)                     f'a valid config: {exc.strerror}: {exc.filename!r}'
309)                 ),
310)                 err=True,
311)             )
312)             ctx.exit(1)
313)         except ModuleNotFoundError:
314)             # TODO(the-13th-letter): Use backslash continuation.
315)             # https://github.com/nedbat/coveragepy/issues/1836
316)             msg = f"""
317) {PROG_NAME}: ERROR: Cannot load the required Python module "cryptography".
318) {PROG_NAME}: INFO: pip users: see the "export" extra.
319) """.lstrip('\n')
320)             click.echo(msg, nl=False, err=True)
321)             ctx.exit(1)
322)         else:
323)             if not _types.is_vault_config(config):
324)                 click.echo(
325)                     f'{PROG_NAME}: ERROR: Invalid vault config: {config!r}',
326)                     err=True,
327)                 )
328)                 ctx.exit(1)
329)             click.echo(json.dumps(config, indent=2, sort_keys=True))
330)             break
331)     else:
332)         click.echo(
333)             f'{PROG_NAME}: ERROR: Cannot parse {path!r} as a valid config.',
334)             err=True,
335)         )
336)         ctx.exit(1)
337) 
338) 
339) # Vault
340) # =====
341) 
342) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

354) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

373)     path = os.getenv(PROG_NAME.upper() + '_PATH') or click.get_app_dir(
374)         PROG_NAME, force_posix=True
375)     )
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

376)     match subsystem:
377)         case None:
378)             return path
379)         case 'vault' | 'settings':
380)             filename = f'{subsystem}.json'
381)         case _:  # pragma: no cover
382)             msg = f'Unknown configuration subsystem: {subsystem!r}'
383)             raise AssertionError(msg)
384)     return os.path.join(path, filename)
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

385) 
386) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

392) 
393)     Returns:
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

409)     return data
410) 
411) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

450) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

521) 
522)     """
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

524)     client_context: contextlib.AbstractContextManager[Any]
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

525)     match conn:
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

526)         case ssh_agent.SSHAgentClient():
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

527)             client = conn
528)             client_context = contextlib.nullcontext()
529)         case socket.socket() | None:
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

530)             client = ssh_agent.SSHAgentClient(socket=conn)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

531)             client_context = client
532)         case _:  # pragma: no cover
533)             assert_never(conn)
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

534)             msg = f'invalid connection hint: {conn!r}'
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

535)             raise TypeError(msg)  # noqa: DOC501
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

548) 
549) 
550) def _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

607)     try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

619) 
620) 
621) def _select_ssh_key(
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

709) 
710) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

754) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

765) 
766) class CommandWithHelpGroups(click.Command):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

776)     def format_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

844) 
845) class ConfigurationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

853) 
854) class StorageManagementOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

861)     """
862) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

863) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

864) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

898)     return int_value
899) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

900) 
901) def _validate_length(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

935)     return int_value
936) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

937) 
938) DEFAULT_NOTES_TEMPLATE = """\
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

1216)     for param in ctx.command.params:
1217)         if isinstance(param, click.Option):
1218)             group: type[click.Option]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

1219)             match param:
1220)                 case PasswordGenerationOption():
1221)                     group = PasswordGenerationOption
1222)                 case ConfigurationOption():
1223)                     group = ConfigurationOption
1224)                 case StorageManagementOption():
1225)                     group = StorageManagementOption
1226)                 case OptionGroupOption():
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

1227)                     raise AssertionError(  # noqa: DOC501,TRY003
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1228)                         f'Unknown option group for {param!r}'  # noqa: EM102
1229)                     )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

1240)     def check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

1248)             return
1249)         for other in incompatible:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1311) 
1312)     check_incompatible_options('--phrase', '--key')
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

1317)                     opt, *options_in_group[PasswordGenerationOption]
1318)                 )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

1374)                 notes_value.strip('\n')
1375)             )
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

1390)     elif import_settings:
1391)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1470)             {},
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1472)         )
1473)         if use_key:
1474)             try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

1522)                     f'actual settings'
1523)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1525)             if service:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1527)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

1533)         else:
1534)             if not service:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

1547)                     base64.standard_b64decode(key)
1548)                 )
1549) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

1582)                     'or in configuration'
1583)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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