94068756e896574a397b4717388b02ed661a22a9
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

1) # SPDX-FileCopyrightText: 2024 Marco Ricci <m@the13thletter.info>
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 Add prototype command-line...

Marco Ricci authored 4 months ago

13) import inspect
14) import json
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

15) import os
16) import socket
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

32) import derivepassphrase as dpp
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

34) 
35) if TYPE_CHECKING:
36)     import pathlib
37)     from collections.abc import (
38)         Iterator,
39)         Sequence,
40)     )
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

41) 
42) __author__ = dpp.__author__
43) __version__ = dpp.__version__
44) 
45) __all__ = ('derivepassphrase',)
46) 
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

55) 
56) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

57) def _config_filename() -> str | bytes | pathlib.Path:
58)     """Return the filename of the configuration file.
59) 
60)     The file is currently named `settings.json`, located within the
61)     configuration directory as determined by the `DERIVEPASSPHRASE_PATH`
62)     environment variable, or by [`click.get_app_dir`][] in POSIX
63)     mode.
64) 
65)     """
66)     path: str | bytes | pathlib.Path
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

67)     path = os.getenv(PROG_NAME.upper() + '_PATH') or click.get_app_dir(
68)         PROG_NAME, force_posix=True
69)     )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

70)     return os.path.join(path, 'settings.json')
71) 
72) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

74)     """Load a vault(1)-compatible config from the application directory.
75) 
76)     The filename is obtained via
77)     [`derivepassphrase.cli._config_filename`][].  This must be an
78)     unencrypted JSON file.
79) 
80)     Returns:
81)         The vault settings.  See
82)         [`derivepassphrase.types.VaultConfig`][] for details.
83) 
84)     Raises:
85)         OSError:
86)             There was an OS error accessing the file.
87)         ValueError:
88)             The data loaded from the file is not a vault(1)-compatible
89)             config.
90) 
91)     """
92)     filename = _config_filename()
93)     with open(filename, 'rb') as fileobj:
94)         data = json.load(fileobj)
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

97)     return data
98) 
99) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

102) 
103)     The filename is obtained via
104)     [`derivepassphrase.cli._config_filename`][].  The config will be
105)     stored as an unencrypted JSON file.
106) 
107)     Args:
108)         config:
109)             vault configuration to save.
110) 
111)     Raises:
112)         OSError:
113)             There was an OS error accessing or writing the file.
114)         ValueError:
115)             The data cannot be stored as a vault(1)-compatible config.
116) 
117)     """
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

120)     filename = _config_filename()
Marco Ricci Create the configuration di...

Marco Ricci authored 3 months ago

121)     filedir = os.path.dirname(os.path.abspath(filename))
122)     try:
123)         os.makedirs(filedir, exist_ok=False)
124)     except FileExistsError:
125)         if not os.path.isdir(filedir):
126)             raise
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

128)         json.dump(config, fileobj)
129) 
130) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

134)     """Yield all SSH keys suitable for passphrase derivation.
135) 
136)     Suitable SSH keys are queried from the running SSH agent (see
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

138) 
139)     Args:
140)         conn:
141)             An optional connection hint to the SSH agent; specifically,
142)             an SSH agent client, or a socket connected to an SSH agent.
143) 
144)             If an existing SSH agent client, then this client will be
145)             queried for the SSH keys, and otherwise left intact.
146) 
147)             If a socket, then a one-shot client will be constructed
148)             based on the socket to query the agent, and deconstructed
149)             afterwards.
150) 
151)             If neither are given, then the agent's socket location is
152)             looked up in the `SSH_AUTH_SOCK` environment variable, and
153)             used to construct/deconstruct a one-shot client, as in the
154)             previous case.
155) 
156)     Yields:
157)         :
158)             Every SSH key from the SSH agent that is suitable for
159)             passphrase derivation.
160) 
161)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

162)         KeyError:
163)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
164)             variable was not found.
165)         OSError:
166)             `conn` was a socket or `None`, and there was an error
167)             setting up a socket connection to the agent.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

175) 
176)     """
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

181)             client = conn
182)             client_context = contextlib.nullcontext()
183)         case socket.socket() | None:
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

185)             client_context = client
186)         case _:  # pragma: no cover
187)             assert_never(conn)
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

188)             msg = f'invalid connection hint: {conn!r}'
189)             raise TypeError(msg)
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

190)     with client_context:
191)         try:
192)             all_key_comment_pairs = list(client.list_keys())
193)         except EOFError as e:  # pragma: no cover
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

202) 
203) 
204) def _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

207)     single_choice_prompt: str = 'Confirm this choice?',
208) ) -> int:
209)     """Prompt user for a choice among the given items.
210) 
211)     Print the heading, if any, then present the items to the user.  If
212)     there are multiple items, prompt the user for a selection, validate
213)     the choice, then return the list index of the selected item.  If
214)     there is only a single item, request confirmation for that item
215)     instead, and return the correct index.
216) 
217)     Args:
218)         heading:
219)             A heading for the list of items, to print immediately
220)             before.  Defaults to a reasonable standard heading.  If
221)             explicitly empty, print no heading.
222)         single_choice_prompt:
223)             The confirmation prompt if there is only a single possible
224)             choice.  Defaults to a reasonable standard prompt.
225) 
226)     Returns:
227)         An index into the items sequence, indicating the user's
228)         selection.
229) 
230)     Raises:
231)         IndexError:
232)             The user made an invalid or empty selection, or requested an
233)             abort.
234) 
235)     """
236)     n = len(items)
237)     if heading:
238)         click.echo(click.style(heading, bold=True))
239)     for i, x in enumerate(items, start=1):
240)         click.echo(click.style(f'[{i}]', bold=True), nl=False)
241)         click.echo(' ', nl=False)
242)         click.echo(x)
243)     if n > 1:
244)         choices = click.Choice([''] + [str(i) for i in range(1, n + 1)])
245)         choice = click.prompt(
246)             f'Your selection? (1-{n}, leave empty to abort)',
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

247)             err=True,
248)             type=choices,
249)             show_choices=False,
250)             show_default=False,
251)             default='',
252)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

256)     prompt_suffix = (
257)         ' ' if single_choice_prompt.endswith(tuple('?.!')) else ': '
258)     )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

259)     try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

260)         click.confirm(
261)             single_choice_prompt,
262)             prompt_suffix=prompt_suffix,
263)             err=True,
264)             abort=True,
265)             default=False,
266)             show_default=False,
267)         )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

268)     except click.Abort:
269)         raise IndexError(_EMPTY_SELECTION) from None
270)     return 0
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

271) 
272) 
273) def _select_ssh_key(
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

275) ) -> bytes | bytearray:
276)     """Interactively select an SSH key for passphrase derivation.
277) 
278)     Suitable SSH keys are queried from the running SSH agent (see
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

279)     [`ssh_agent.SSHAgentClient.list_keys`][]), then the user is
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

280)     prompted interactively (see [`click.prompt`][]) for a selection.
281) 
282)     Args:
283)         conn:
284)             An optional connection hint to the SSH agent; specifically,
285)             an SSH agent client, or a socket connected to an SSH agent.
286) 
287)             If an existing SSH agent client, then this client will be
288)             queried for the SSH keys, and otherwise left intact.
289) 
290)             If a socket, then a one-shot client will be constructed
291)             based on the socket to query the agent, and deconstructed
292)             afterwards.
293) 
294)             If neither are given, then the agent's socket location is
295)             looked up in the `SSH_AUTH_SOCK` environment variable, and
296)             used to construct/deconstruct a one-shot client, as in the
297)             previous case.
298) 
299)     Returns:
300)         The selected SSH key.
301) 
302)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

303)         KeyError:
304)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
305)             variable was not found.
306)         OSError:
307)             `conn` was a socket or `None`, and there was an error
308)             setting up a socket connection to the agent.
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

309)         IndexError:
310)             The user made an invalid or empty selection, or requested an
311)             abort.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

319)     """
320)     suitable_keys = list(_get_suitable_ssh_keys(conn))
321)     key_listing: list[str] = []
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

326)         key_prefix = (
327)             key_str
328)             if len(key_str) < KEY_DISPLAY_LENGTH + len('...')
329)             else key_str[:KEY_DISPLAY_LENGTH] + '...'
330)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

334)         key_listing,
335)         heading='Suitable SSH keys:',
336)         single_choice_prompt='Use this key?',
337)     )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

338)     return suitable_keys[choice].key
339) 
340) 
341) def _prompt_for_passphrase() -> str:
342)     """Interactively prompt for the passphrase.
343) 
344)     Calls [`click.prompt`][] internally.  Moved into a separate function
345)     mainly for testing/mocking purposes.
346) 
347)     Returns:
348)         The user input.
349) 
350)     """
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 3 months ago

351)     return cast(
352)         str,
353)         click.prompt(
354)             'Passphrase',
355)             default='',
356)             hide_input=True,
357)             show_default=False,
358)             err=True,
359)         ),
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

361) 
362) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

363) def _check_for_misleading_passphrase(
364)     key: tuple[str, ...],
365)     value: dict[str, Any],
366)     *,
367)     form: Literal['NFC', 'NFD', 'NFKC', 'NFKD'] = 'NFC',
368) ) -> None:
369)     def is_json_identifier(x: str) -> bool:
370)         return not x.startswith(tuple('0123456789')) and not any(
371)             c.lower() not in set('0123456789abcdefghijklmnopqrstuvwxyz_')
372)             for c in x
373)         )
374) 
375)     if 'phrase' in value:
376)         phrase = value['phrase']
377)         if not unicodedata.is_normalized(form, phrase):
378)             key_path = '.'.join(
379)                 x if is_json_identifier(x) else repr(x) for x in key
380)             )
381)             click.echo(
382)                 (
383)                     f'{PROG_NAME}: Warning: the {key_path} passphrase '
384)                     f'is not {form}-normalized. Make sure to double-check '
385)                     f'this is really the passphrase you want.'
386)                 ),
387)                 err=True,
388)             )
389) 
390) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

392)     """A [`click.Option`][] with an associated group name and group epilog.
393) 
394)     Used by [`derivepassphrase.cli.CommandWithHelpGroups`][] to print
395)     help sections.  Each subclass contains its own group name and
396)     epilog.
397) 
398)     Attributes:
399)         option_group_name:
400)             The name of the option group.  Used as a heading on the help
401)             text for options in this section.
402)         epilog:
403)             An epilog to print after listing the options in this
404)             section.
405) 
406)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

407) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

408)     option_group_name: str = ''
409)     epilog: str = ''
410) 
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 3 months ago

411)     def __init__(self, *args: Any, **kwargs: Any) -> None:
412)         if self.__class__ == __class__:  # type: ignore[name-defined]
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

416) 
417) class CommandWithHelpGroups(click.Command):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

418)     """A [`click.Command`][] with support for help/option groups.
419) 
420)     Inspired by [a comment on `pallets/click#373`][CLICK_ISSUE], and
421)     further modified to support group epilogs.
422) 
423)     [CLICK_ISSUE]: https://github.com/pallets/click/issues/373#issuecomment-515293746
424) 
425)     """
426) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

427)     def format_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

428)         self,
429)         ctx: click.Context,
430)         formatter: click.HelpFormatter,
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

434)         This is a callback for [`click.Command.get_help`][] that
435)         implements the `--help` listing, by calling appropriate methods
436)         of the `formatter`.  We list all options (like the base
437)         implementation), but grouped into sections according to the
438)         concrete [`click.Option`][] subclass being used.  If the option
439)         is an instance of some subclass `X` of
440)         [`derivepassphrase.cli.OptionGroupOption`][], then the section
441)         heading and the epilog are taken from `X.option_group_name` and
442)         `X.epilog`; otherwise, the section heading is "Options" (or
443)         "Other options" if there are other option groups) and the epilog
444)         is empty.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

445) 
446)         Args:
447)             ctx:
448)                 The click context.
449)             formatter:
450)                 The formatter for the `--help` listing.
451) 
Marco Ricci Add minor documentation rew...

Marco Ricci authored 4 months ago

452)         Returns:
453)             Nothing.  Output is generated by calling appropriate methods
454)             on `formatter` instead.
455) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

456)         """
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

457)         help_records: dict[str, list[tuple[str, str]]] = {}
458)         epilogs: dict[str, str] = {}
459)         params = self.params[:]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

460)         if (  # pragma: no branch
461)             (help_opt := self.get_help_option(ctx)) is not None
462)             and help_opt not in params
463)         ):
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

464)             params.append(help_opt)
465)         for param in params:
466)             rec = param.get_help_record(ctx)
467)             if rec is not None:
468)                 if isinstance(param, OptionGroupOption):
469)                     group_name = param.option_group_name
470)                     epilogs.setdefault(group_name, param.epilog)
471)                 else:
472)                     group_name = ''
473)                 help_records.setdefault(group_name, []).append(rec)
474)         default_group = help_records.pop('')
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

475)         default_group_name = (
476)             'Other Options' if len(default_group) > 1 else 'Options'
477)         )
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

478)         help_records[default_group_name] = default_group
479)         for group_name, records in help_records.items():
480)             with formatter.section(group_name):
481)                 formatter.write_dl(records)
482)             epilog = inspect.cleandoc(epilogs.get(group_name, ''))
483)             if epilog:
484)                 formatter.write_paragraph()
485)                 with formatter.indentation():
486)                     formatter.write_text(epilog)
487) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

499) 
500) class ConfigurationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

508) 
509) class StorageManagementOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

516)     """
517) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

518) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

519) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

520)     ctx: click.Context,
521)     param: click.Parameter,
522)     value: Any,
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

523) ) -> int | None:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

524)     """Check that the occurrence constraint is valid (int, 0 or larger)."""
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

527)     if value is None:
528)         return value
529)     if isinstance(value, int):
530)         int_value = value
531)     else:
532)         try:
533)             int_value = int(value, 10)
534)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

540)     return int_value
541) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

542) 
543) def _validate_length(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

544)     ctx: click.Context,
545)     param: click.Parameter,
546)     value: Any,
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

547) ) -> int | None:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

548)     """Check that the length is valid (int, 1 or larger)."""
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

551)     if value is None:
552)         return value
553)     if isinstance(value, int):
554)         int_value = value
555)     else:
556)         try:
557)             int_value = int(value, 10)
558)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

564)     return int_value
565) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

566) 
567) DEFAULT_NOTES_TEMPLATE = """\
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

568) # Enter notes below the line with the cut mark (ASCII scissors and
569) # dashes).  Lines above the cut mark (such as this one) will be ignored.
570) #
571) # If you wish to clear the notes, leave everything beyond the cut mark
572) # blank.  However, if you leave the *entire* file blank, also removing
573) # the cut mark, then the edit is aborted, and the old notes contents are
574) # retained.
575) #
576) # - - - - - >8 - - - - - >8 - - - - - >8 - - - - - >8 - - - - -
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

578) DEFAULT_NOTES_MARKER = '# - - - - - >8 - - - - -'
579) 
580) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

581) @click.command(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

590) 
591)         Configuration is stored in a directory according to the
592)         DERIVEPASSPHRASE_PATH variable, which defaults to
593)         `~/.derivepassphrase` on UNIX-like systems and
594)         `C:\Users\<user>\AppData\Roaming\Derivepassphrase` on Windows.
595)         The configuration is NOT encrypted, and you are STRONGLY
596)         discouraged from using a stored passphrase.
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

597)     """,
598) )
599) @click.option(
600)     '-p',
601)     '--phrase',
602)     'use_phrase',
603)     is_flag=True,
604)     help='prompts you for your passphrase',
605)     cls=PasswordGenerationOption,
606) )
607) @click.option(
608)     '-k',
609)     '--key',
610)     'use_key',
611)     is_flag=True,
612)     help='uses your SSH private key to generate passwords',
613)     cls=PasswordGenerationOption,
614) )
615) @click.option(
616)     '-l',
617)     '--length',
618)     metavar='NUMBER',
619)     callback=_validate_length,
620)     help='emits password of length NUMBER',
621)     cls=PasswordGenerationOption,
622) )
623) @click.option(
624)     '-r',
625)     '--repeat',
626)     metavar='NUMBER',
627)     callback=_validate_occurrence_constraint,
628)     help='allows maximum of NUMBER repeated adjacent chars',
629)     cls=PasswordGenerationOption,
630) )
631) @click.option(
632)     '--lower',
633)     metavar='NUMBER',
634)     callback=_validate_occurrence_constraint,
635)     help='includes at least NUMBER lowercase letters',
636)     cls=PasswordGenerationOption,
637) )
638) @click.option(
639)     '--upper',
640)     metavar='NUMBER',
641)     callback=_validate_occurrence_constraint,
642)     help='includes at least NUMBER uppercase letters',
643)     cls=PasswordGenerationOption,
644) )
645) @click.option(
646)     '--number',
647)     metavar='NUMBER',
648)     callback=_validate_occurrence_constraint,
649)     help='includes at least NUMBER digits',
650)     cls=PasswordGenerationOption,
651) )
652) @click.option(
653)     '--space',
654)     metavar='NUMBER',
655)     callback=_validate_occurrence_constraint,
656)     help='includes at least NUMBER spaces',
657)     cls=PasswordGenerationOption,
658) )
659) @click.option(
660)     '--dash',
661)     metavar='NUMBER',
662)     callback=_validate_occurrence_constraint,
663)     help='includes at least NUMBER "-" or "_"',
664)     cls=PasswordGenerationOption,
665) )
666) @click.option(
667)     '--symbol',
668)     metavar='NUMBER',
669)     callback=_validate_occurrence_constraint,
670)     help='includes at least NUMBER symbol chars',
671)     cls=PasswordGenerationOption,
672) )
673) @click.option(
674)     '-n',
675)     '--notes',
676)     'edit_notes',
677)     is_flag=True,
678)     help='spawn an editor to edit notes for SERVICE',
679)     cls=ConfigurationOption,
680) )
681) @click.option(
682)     '-c',
683)     '--config',
684)     'store_config_only',
685)     is_flag=True,
686)     help='saves the given settings for SERVICE or global',
687)     cls=ConfigurationOption,
688) )
689) @click.option(
690)     '-x',
691)     '--delete',
692)     'delete_service_settings',
693)     is_flag=True,
694)     help='deletes settings for SERVICE',
695)     cls=ConfigurationOption,
696) )
697) @click.option(
698)     '--delete-globals',
699)     is_flag=True,
700)     help='deletes the global shared settings',
701)     cls=ConfigurationOption,
702) )
703) @click.option(
704)     '-X',
705)     '--clear',
706)     'clear_all_settings',
707)     is_flag=True,
708)     help='deletes all settings',
709)     cls=ConfigurationOption,
710) )
711) @click.option(
712)     '-e',
713)     '--export',
714)     'export_settings',
715)     metavar='PATH',
716)     type=click.Path(file_okay=True, allow_dash=True, exists=False),
717)     help='export all saved settings into file PATH',
718)     cls=StorageManagementOption,
719) )
720) @click.option(
721)     '-i',
722)     '--import',
723)     'import_settings',
724)     metavar='PATH',
725)     type=click.Path(file_okay=True, allow_dash=True, exists=False),
726)     help='import saved settings from file PATH',
727)     cls=StorageManagementOption,
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

730) @click.argument('service', required=False)
731) @click.pass_context
732) def derivepassphrase(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

733)     ctx: click.Context,
734)     /,
735)     *,
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

736)     service: str | None = None,
737)     use_phrase: bool = False,
738)     use_key: bool = False,
739)     length: int | None = None,
740)     repeat: int | None = None,
741)     lower: int | None = None,
742)     upper: int | None = None,
743)     number: int | None = None,
744)     space: int | None = None,
745)     dash: int | None = None,
746)     symbol: int | None = None,
747)     edit_notes: bool = False,
748)     store_config_only: bool = False,
749)     delete_service_settings: bool = False,
750)     delete_globals: bool = False,
751)     clear_all_settings: bool = False,
752)     export_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
753)     import_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

754) ) -> None:
755)     """Derive a strong passphrase, deterministically, from a master secret.
756) 
Marco Ricci Fill out README and documen...

Marco Ricci authored 4 months ago

757)     Using a master passphrase or a master SSH key, derive a passphrase
758)     for SERVICE, subject to length, character and character repetition
759)     constraints.  The derivation is cryptographically strong, meaning
760)     that even if a single passphrase is compromised, guessing the master
761)     passphrase or a different service's passphrase is computationally
762)     infeasible.  The derivation is also deterministic, given the same
763)     inputs, thus the resulting passphrase need not be stored explicitly.
764)     The service name and constraints themselves also need not be kept
765)     secret; the latter are usually stored in a world-readable file.
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

775) 
776)     [CLICK]: https://click.palletsprojects.com/
777) 
778)     Parameters:
779)         ctx (click.Context):
780)             The `click` context.
781) 
782)     Other Parameters:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

809)         space:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

810)             Command-line argument `--number`.  Same as `lower`, but for
811)             the space character.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

813)             Command-line argument `--number`.  Same as `lower`, but for
814)             the hyphen-minus and underscore characters.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

815)         symbol:
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

816)             Command-line argument `--number`.  Same as `lower`, but for
817)             all other ASCII printable characters (except backquote).
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

835)         export_settings:
836)             Command-line argument `-e`/`--export`.  If a file object,
837)             then it must be open for writing and accept `str` inputs.
838)             Otherwise, a filename to open for writing.  Using `-` for
839)             standard output is supported.
840)         import_settings:
841)             Command-line argument `-i`/`--import`.  If a file object, it
842)             must be open for reading and yield `str` values.  Otherwise,
843)             a filename to open for reading.  Using `-` for standard
844)             input is supported.
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

845) 
846)     """
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

853)             match param:
854)                 case PasswordGenerationOption():
855)                     group = PasswordGenerationOption
856)                 case ConfigurationOption():
857)                     group = ConfigurationOption
858)                 case StorageManagementOption():
859)                     group = StorageManagementOption
860)                 case OptionGroupOption():
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

861)                     raise AssertionError(  # noqa: TRY003
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

864)                 case _:
865)                     group = click.Option
866)             options_in_group.setdefault(group, []).append(param)
867)         params_by_str[param.human_readable_name] = param
868)         for name in param.opts + param.secondary_opts:
869)             params_by_str[name] = param
870) 
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

874)     def check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

878)         if isinstance(param, str):
879)             param = params_by_str[param]
880)         assert isinstance(param, click.Parameter)
881)         if not is_param_set(param):
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

882)             return
883)         for other in incompatible:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

886)             assert isinstance(other, click.Parameter)
887)             if other != param and is_param_set(other):
888)                 opt_str = param.opts[0]
889)                 other_str = other.opts[0]
890)                 raise click.BadOptionUsage(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

894)     def err(msg: str) -> NoReturn:
895)         click.echo(f'{PROG_NAME}: {msg}', err=True)
896)         ctx.exit(1)
897) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

899)         try:
900)             return _load_config()
901)         except FileNotFoundError:
902)             return {'services': {}}
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

906)             err(f'Cannot load config: {e}')
907) 
908)     def put_config(config: _types.VaultConfig, /) -> None:
909)         try:
910)             _save_config(config)
Marco Ricci Document and handle other e...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

917) 
918)     check_incompatible_options('--phrase', '--key')
Marco Ricci Add prototype command-line...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

923)                     opt, *options_in_group[PasswordGenerationOption]
924)                 )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

929)                 opt,
930)                 *options_in_group[ConfigurationOption],
931)                 *options_in_group[StorageManagementOption],
932)             )
933)     sv_options = options_in_group[PasswordGenerationOption] + [
934)         params_by_str['--notes'],
935)         params_by_str['--delete'],
936)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

937)     sv_options.remove(params_by_str['--key'])
938)     sv_options.remove(params_by_str['--phrase'])
939)     for param in sv_options:
940)         if is_param_set(param) and not service:
941)             opt_str = param.opts[0]
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

942)             msg = f'{opt_str} requires a SERVICE'
943)             raise click.UsageError(msg)
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

951)     no_sv_options = [
952)         params_by_str['--delete-globals'],
953)         params_by_str['--clear'],
954)         *options_in_group[StorageManagementOption],
955)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

961) 
962)     if edit_notes:
963)         assert service is not None
964)         configuration = get_config()
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

968)         notes_value = click.edit(text=text)
969)         if notes_value is not None:
970)             notes_lines = collections.deque(notes_value.splitlines(True))
971)             while notes_lines:
972)                 line = notes_lines.popleft()
973)                 if line.startswith(DEFAULT_NOTES_MARKER):
974)                     notes_value = ''.join(notes_lines)
975)                     break
976)             else:
977)                 if not notes_value.strip():
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

980)                 notes_value.strip('\n')
981)             )
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

983)     elif delete_service_settings:
984)         assert service is not None
985)         configuration = get_config()
986)         if service in configuration['services']:
987)             del configuration['services'][service]
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

989)     elif delete_globals:
990)         configuration = get_config()
991)         if 'global' in configuration:
992)             del configuration['global']
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

996)     elif import_settings:
997)         try:
998)             # TODO: keep track of auto-close; try os.dup if feasible
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

999)             infile = (
1000)                 cast(TextIO, import_settings)
1001)                 if hasattr(import_settings, 'close')
1002)                 else click.open_file(os.fspath(import_settings), 'rt')
1003)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1004)             with infile:
1005)                 maybe_config = json.load(infile)
1006)         except json.JSONDecodeError as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

1011)             form = cast(
1012)                 Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1013)                 maybe_config.get('global', {}).get(
1014)                     'unicode_normalization_form', 'NFC'
1015)                 ),
1016)             )
1017)             assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1018)             _check_for_misleading_passphrase(
1019)                 ('global',),
1020)                 cast(dict[str, Any], maybe_config.get('global', {})),
1021)                 form=form,
1022)             )
1023)             for key, value in maybe_config['services'].items():
1024)                 _check_for_misleading_passphrase(
1025)                     ('services', key),
1026)                     cast(dict[str, Any], value),
1027)                     form=form,
1028)                 )
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

1032)     elif export_settings:
1033)         configuration = get_config()
1034)         try:
1035)             # TODO: keep track of auto-close; try os.dup if feasible
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1036)             outfile = (
1037)                 cast(TextIO, export_settings)
1038)                 if hasattr(export_settings, 'close')
1039)                 else click.open_file(os.fspath(export_settings), 'wt')
1040)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1041)             with outfile:
1042)                 json.dump(configuration, outfile)
1043)         except OSError as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

1052)         service_keys = {
1053)             'key',
1054)             'phrase',
1055)             'length',
1056)             'repeat',
1057)             'lower',
1058)             'upper',
1059)             'number',
1060)             'space',
1061)             'dash',
1062)             'symbol',
1063)         }
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

1065)             {
1066)                 k: v
1067)                 for k, v in locals().items()
1068)                 if k in service_keys and v is not None
1069)             },
1070)             cast(
1071)                 dict[str, Any],
1072)                 configuration['services'].get(service or '', {}),
1073)             ),
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1074)             {},
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1076)         )
1077)         if use_key:
1078)             try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1079)                 key = base64.standard_b64encode(_select_ssh_key()).decode(
1080)                     'ASCII'
1081)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

1086)             except OSError as e:
1087)                 err(
1088)                     f'Cannot connect to SSH agent: {e.strerror}: '
1089)                     f'{e.filename!r}'
1090)                 )
Marco Ricci Add a specific error class...

Marco Ricci authored 2 months ago

1091)             except (
1092)                 LookupError,
1093)                 RuntimeError,
1094)                 ssh_agent.SSHAgentFailedError,
1095)             ) as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

1097)         elif use_phrase:
1098)             maybe_phrase = _prompt_for_passphrase()
1099)             if not maybe_phrase:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

1101)             else:
1102)                 phrase = maybe_phrase
1103)         if store_config_only:
1104)             view: collections.ChainMap[str, Any]
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

1105)             view = (
1106)                 collections.ChainMap(*settings.maps[:2])
1107)                 if service
1108)                 else settings.parents.parents
1109)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1110)             if use_key:
1111)                 view['key'] = key
1112)                 for m in view.maps:
1113)                     m.pop('phrase', '')
1114)             elif use_phrase:
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

1115)                 _check_for_misleading_passphrase(
1116)                     ('services', service) if service else ('global',),
1117)                     {'phrase': phrase},
1118)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

1126)                     f'actual settings'
1127)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1129)             if service:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1131)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

1137)         else:
1138)             if not service:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

1141)             kwargs: dict[str, Any] = {
1142)                 k: v
1143)                 for k, v in settings.items()
1144)                 if k in service_keys and v is not None
1145)             }
1146) 
Marco Ricci Shift misplaced local function

Marco Ricci authored 3 months ago

1147)             def key_to_phrase(
1148)                 key: str | bytes | bytearray,
1149)             ) -> bytes | bytearray:
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

1151)                     base64.standard_b64decode(key)
1152)                 )
1153) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 2 months ago

1154)             if use_phrase:
1155)                 form = cast(
1156)                     Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1157)                     configuration.get('global', {}).get(
1158)                         'unicode_normalization_form', 'NFC'
1159)                     ),
1160)                 )
1161)                 assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1162)                 _check_for_misleading_passphrase(
1163)                     ('interactive',), {'phrase': phrase}, form=form
1164)                 )
1165) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 4 months ago

1166)             # If either --key or --phrase are given, use that setting.
1167)             # Otherwise, if both key and phrase are set in the config,
1168)             # one must be global (ignore it) and one must be
1169)             # service-specific (use that one). Otherwise, if only one of
1170)             # key and phrase is set in the config, use that one.  In all
1171)             # these above cases, set the phrase via
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1181)             elif kwargs.get('phrase'):
1182)                 pass
1183)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

1186)                     'or in configuration'
1187)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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