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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2) #
3) # SPDX-License-Identifier: MIT
4) 
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

5) # ruff: noqa: TRY400
6) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

8) 
9) from __future__ import annotations
10) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

11) import base64
12) import collections
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

14) import enum
Marco Ricci Rewrite incompatible option...

Marco Ricci authored 3 weeks ago

15) import functools
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

17) import inspect
18) import json
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

20) import os
Marco Ricci Support exporting the `vaul...

Marco Ricci authored 2 weeks ago

21) import shlex
Marco Ricci Introduce a central user co...

Marco Ricci authored 3 weeks ago

22) import sys
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

23) import unicodedata
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

24) import warnings
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

25) from typing import (
26)     TYPE_CHECKING,
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

27)     Callable,
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

30)     TextIO,
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

31)     TypeVar,
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

32)     cast,
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

34) 
35) import click
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

36) from typing_extensions import (
37)     Any,
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

38)     ParamSpec,
39)     Self,
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

40)     assert_never,
41) )
42) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

45) 
Marco Ricci Introduce a central user co...

Marco Ricci authored 3 weeks ago

46) if sys.version_info >= (3, 11):
47)     import tomllib
48) else:
49)     import tomli as tomllib
50) 
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

51) if TYPE_CHECKING:
52)     import pathlib
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

53)     import socket
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

55)     from collections.abc import (
56)         Iterator,
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

57)         MutableSequence,
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

58)         Sequence,
59)     )
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

60) 
61) __author__ = dpp.__author__
62) __version__ = dpp.__version__
63) 
64) __all__ = ('derivepassphrase',)
65) 
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

66) PROG_NAME = 'derivepassphrase'
Marco Ricci Make suitable SSH key listi...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

68) 
69) # Error messages
70) _INVALID_VAULT_CONFIG = 'Invalid vault config'
71) _AGENT_COMMUNICATION_ERROR = 'Error communicating with the SSH agent'
72) _NO_USABLE_KEYS = 'No usable SSH keys were found'
73) _EMPTY_SELECTION = 'Empty selection'
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

74) 
75) 
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

76) # Logging
77) # =======
78) 
79) 
80) class ClickEchoStderrHandler(logging.Handler):
81)     """A [`logging.Handler`][] for `click` applications.
82) 
83)     Outputs log messages to [`sys.stderr`][] via [`click.echo`][].
84) 
85)     """
86) 
87)     def emit(self, record: logging.LogRecord) -> None:
88)         """Emit a log record.
89) 
90)         Format the log record, then emit it via [`click.echo`][] to
91)         [`sys.stderr`][].
92) 
93)         """
94)         click.echo(self.format(record), err=True)
95) 
96) 
97) class CLIofPackageFormatter(logging.Formatter):
98)     """A [`logging.LogRecord`][] formatter for the CLI of a Python package.
99) 
100)     Assuming a package `PKG` and loggers within the same hierarchy
101)     `PKG`, format all log records from that hierarchy for proper user
102)     feedback on the console.  Intended for use with [`click`][CLICK] and
103)     when `PKG` provides a command-line tool `PKG` and when logs from
104)     that package should show up as output of the command-line tool.
105) 
106)     Essentially, this prepends certain short strings to the log message
107)     lines to make them readable as standard error output.
108) 
109)     Because this log output is intended to be displayed on standard
110)     error as high-level diagnostic output, you are strongly discouraged
111)     from changing the output format to include more tokens besides the
112)     log message.  Use a dedicated log file handler instead, without this
113)     formatter.
114) 
115)     [CLICK]: https://pypi.org/projects/click/
116) 
117)     """
118) 
119)     def __init__(
120)         self,
121)         *,
122)         prog_name: str = PROG_NAME,
123)         package_name: str | None = None,
124)     ) -> None:
125)         self.prog_name = prog_name
126)         self.package_name = (
127)             package_name
128)             if package_name is not None
129)             else prog_name.lower().replace(' ', '_').replace('-', '_')
130)         )
131) 
132)     def format(self, record: logging.LogRecord) -> str:
133)         """Format a log record suitably for standard error console output.
134) 
135)         Prepend the formatted string `"PROG_NAME: LABEL"` to each line
136)         of the message, where `PROG_NAME` is the program name, and
137)         `LABEL` depends on the record's level and on the logger name as
138)         follows:
139) 
140)           * For records at level [`logging.DEBUG`][], `LABEL` is
141)             `"Debug: "`.
142)           * For records at level [`logging.INFO`][], `LABEL` is the
143)             empty string.
144)           * For records at level [`logging.WARNING`][], `LABEL` is
145)             `"Deprecation warning: "` if the logger is named
146)             `PKG.deprecation` (where `PKG` is the package name), else
147)             `"Warning: "`.
148)           * For records at level [`logging.ERROR`][] and
149)             [`logging.CRITICAL`][] `"Error: "`, `LABEL` is `"ERROR: "`.
150) 
151)         The level indication strings at level `WARNING` or above are
152)         highlighted.  Use [`click.echo`][] to output them and remove
153)         color output if necessary.
154) 
155)         Args:
156)             record: A log record.
157) 
158)         Returns:
159)             A formatted log record.
160) 
161)         Raises:
162)             AssertionError:
163)                 The log level is not supported.
164) 
165)         """
166)         preliminary_result = record.getMessage()
167)         prefix = f'{self.prog_name}: '
168)         if record.levelname == 'DEBUG':  # pragma: no cover
169)             level_indicator = 'Debug: '
170)         elif record.levelname == 'INFO':
171)             level_indicator = ''
172)         elif record.levelname == 'WARNING':
173)             level_indicator = (
174)                 f'{click.style("Deprecation warning", bold=True)}: '
175)                 if record.name.endswith('.deprecation')
176)                 else f'{click.style("Warning", bold=True)}: '
177)             )
178)         elif record.levelname in {'ERROR', 'CRITICAL'}:
179)             level_indicator = ''
180)         else:  # pragma: no cover
181)             msg = f'Unsupported logging level: {record.levelname}'
182)             raise AssertionError(msg)
183)         return ''.join(
184)             prefix + level_indicator + line
185)             for line in preliminary_result.splitlines(True)  # noqa: FBT003
186)         )
187) 
188) 
189) class StandardCLILogging:
190)     """Set up CLI logging handlers upon instantiation."""
191) 
192)     prog_name = PROG_NAME
193)     package_name = PROG_NAME.lower().replace(' ', '_').replace('-', '_')
194)     cli_formatter = CLIofPackageFormatter(
195)         prog_name=prog_name, package_name=package_name
196)     )
197)     cli_handler = ClickEchoStderrHandler()
198)     cli_handler.addFilter(logging.Filter(name=package_name))
199)     cli_handler.setFormatter(cli_formatter)
200)     cli_handler.setLevel(logging.WARNING)
201)     warnings_handler = ClickEchoStderrHandler()
202)     warnings_handler.addFilter(logging.Filter(name='py.warnings'))
203)     warnings_handler.setFormatter(cli_formatter)
204)     warnings_handler.setLevel(logging.WARNING)
205) 
206)     @classmethod
207)     def ensure_standard_logging(cls) -> StandardLoggingContextManager:
208)         """Return a context manager to ensure standard logging is set up."""
209)         return StandardLoggingContextManager(
210)             handler=cls.cli_handler,
211)             root_logger=cls.package_name,
212)         )
213) 
214)     @classmethod
215)     def ensure_standard_warnings_logging(
216)         cls,
217)     ) -> StandardWarningsLoggingContextManager:
218)         """Return a context manager to ensure warnings logging is set up."""
219)         return StandardWarningsLoggingContextManager(
220)             handler=cls.warnings_handler,
221)         )
222) 
223) 
224) class StandardLoggingContextManager:
225)     """A reentrant context manager setting up standard CLI logging.
226) 
227)     Ensures that the given handler (defaulting to the CLI logging
228)     handler) is added to the named logger (defaulting to the root
229)     logger), and if it had to be added, then that it will be removed
230)     upon exiting the context.
231) 
232)     Reentrant, but not thread safe, because it temporarily modifies
233)     global state.
234) 
235)     """
236) 
237)     def __init__(
238)         self,
239)         handler: logging.Handler,
240)         root_logger: str | None = None,
241)     ) -> None:
242)         self.handler = handler
243)         self.root_logger_name = root_logger
244)         self.base_logger = logging.getLogger(self.root_logger_name)
245)         self.action_required: MutableSequence[bool] = collections.deque()
246) 
247)     def __enter__(self) -> Self:
248)         self.action_required.append(
249)             self.handler not in self.base_logger.handlers
250)         )
251)         if self.action_required[-1]:
252)             self.base_logger.addHandler(self.handler)
253)         return self
254) 
255)     def __exit__(
256)         self,
257)         exc_type: type[BaseException] | None,
258)         exc_value: BaseException | None,
259)         exc_tb: types.TracebackType | None,
260)     ) -> Literal[False]:
261)         if self.action_required[-1]:
262)             self.base_logger.removeHandler(self.handler)
263)         self.action_required.pop()
264)         return False
265) 
266) 
267) class StandardWarningsLoggingContextManager(StandardLoggingContextManager):
268)     """A reentrant context manager setting up standard warnings logging.
269) 
270)     Ensures that warnings are being diverted to the logging system, and
271)     that the given handler (defaulting to the CLI logging handler) is
272)     added to the warnings logger. If the handler had to be added, then
273)     it will be removed upon exiting the context.
274) 
275)     Reentrant, but not thread safe, because it temporarily modifies
276)     global state.
277) 
278)     """
279) 
280)     def __init__(
281)         self,
282)         handler: logging.Handler,
283)     ) -> None:
284)         super().__init__(handler=handler, root_logger='py.warnings')
285)         self.stack: MutableSequence[
286)             tuple[
287)                 Callable[
288)                     [
289)                         type[BaseException] | None,
290)                         BaseException | None,
291)                         types.TracebackType | None,
292)                     ],
293)                     None,
294)                 ],
295)                 Callable[
296)                     [
297)                         str | Warning,
298)                         type[Warning],
299)                         str,
300)                         int,
301)                         TextIO | None,
302)                         str | None,
303)                     ],
304)                     None,
305)                 ],
306)             ]
307)         ] = collections.deque()
308) 
309)     def __enter__(self) -> Self:
310)         def showwarning(  # noqa: PLR0913,PLR0917
311)             message: str | Warning,
312)             category: type[Warning],
313)             filename: str,
314)             lineno: int,
315)             file: TextIO | None = None,
316)             line: str | None = None,
317)         ) -> None:
318)             if file is not None:  # pragma: no cover
319)                 self.stack[0][1](
320)                     message, category, filename, lineno, file, line
321)                 )
322)             else:
323)                 logging.getLogger('py.warnings').warning(
324)                     str(
325)                         warnings.formatwarning(
326)                             message, category, filename, lineno, line
327)                         )
328)                     )
329)                 )
330) 
331)         ctx = warnings.catch_warnings()
332)         exit_func = ctx.__exit__
333)         ctx.__enter__()
334)         self.stack.append((exit_func, warnings.showwarning))
335)         warnings.showwarning = showwarning
336)         return super().__enter__()
337) 
338)     def __exit__(
339)         self,
340)         exc_type: type[BaseException] | None,
341)         exc_value: BaseException | None,
342)         exc_tb: types.TracebackType | None,
343)     ) -> Literal[False]:
344)         ret = super().__exit__(exc_type, exc_value, exc_tb)
345)         val = self.stack.pop()[0](exc_type, exc_value, exc_tb)
346)         assert not val
347)         return ret
348) 
349) 
350) P = ParamSpec('P')
351) R = TypeVar('R')
352) 
353) 
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

354) def adjust_logging_level(
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

355)     ctx: click.Context,
356)     /,
357)     param: click.Parameter | None = None,
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

358)     value: int | None = None,
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

359) ) -> None:
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

360)     """Change the logs that are emitted to standard error.
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

361) 
362)     This modifies the [`StandardCLILogging`][] settings such that log
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

363)     records at the respective level are emitted, based on the `param`
364)     and the `value`.
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

365) 
366)     """
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

367)     # Note: If multiple options use this callback, then we will be
368)     # called multiple times.  Ensure the runs are idempotent.
369)     if param is None or value is None or ctx.resilient_parsing:
370)         return
371)     StandardCLILogging.cli_handler.setLevel(value)
372)     logging.getLogger(StandardCLILogging.package_name).setLevel(value)
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

373) 
374) 
Marco Ricci Shift option parsing and gr...

Marco Ricci authored 1 month ago

375) # Option parsing and grouping
376) # ===========================
377) 
378) 
379) class OptionGroupOption(click.Option):
380)     """A [`click.Option`][] with an associated group name and group epilog.
381) 
382)     Used by [`CommandWithHelpGroups`][] to print help sections.  Each
383)     subclass contains its own group name and epilog.
384) 
385)     Attributes:
386)         option_group_name:
387)             The name of the option group.  Used as a heading on the help
388)             text for options in this section.
389)         epilog:
390)             An epilog to print after listing the options in this
391)             section.
392) 
393)     """
394) 
395)     option_group_name: str = ''
396)     """"""
397)     epilog: str = ''
398)     """"""
399) 
400)     def __init__(self, *args: Any, **kwargs: Any) -> None:  # noqa: ANN401
401)         if self.__class__ == __class__:  # type: ignore[name-defined]
402)             raise NotImplementedError
403)         super().__init__(*args, **kwargs)
404) 
405) 
406) class CommandWithHelpGroups(click.Command):
407)     """A [`click.Command`][] with support for help/option groups.
408) 
409)     Inspired by [a comment on `pallets/click#373`][CLICK_ISSUE], and
410)     further modified to support group epilogs.
411) 
412)     [CLICK_ISSUE]: https://github.com/pallets/click/issues/373#issuecomment-515293746
413) 
414)     """
415) 
416)     def format_options(
417)         self,
418)         ctx: click.Context,
419)         formatter: click.HelpFormatter,
420)     ) -> None:
421)         r"""Format options on the help listing, grouped into sections.
422) 
423)         This is a callback for [`click.Command.get_help`][] that
424)         implements the `--help` listing, by calling appropriate methods
425)         of the `formatter`.  We list all options (like the base
426)         implementation), but grouped into sections according to the
427)         concrete [`click.Option`][] subclass being used.  If the option
428)         is an instance of some subclass of [`OptionGroupOption`][], then
429)         the section heading and the epilog are taken from the
430)         [`option_group_name`] [OptionGroupOption.option_group_name] and
431)         [`epilog`] [OptionGroupOption.epilog] attributes; otherwise, the
432)         section heading is "Options" (or "Other options" if there are
433)         other option groups) and the epilog is empty.
434) 
435)         Args:
436)             ctx:
437)                 The click context.
438)             formatter:
439)                 The formatter for the `--help` listing.
440) 
441)         """
442)         help_records: dict[str, list[tuple[str, str]]] = {}
443)         epilogs: dict[str, str] = {}
444)         params = self.params[:]
445)         if (  # pragma: no branch
446)             (help_opt := self.get_help_option(ctx)) is not None
447)             and help_opt not in params
448)         ):
449)             params.append(help_opt)
450)         for param in params:
451)             rec = param.get_help_record(ctx)
452)             if rec is not None:
453)                 if isinstance(param, OptionGroupOption):
454)                     group_name = param.option_group_name
455)                     epilogs.setdefault(group_name, param.epilog)
456)                 else:
457)                     group_name = ''
458)                 help_records.setdefault(group_name, []).append(rec)
459)         default_group = help_records.pop('')
460)         default_group_name = (
461)             'Other Options' if len(default_group) > 1 else 'Options'
462)         )
463)         help_records[default_group_name] = default_group
464)         for group_name, records in help_records.items():
465)             with formatter.section(group_name):
466)                 formatter.write_dl(records)
467)             epilog = inspect.cleandoc(epilogs.get(group_name, ''))
468)             if epilog:
469)                 formatter.write_paragraph()
470)                 with formatter.indentation():
471)                     formatter.write_text(epilog)
472) 
473) 
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

474) class LoggingOption(OptionGroupOption):
475)     """Logging options for the CLI."""
476) 
477)     option_group_name = 'Logging'
478)     epilog = ''
479) 
480) 
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

481) debug_option = click.option(
482)     '--debug',
483)     'logging_level',
484)     is_flag=True,
485)     flag_value=logging.DEBUG,
486)     expose_value=False,
487)     callback=adjust_logging_level,
488)     help='also emit debug information (implies --verbose)',
489)     cls=LoggingOption,
490) )
491) verbose_option = click.option(
492)     '-v',
493)     '--verbose',
494)     'logging_level',
495)     is_flag=True,
496)     flag_value=logging.INFO,
497)     expose_value=False,
498)     callback=adjust_logging_level,
499)     help='emit extra/progress information to standard error',
500)     cls=LoggingOption,
501) )
502) quiet_option = click.option(
503)     '-q',
504)     '--quiet',
505)     'logging_level',
506)     is_flag=True,
507)     flag_value=logging.ERROR,
508)     expose_value=False,
509)     callback=adjust_logging_level,
510)     help='suppress even warnings, emit only errors',
511)     cls=LoggingOption,
512) )
513) 
514) 
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

515) def standard_logging_options(f: Callable[P, R]) -> Callable[P, R]:
516)     """Decorate the function with standard logging click options.
517) 
518)     Adds the three click options `-v`/`--verbose`, `-q`/`--quiet` and
519)     `--debug`, which issue callbacks to the [`log_info`][],
520)     [`silence_warnings`][] and [`log_debug`][] functions, respectively.
521) 
522)     Args:
523)         f: A callable to decorate.
524) 
525)     Returns:
526)         The decorated callable.
527) 
528)     """
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

529)     return debug_option(verbose_option(quiet_option(f)))
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

530) 
531) 
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

532) # Top-level
533) # =========
534) 
535) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

536) class _DefaultToVaultGroup(click.Group):
537)     """A helper class to implement the default-to-"vault"-subcommand behavior.
538) 
539)     Modifies internal [`click.MultiCommand`][] methods, and thus is both
540)     an implementation detail and a kludge.
541) 
542)     """
543) 
544)     def resolve_command(
545)         self, ctx: click.Context, args: list[str]
546)     ) -> tuple[str | None, click.Command | None, list[str]]:
547)         """Resolve a command, but default to "vault" instead of erroring out.
548) 
549)         Based on code from click 8.1, which appears to be essentially
550)         untouched since at least click 3.2.
551) 
552)         """
553)         cmd_name = click.utils.make_str(args[0])
554) 
555)         # ORIGINAL COMMENT
556)         # Get the command
557)         cmd = self.get_command(ctx, cmd_name)
558) 
559)         # ORIGINAL COMMENT
560)         # If we can't find the command but there is a normalization
561)         # function available, we try with that one.
562)         if (  # pragma: no cover
563)             cmd is None and ctx.token_normalize_func is not None
564)         ):
565)             cmd_name = ctx.token_normalize_func(cmd_name)
566)             cmd = self.get_command(ctx, cmd_name)
567) 
568)         # ORIGINAL COMMENT
569)         # If we don't find the command we want to show an error message
570)         # to the user that it was not provided.  However, there is
571)         # something else we should do: if the first argument looks like
572)         # an option we want to kick off parsing again for arguments to
573)         # resolve things like --help which now should go to the main
574)         # place.
575)         if cmd is None and not ctx.resilient_parsing:
576)             if click.parser.split_opt(cmd_name)[0]:
577)                 self.parse_args(ctx, ctx.args)
578)             # Instead of calling ctx.fail here, default to "vault", and
579)             # issue a deprecation warning.
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

580)             logger = logging.getLogger(PROG_NAME)
581)             deprecation = logging.getLogger(f'{PROG_NAME}.deprecation')
582)             deprecation.warning(
583)                 'A subcommand will be required in v1.0. '
584)                 'See --help for available subcommands.'
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

585)             )
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

586)             logger.warning('Defaulting to subcommand "vault".')
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

587)             cmd_name = 'vault'
588)             cmd = self.get_command(ctx, cmd_name)
589)             assert cmd is not None, 'Mandatory subcommand "vault" missing!'
590)             args = [cmd_name, *args]
591)         return cmd_name if cmd else None, cmd, args[1:]  # noqa: DOC201
592) 
593) 
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

594) class _TopLevelCLIEntryPoint(_DefaultToVaultGroup):
595)     """A minor variation of _DefaultToVaultGroup for the top-level command.
596) 
597)     When called as a function, this sets up the environment properly
598)     before invoking the actual callbacks.  Currently, this means setting
599)     up the logging subsystem and the delegation of Python warnings to
600)     the logging subsystem.
601) 
602)     The environment setup can be bypassed by calling the `.main` method
603)     directly.
604) 
605)     """
606) 
607)     def __call__(  # pragma: no cover
608)         self,
609)         *args: Any,  # noqa: ANN401
610)         **kwargs: Any,  # noqa: ANN401
611)     ) -> Any:  # noqa: ANN401
612)         """"""  # noqa: D419
613)         # Coverage testing is done with the `click.testing` module,
614)         # which does not use the `__call__` shortcut.  So it is normal
615)         # that this function is never called, and thus should be
616)         # excluded from coverage.
617)         with (
618)             StandardCLILogging.ensure_standard_logging(),
619)             StandardCLILogging.ensure_standard_warnings_logging(),
620)         ):
621)             return self.main(*args, **kwargs)
622) 
623) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

624) @click.group(
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

625)     context_settings={
626)         'help_option_names': ['-h', '--help'],
627)         'ignore_unknown_options': True,
628)         'allow_interspersed_args': False,
629)     },
630)     epilog=r"""
631)         Configuration is stored in a directory according to the
632)         DERIVEPASSPHRASE_PATH variable, which defaults to
633)         `~/.derivepassphrase` on UNIX-like systems and
634)         `C:\Users\<user>\AppData\Roaming\Derivepassphrase` on Windows.
Marco Ricci Fix minor typo, formatting...

Marco Ricci authored 3 months ago

635)     """,
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

636)     invoke_without_command=True,
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

637)     cls=_TopLevelCLIEntryPoint,
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

638) )
639) @click.version_option(version=dpp.__version__, prog_name=PROG_NAME)
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

640) @standard_logging_options
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

641) @click.pass_context
642) def derivepassphrase(ctx: click.Context, /) -> None:
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

643)     """Derive a strong passphrase, deterministically, from a master secret.
644) 
645)     Using a master secret, derive a passphrase for a named service,
646)     subject to constraints e.g. on passphrase length, allowed
647)     characters, etc.  The exact derivation depends on the selected
648)     derivation scheme.  For each scheme, it is computationally
649)     infeasible to discern the master secret from the derived passphrase.
650)     The derivations are also deterministic, given the same inputs, thus
651)     the resulting passphrases need not be stored explicitly.  The
652)     service name and constraints themselves also generally need not be
653)     kept secret, depending on the scheme.
654) 
655)     The currently implemented subcommands are "vault" (for the scheme
656)     used by vault) and "export" (for exporting foreign configuration
657)     data).  See the respective `--help` output for instructions.  If no
658)     subcommand is given, we default to "vault".
659) 
660)     Deprecation notice: Defaulting to "vault" is deprecated.  Starting
661)     in v1.0, the subcommand must be specified explicitly.\f
662) 
663)     This is a [`click`][CLICK]-powered command-line interface function,
664)     and not intended for programmatic use.  Call with arguments
665)     `['--help']` to see full documentation of the interface.  (See also
666)     [`click.testing.CliRunner`][] for controlled, programmatic
667)     invocation.)
668) 
Marco Ricci Update all URLs to stable a...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

670) 
671)     """  # noqa: D301
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

672)     logger = logging.getLogger(PROG_NAME)
673)     deprecation = logging.getLogger(f'{PROG_NAME}.deprecation')
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

674)     if ctx.invoked_subcommand is None:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

675)         deprecation.warning(
676)             'A subcommand will be required in v1.0. '
677)             'See --help for available subcommands.'
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

678)         )
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

679)         logger.warning('Defaulting to subcommand "vault".')
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

680)         # See definition of click.Group.invoke, non-chained case.
681)         with ctx:
682)             sub_ctx = derivepassphrase_vault.make_context(
683)                 'vault', ctx.args, parent=ctx
684)             )
685)             with sub_ctx:
686)                 return derivepassphrase_vault.invoke(sub_ctx)
687)     return None
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

688) 
689) 
690) # Exporter
691) # ========
692) 
693) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

694) @derivepassphrase.group(
695)     'export',
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

696)     context_settings={
697)         'help_option_names': ['-h', '--help'],
698)         'ignore_unknown_options': True,
699)         'allow_interspersed_args': False,
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

700)     },
701)     invoke_without_command=True,
702)     cls=_DefaultToVaultGroup,
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

703) )
704) @click.version_option(version=dpp.__version__, prog_name=PROG_NAME)
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

705) @standard_logging_options
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

706) @click.pass_context
707) def derivepassphrase_export(ctx: click.Context, /) -> None:
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

708)     """Export a foreign configuration to standard output.
709) 
710)     Read a foreign system configuration, extract all information from
711)     it, and export the resulting configuration to standard output.
712) 
713)     The only available subcommand is "vault", which implements the
714)     vault-native configuration scheme.  If no subcommand is given, we
715)     default to "vault".
716) 
717)     Deprecation notice: Defaulting to "vault" is deprecated.  Starting
718)     in v1.0, the subcommand must be specified explicitly.\f
719) 
720)     This is a [`click`][CLICK]-powered command-line interface function,
721)     and not intended for programmatic use.  Call with arguments
722)     `['--help']` to see full documentation of the interface.  (See also
723)     [`click.testing.CliRunner`][] for controlled, programmatic
724)     invocation.)
725) 
Marco Ricci Update all URLs to stable a...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

727) 
728)     """  # noqa: D301
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

729)     logger = logging.getLogger(PROG_NAME)
730)     deprecation = logging.getLogger(f'{PROG_NAME}.deprecation')
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

731)     if ctx.invoked_subcommand is None:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

732)         deprecation.warning(
733)             'A subcommand will be required in v1.0. '
734)             'See --help for available subcommands.'
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

735)         )
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

736)         logger.warning('Defaulting to subcommand "vault".')
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

737)         # See definition of click.Group.invoke, non-chained case.
738)         with ctx:
739)             sub_ctx = derivepassphrase_export_vault.make_context(
740)                 'vault', ctx.args, parent=ctx
741)             )
742)             # Constructing the subcontext above will usually already
743)             # lead to a click.UsageError, so this block typically won't
744)             # actually be called.
745)             with sub_ctx:  # pragma: no cover
746)                 return derivepassphrase_export_vault.invoke(sub_ctx)
747)     return None
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

748) 
749) 
750) def _load_data(
751)     fmt: Literal['v0.2', 'v0.3', 'storeroom'],
752)     path: str | bytes | os.PathLike[str],
753)     key: bytes,
754) ) -> Any:  # noqa: ANN401
755)     contents: bytes
756)     module: types.ModuleType
Marco Ricci Add support for Python 3.9

Marco Ricci authored 3 months ago

757)     # Use match/case here once Python 3.9 becomes unsupported.
758)     if fmt == 'v0.2':
759)         module = importlib.import_module(
760)             'derivepassphrase.exporter.vault_native'
761)         )
762)         if module.STUBBED:
763)             raise ModuleNotFoundError
764)         with open(path, 'rb') as infile:
765)             contents = base64.standard_b64decode(infile.read())
766)         return module.export_vault_native_data(
767)             contents, key, try_formats=['v0.2']
768)         )
769)     elif fmt == 'v0.3':  # noqa: RET505
770)         module = importlib.import_module(
771)             'derivepassphrase.exporter.vault_native'
772)         )
773)         if module.STUBBED:
774)             raise ModuleNotFoundError
775)         with open(path, 'rb') as infile:
776)             contents = base64.standard_b64decode(infile.read())
777)         return module.export_vault_native_data(
778)             contents, key, try_formats=['v0.3']
779)         )
780)     elif fmt == 'storeroom':
781)         module = importlib.import_module('derivepassphrase.exporter.storeroom')
782)         if module.STUBBED:
783)             raise ModuleNotFoundError
784)         return module.export_storeroom_data(path, key)
785)     else:  # pragma: no cover
786)         assert_never(fmt)
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

787) 
788) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

789) @derivepassphrase_export.command(
790)     'vault',
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

791)     context_settings={'help_option_names': ['-h', '--help']},
792) )
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

793) @standard_logging_options
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

794) @click.option(
795)     '-f',
796)     '--format',
797)     'formats',
798)     metavar='FMT',
799)     multiple=True,
800)     default=('v0.3', 'v0.2', 'storeroom'),
801)     type=click.Choice(['v0.2', 'v0.3', 'storeroom']),
802)     help='try the following storage formats, in order (default: v0.3, v0.2)',
803) )
804) @click.option(
805)     '-k',
806)     '--key',
807)     metavar='K',
808)     help=(
809)         'use K as the storage master key '
810)         '(default: check the `VAULT_KEY`, `LOGNAME`, `USER` or '
811)         '`USERNAME` environment variables)'
812)     ),
813) )
814) @click.argument('path', metavar='PATH', required=True)
815) @click.pass_context
816) def derivepassphrase_export_vault(
817)     ctx: click.Context,
818)     /,
819)     *,
820)     path: str | bytes | os.PathLike[str],
821)     formats: Sequence[Literal['v0.2', 'v0.3', 'storeroom']] = (),
822)     key: str | bytes | None = None,
823) ) -> None:
824)     """Export a vault-native configuration to standard output.
825) 
826)     Read the vault-native configuration at PATH, extract all information
827)     from it, and export the resulting configuration to standard output.
828)     Depending on the configuration format, PATH may either be a file or
829)     a directory.  Supports the vault "v0.2", "v0.3" and "storeroom"
830)     formats.
831) 
832)     If PATH is explicitly given as `VAULT_PATH`, then use the
833)     `VAULT_PATH` environment variable to determine the correct path.
834)     (Use `./VAULT_PATH` or similar to indicate a file/directory actually
835)     named `VAULT_PATH`.)
836) 
837)     """
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

838)     logger = logging.getLogger(PROG_NAME)
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

839)     if path in {'VAULT_PATH', b'VAULT_PATH'}:
840)         path = exporter.get_vault_path()
841)     if key is None:
842)         key = exporter.get_vault_key()
843)     elif isinstance(key, str):  # pragma: no branch
844)         key = key.encode('utf-8')
845)     for fmt in formats:
846)         try:
847)             config = _load_data(fmt, path, key)
848)         except (
849)             IsADirectoryError,
850)             NotADirectoryError,
851)             ValueError,
852)             RuntimeError,
853)         ):
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

854)             logger.info('Cannot load as %s: %s', fmt, path)
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

855)             continue
856)         except OSError as exc:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

857)             logger.error(
858)                 'Cannot parse %r as a valid config: %s: %r',
859)                 path,
860)                 exc.strerror,
861)                 exc.filename,
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

862)             )
863)             ctx.exit(1)
864)         except ModuleNotFoundError:
865)             # TODO(the-13th-letter): Use backslash continuation.
866)             # https://github.com/nedbat/coveragepy/issues/1836
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

867)             logger.error(
868)                 'Cannot load the required Python module "cryptography".'
869)             )
870)             logger.info('pip users: see the "export" extra.')
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

871)             ctx.exit(1)
872)         else:
873)             if not _types.is_vault_config(config):
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

874)                 logger.error('Invalid vault config: %r', config)
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

875)                 ctx.exit(1)
876)             click.echo(json.dumps(config, indent=2, sort_keys=True))
877)             break
878)     else:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

879)         logger.error('Cannot parse %r as a valid config.', path)
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

880)         ctx.exit(1)
881) 
882) 
883) # Vault
884) # =====
885) 
886) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

887) def _config_filename(
Marco Ricci Make obtaining the compatib...

Marco Ricci authored 3 weeks ago

888)     subsystem: str | None = 'old settings.json',
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

889) ) -> str | bytes | pathlib.Path:
890)     """Return the filename of the configuration file for the subsystem.
891) 
892)     The (implicit default) file is currently named `settings.json`,
893)     located within the configuration directory as determined by the
894)     `DERIVEPASSPHRASE_PATH` environment variable, or by
895)     [`click.get_app_dir`][] in POSIX mode.  Depending on the requested
896)     subsystem, this will usually be a different file within that
897)     directory.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

898) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

899)     Args:
900)         subsystem:
901)             Name of the configuration subsystem whose configuration
902)             filename to return.  If not given, return the old filename
903)             from before the subcommand migration.  If `None`, return the
904)             configuration directory instead.
905) 
906)     Raises:
907)         AssertionError:
908)             An unknown subsystem was passed.
909) 
910)     Deprecated:
911)         Since v0.2.0: The implicit default subsystem and the old
912)         configuration filename are deprecated, and will be removed in v1.0.
913)         The subsystem will be mandatory to specify.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

914) 
915)     """
916)     path: str | bytes | pathlib.Path
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

920)     # Use match/case here once Python 3.9 becomes unsupported.
921)     if subsystem is None:
922)         return path
Marco Ricci Make obtaining the compatib...

Marco Ricci authored 3 weeks ago

923)     elif subsystem == 'vault':  # noqa: RET505
Marco Ricci Add support for Python 3.9

Marco Ricci authored 3 months ago

924)         filename = f'{subsystem}.json'
Marco Ricci Introduce a central user co...

Marco Ricci authored 3 weeks ago

925)     elif subsystem == 'user configuration':
926)         filename = 'config.toml'
Marco Ricci Make obtaining the compatib...

Marco Ricci authored 3 weeks ago

927)     elif subsystem == 'old settings.json':
928)         filename = 'settings.json'
Marco Ricci Add support for Python 3.9

Marco Ricci authored 3 months ago

929)     else:  # pragma: no cover
930)         msg = f'Unknown configuration subsystem: {subsystem!r}'
931)         raise AssertionError(msg)
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

933) 
934) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

940) 
941)     Returns:
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

943) 
944)     Raises:
945)         OSError:
946)             There was an OS error accessing the file.
947)         ValueError:
948)             The data loaded from the file is not a vault(1)-compatible
949)             config.
950) 
951)     """
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

957)     return data
958) 
959) 
Marco Ricci Permit one flaky test and f...

Marco Ricci authored 3 months ago

960) def _migrate_and_load_old_config() -> tuple[
961)     _types.VaultConfig, OSError | None
962) ]:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

963)     """Load and migrate a vault(1)-compatible config.
964) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

968) 
969)     Returns:
970)         The vault settings, and an optional exception encountered during
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

973) 
974)     Raises:
975)         OSError:
976)             There was an OS error accessing the old file.
977)         ValueError:
978)             The data loaded from the file is not a vault(1)-compatible
979)             config.
980) 
981)     """
982)     new_filename = _config_filename(subsystem='vault')
Marco Ricci Make obtaining the compatib...

Marco Ricci authored 3 weeks ago

983)     old_filename = _config_filename(subsystem='old settings.json')
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

984)     with open(old_filename, 'rb') as fileobj:
985)         data = json.load(fileobj)
986)     if not _types.is_vault_config(data):
987)         raise ValueError(_INVALID_VAULT_CONFIG)
988)     try:
989)         os.replace(old_filename, new_filename)
990)     except OSError as exc:
991)         return data, exc
992)     else:
993)         return data, None
994) 
995) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

998) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1001) 
1002)     Args:
1003)         config:
1004)             vault configuration to save.
1005) 
1006)     Raises:
1007)         OSError:
1008)             There was an OS error accessing or writing the file.
1009)         ValueError:
1010)             The data cannot be stored as a vault(1)-compatible config.
1011) 
1012)     """
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1016)     filedir = os.path.dirname(os.path.abspath(filename))
1017)     try:
1018)         os.makedirs(filedir, exist_ok=False)
1019)     except FileExistsError:
1020)         if not os.path.isdir(filedir):
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1023)         json.dump(config, fileobj)
1024) 
1025) 
Marco Ricci Introduce a central user co...

Marco Ricci authored 3 weeks ago

1026) def _load_user_config() -> dict[str, Any]:
1027)     """Load the user config from the application directory.
1028) 
1029)     The filename is obtained via [`_config_filename`][].
1030) 
1031)     Returns:
1032)         The user configuration, as a nested `dict`.
1033) 
1034)     Raises:
1035)         OSError:
1036)             There was an OS error accessing the file.
1037)         ValueError:
1038)             The data loaded from the file is not a valid configuration
1039)             file.
1040) 
1041)     """
1042)     filename = _config_filename(subsystem='user configuration')
1043)     with open(filename, 'rb') as fileobj:
1044)         return tomllib.load(fileobj)
1045) 
1046) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1054) 
1055)     Args:
1056)         conn:
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

1059) 
1060)     Yields:
Marco Ricci Convert old syntax for Yiel...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1063) 
1064)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

1065)         KeyError:
1066)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
1067)             variable was not found.
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1082) 
1083)     """
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1088)             raise RuntimeError(_AGENT_COMMUNICATION_ERROR) from e
Marco Ricci Publish polished `is_suitab...

Marco Ricci authored 1 month ago

1089)         suitable_keys = copy.copy(all_key_comment_pairs)
1090)         for pair in all_key_comment_pairs:
1091)             key, _comment = pair
1092)             if vault.Vault.is_suitable_ssh_key(key, client=client):
1093)                 yield pair
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1094)     if not suitable_keys:  # pragma: no cover
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1096) 
1097) 
1098) def _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1101)     single_choice_prompt: str = 'Confirm this choice?',
1102) ) -> int:
1103)     """Prompt user for a choice among the given items.
1104) 
1105)     Print the heading, if any, then present the items to the user.  If
1106)     there are multiple items, prompt the user for a selection, validate
1107)     the choice, then return the list index of the selected item.  If
1108)     there is only a single item, request confirmation for that item
1109)     instead, and return the correct index.
1110) 
1111)     Args:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1114)         heading:
1115)             A heading for the list of items, to print immediately
1116)             before.  Defaults to a reasonable standard heading.  If
1117)             explicitly empty, print no heading.
1118)         single_choice_prompt:
1119)             The confirmation prompt if there is only a single possible
1120)             choice.  Defaults to a reasonable standard prompt.
1121) 
1122)     Returns:
1123)         An index into the items sequence, indicating the user's
1124)         selection.
1125) 
1126)     Raises:
1127)         IndexError:
1128)             The user made an invalid or empty selection, or requested an
1129)             abort.
1130) 
1131)     """
1132)     n = len(items)
1133)     if heading:
1134)         click.echo(click.style(heading, bold=True))
1135)     for i, x in enumerate(items, start=1):
1136)         click.echo(click.style(f'[{i}]', bold=True), nl=False)
1137)         click.echo(' ', nl=False)
1138)         click.echo(x)
1139)     if n > 1:
1140)         choices = click.Choice([''] + [str(i) for i in range(1, n + 1)])
1141)         choice = click.prompt(
1142)             f'Your selection? (1-{n}, leave empty to abort)',
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1143)             err=True,
1144)             type=choices,
1145)             show_choices=False,
1146)             show_default=False,
1147)             default='',
1148)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1152)     prompt_suffix = (
1153)         ' ' if single_choice_prompt.endswith(tuple('?.!')) else ': '
1154)     )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

1155)     try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1156)         click.confirm(
1157)             single_choice_prompt,
1158)             prompt_suffix=prompt_suffix,
1159)             err=True,
1160)             abort=True,
1161)             default=False,
1162)             show_default=False,
1163)         )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

1164)     except click.Abort:
1165)         raise IndexError(_EMPTY_SELECTION) from None
1166)     return 0
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1167) 
1168) 
1169) def _select_ssh_key(
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1177) 
1178)     Args:
1179)         conn:
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

1182) 
1183)     Returns:
1184)         The selected SSH key.
1185) 
1186)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

1187)         KeyError:
1188)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
1189)             variable was not found.
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1197)         IndexError:
1198)             The user made an invalid or empty selection, or requested an
1199)             abort.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1207)     """
1208)     suitable_keys = list(_get_suitable_ssh_keys(conn))
1209)     key_listing: list[str] = []
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

1214)         remaining_key_display_length = KEY_DISPLAY_LENGTH - 1 - len(keytype)
1215)         key_extract = min(
1216)             key_str,
1217)             '...' + key_str[-remaining_key_display_length:],
1218)             key=len,
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1223)         key_listing,
1224)         heading='Suitable SSH keys:',
1225)         single_choice_prompt='Use this key?',
1226)     )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1227)     return suitable_keys[choice].key
1228) 
1229) 
1230) def _prompt_for_passphrase() -> str:
1231)     """Interactively prompt for the passphrase.
1232) 
1233)     Calls [`click.prompt`][] internally.  Moved into a separate function
1234)     mainly for testing/mocking purposes.
1235) 
1236)     Returns:
1237)         The user input.
1238) 
1239)     """
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

1240)     return cast(
1241)         str,
1242)         click.prompt(
1243)             'Passphrase',
1244)             default='',
1245)             hide_input=True,
1246)             show_default=False,
1247)             err=True,
1248)         ),
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1250) 
1251) 
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

1252) def _toml_key(*parts: str) -> str:
1253)     """Return a formatted TOML key, given its parts."""
1254)     def escape(string: str) -> str:
1255)         translated = string.translate({
1256)             0: r'\u0000',
1257)             1: r'\u0001',
1258)             2: r'\u0002',
1259)             3: r'\u0003',
1260)             4: r'\u0004',
1261)             5: r'\u0005',
1262)             6: r'\u0006',
1263)             7: r'\u0007',
1264)             8: r'\b',
1265)             9: r'\t',
1266)             10: r'\n',
1267)             11: r'\u000B',
1268)             12: r'\f',
1269)             13: r'\r',
1270)             14: r'\u000E',
1271)             15: r'\u000F',
1272)             ord('"'): r'\"',
1273)             ord('\\'): r'\\',
1274)             127: r'\u007F',
1275)         })
1276)         return f'"{translated}"' if translated != string else string
1277)     return '.'.join(map(escape, parts))
1278) 
1279) 
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1280) class _ORIGIN(enum.Enum):
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

1281)     INTERACTIVE: str = 'interactive input'
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1282) 
1283) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1286)     value: dict[str, Any],
1287)     *,
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

1288)     main_config: dict[str, Any],
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

1289) ) -> None:
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

1290)     form_key = 'unicode-normalization-form'
1291)     default_form: str = main_config.get('vault', {}).get(
1292)         f'default-{form_key}', 'NFC'
1293)     )
1294)     form_dict: dict[str, dict] = main_config.get('vault', {}).get(form_key, {})
1295)     form: Any = (
1296)         default_form
1297)         if isinstance(key, _ORIGIN) or key == ('global',)
1298)         else form_dict.get(key[1], default_form)
1299)     )
1300)     config_key = (
1301)         _toml_key('vault', key[1], form_key)
1302)         if isinstance(key, tuple) and len(key) > 1 and key[1] in form_dict
1303)         else f'vault.default-{form_key}'
1304)     )
1305)     if form not in {'NFC', 'NFD', 'NFKC', 'NFKD'}:
1306)         msg = f'Invalid value {form!r} for config key {config_key}'
1307)         raise AssertionError(msg)
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1308)     logger = logging.getLogger(PROG_NAME)
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

1309)     formatted_key = (
1310)         key.value if isinstance(key, _ORIGIN) else _types.json_path(key)
1311)     )
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

1312)     if 'phrase' in value:
1313)         phrase = value['phrase']
1314)         if not unicodedata.is_normalized(form, phrase):
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1315)             logger.warning(
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

1316)                 (
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

1317)                     'the %s passphrase is not %s-normalized.  '
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1318)                     'Make sure to double-check this is really the '
1319)                     'passphrase you want.'
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

1320)                 ),
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1321)                 formatted_key,
1322)                 form,
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

1323)                 stacklevel=2,
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

1324)             )
1325) 
1326) 
Marco Ricci Hoist and add tests for int...

Marco Ricci authored 3 weeks ago

1327) def _key_to_phrase(
1328)     key_: str | bytes | bytearray,
1329)     /,
1330)     *,
1331)     error_callback: Callable[..., NoReturn] = sys.exit,
1332) ) -> bytes | bytearray:
1333)     key = base64.standard_b64decode(key_)
1334)     try:
1335)         with ssh_agent.SSHAgentClient.ensure_agent_subcontext() as client:
1336)             try:
1337)                 return vault.Vault.phrase_from_key(key, conn=client)
1338)             except ssh_agent.SSHAgentFailedError as e:
1339)                 try:
1340)                     keylist = client.list_keys()
1341)                 except ssh_agent.SSHAgentFailedError:
1342)                     pass
1343)                 except Exception as e2:  # noqa: BLE001
1344)                     e.__context__ = e2
1345)                 else:
1346)                     if not any(  # pragma: no branch
1347)                         k == key for k, _ in keylist
1348)                     ):
1349)                         error_callback(
1350)                             'The requested SSH key is not loaded '
1351)                             'into the agent.'
1352)                         )
1353)                 error_callback(e)
1354)     except KeyError:
1355)         error_callback('Cannot find running SSH agent; check SSH_AUTH_SOCK')
1356)     except NotImplementedError:
1357)         error_callback(
1358)             'Cannot connect to SSH agent because '
1359)             'this Python version does not support UNIX domain sockets'
1360)         )
1361)     except OSError as e:
1362)         error_callback('Cannot connect to SSH agent: %s', e.strerror)
1363) 
1364) 
Marco Ricci Support exporting the `vaul...

Marco Ricci authored 2 weeks ago

1365) def _print_config_as_sh_script(
1366)     config: _types.VaultConfig,
1367)     /,
1368)     *,
1369)     outfile: TextIO,
1370)     prog_name_list: Sequence[str],
1371) ) -> None:
1372)     service_keys = (
1373)         'length',
1374)         'repeat',
1375)         'lower',
1376)         'upper',
1377)         'number',
1378)         'space',
1379)         'dash',
1380)         'symbol',
1381)     )
1382)     print('#!/bin/sh -e', file=outfile)
1383)     print(file=outfile)
1384)     print(shlex.join([*prog_name_list, '--clear']), file=outfile)
1385)     sv_obj_pairs: list[
1386)         tuple[
1387)             str | None,
1388)             _types.VaultConfigGlobalSettings
1389)             | _types.VaultConfigServicesSettings,
1390)         ],
1391)     ] = list(config['services'].items())
1392)     if config.get('global', {}):
1393)         sv_obj_pairs.insert(0, (None, config['global']))
1394)     for sv, sv_obj in sv_obj_pairs:
1395)         this_service_keys = tuple(k for k in service_keys if k in sv_obj)
1396)         this_other_keys = tuple(k for k in sv_obj if k not in service_keys)
1397)         if this_other_keys:
1398)             other_sv_obj = {k: sv_obj[k] for k in this_other_keys}  # type: ignore[literal-required]
1399)             dumped_config = json.dumps(
1400)                 (
1401)                     {'services': {sv: other_sv_obj}}
1402)                     if sv is not None
1403)                     else {'global': other_sv_obj, 'services': {}}
1404)                 ),
1405)                 ensure_ascii=False,
1406)                 indent=None,
1407)             )
1408)             print(
1409)                 shlex.join([*prog_name_list, '--import', '-']) + " <<'HERE'",
1410)                 dumped_config,
1411)                 'HERE',
1412)                 sep='\n',
1413)                 file=outfile,
1414)             )
1415)         if not this_service_keys and not this_other_keys and sv:
1416)             dumped_config = json.dumps(
1417)                 {'services': {sv: {}}},
1418)                 ensure_ascii=False,
1419)                 indent=None,
1420)             )
1421)             print(
1422)                 shlex.join([*prog_name_list, '--import', '-']) + " <<'HERE'",
1423)                 dumped_config,
1424)                 'HERE',
1425)                 sep='\n',
1426)                 file=outfile,
1427)             )
1428)         elif this_service_keys:
1429)             tokens = [*prog_name_list, '--config']
1430)             for key in this_service_keys:
1431)                 tokens.extend([f'--{key}', str(sv_obj[key])])  # type: ignore[literal-required]
1432)             if sv is not None:
1433)                 tokens.extend(['--', sv])
1434)             print(shlex.join(tokens), file=outfile)
1435) 
1436) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1447) 
1448) class ConfigurationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1456) 
1457) class StorageManagementOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1464)     """
1465) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

1466) 
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1467) class CompatibilityOption(OptionGroupOption):
1468)     """Compatibility and incompatibility options for the CLI."""
1469) 
1470)     option_group_name = 'Options concerning compatibility with other tools'
1471) 
1472) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1473) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1478)     """Check that the occurrence constraint is valid (int, 0 or larger).
1479) 
1480)     Args:
1481)         ctx: The `click` context.
1482)         param: The current command-line parameter.
1483)         value: The parameter value to be checked.
1484) 
1485)     Returns:
1486)         The parsed parameter value.
1487) 
1488)     Raises:
1489)         click.BadParameter: The parameter value is invalid.
1490) 
1491)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1494)     if value is None:
1495)         return value
1496)     if isinstance(value, int):
1497)         int_value = value
1498)     else:
1499)         try:
1500)             int_value = int(value, 10)
1501)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1507)     return int_value
1508) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1509) 
1510) def _validate_length(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1515)     """Check that the length is valid (int, 1 or larger).
1516) 
1517)     Args:
1518)         ctx: The `click` context.
1519)         param: The current command-line parameter.
1520)         value: The parameter value to be checked.
1521) 
1522)     Returns:
1523)         The parsed parameter value.
1524) 
1525)     Raises:
1526)         click.BadParameter: The parameter value is invalid.
1527) 
1528)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1531)     if value is None:
1532)         return value
1533)     if isinstance(value, int):
1534)         int_value = value
1535)     else:
1536)         try:
1537)             int_value = int(value, 10)
1538)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1544)     return int_value
1545) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1546) 
1547) DEFAULT_NOTES_TEMPLATE = """\
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1548) # Enter notes below the line with the cut mark (ASCII scissors and
1549) # dashes).  Lines above the cut mark (such as this one) will be ignored.
1550) #
1551) # If you wish to clear the notes, leave everything beyond the cut mark
1552) # blank.  However, if you leave the *entire* file blank, also removing
1553) # the cut mark, then the edit is aborted, and the old notes contents are
1554) # retained.
1555) #
1556) # - - - - - >8 - - - - - >8 - - - - - >8 - - - - - >8 - - - - -
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1558) DEFAULT_NOTES_MARKER = '# - - - - - >8 - - - - -'
1559) 
1560) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

1561) @derivepassphrase.command(
1562)     'vault',
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1574)     """,
1575) )
1576) @click.option(
1577)     '-p',
1578)     '--phrase',
1579)     'use_phrase',
1580)     is_flag=True,
1581)     help='prompts you for your passphrase',
1582)     cls=PasswordGenerationOption,
1583) )
1584) @click.option(
1585)     '-k',
1586)     '--key',
1587)     'use_key',
1588)     is_flag=True,
1589)     help='uses your SSH private key to generate passwords',
1590)     cls=PasswordGenerationOption,
1591) )
1592) @click.option(
1593)     '-l',
1594)     '--length',
1595)     metavar='NUMBER',
1596)     callback=_validate_length,
1597)     help='emits password of length NUMBER',
1598)     cls=PasswordGenerationOption,
1599) )
1600) @click.option(
1601)     '-r',
1602)     '--repeat',
1603)     metavar='NUMBER',
1604)     callback=_validate_occurrence_constraint,
1605)     help='allows maximum of NUMBER repeated adjacent chars',
1606)     cls=PasswordGenerationOption,
1607) )
1608) @click.option(
1609)     '--lower',
1610)     metavar='NUMBER',
1611)     callback=_validate_occurrence_constraint,
1612)     help='includes at least NUMBER lowercase letters',
1613)     cls=PasswordGenerationOption,
1614) )
1615) @click.option(
1616)     '--upper',
1617)     metavar='NUMBER',
1618)     callback=_validate_occurrence_constraint,
1619)     help='includes at least NUMBER uppercase letters',
1620)     cls=PasswordGenerationOption,
1621) )
1622) @click.option(
1623)     '--number',
1624)     metavar='NUMBER',
1625)     callback=_validate_occurrence_constraint,
1626)     help='includes at least NUMBER digits',
1627)     cls=PasswordGenerationOption,
1628) )
1629) @click.option(
1630)     '--space',
1631)     metavar='NUMBER',
1632)     callback=_validate_occurrence_constraint,
1633)     help='includes at least NUMBER spaces',
1634)     cls=PasswordGenerationOption,
1635) )
1636) @click.option(
1637)     '--dash',
1638)     metavar='NUMBER',
1639)     callback=_validate_occurrence_constraint,
1640)     help='includes at least NUMBER "-" or "_"',
1641)     cls=PasswordGenerationOption,
1642) )
1643) @click.option(
1644)     '--symbol',
1645)     metavar='NUMBER',
1646)     callback=_validate_occurrence_constraint,
1647)     help='includes at least NUMBER symbol chars',
1648)     cls=PasswordGenerationOption,
1649) )
1650) @click.option(
1651)     '-n',
1652)     '--notes',
1653)     'edit_notes',
1654)     is_flag=True,
1655)     help='spawn an editor to edit notes for SERVICE',
1656)     cls=ConfigurationOption,
1657) )
1658) @click.option(
1659)     '-c',
1660)     '--config',
1661)     'store_config_only',
1662)     is_flag=True,
1663)     help='saves the given settings for SERVICE or global',
1664)     cls=ConfigurationOption,
1665) )
1666) @click.option(
1667)     '-x',
1668)     '--delete',
1669)     'delete_service_settings',
1670)     is_flag=True,
1671)     help='deletes settings for SERVICE',
1672)     cls=ConfigurationOption,
1673) )
1674) @click.option(
1675)     '--delete-globals',
1676)     is_flag=True,
1677)     help='deletes the global shared settings',
1678)     cls=ConfigurationOption,
1679) )
1680) @click.option(
1681)     '-X',
1682)     '--clear',
1683)     'clear_all_settings',
1684)     is_flag=True,
1685)     help='deletes all settings',
1686)     cls=ConfigurationOption,
1687) )
1688) @click.option(
1689)     '-e',
1690)     '--export',
1691)     'export_settings',
1692)     metavar='PATH',
1693)     help='export all saved settings into file PATH',
1694)     cls=StorageManagementOption,
1695) )
1696) @click.option(
1697)     '-i',
1698)     '--import',
1699)     'import_settings',
1700)     metavar='PATH',
1701)     help='import saved settings from file PATH',
1702)     cls=StorageManagementOption,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

1703) )
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1704) @click.option(
1705)     '--overwrite-existing/--merge-existing',
1706)     'overwrite_config',
1707)     default=False,
1708)     help='overwrite or merge (default) the existing configuration',
1709)     cls=CompatibilityOption,
1710) )
Marco Ricci Allow unsetting settings wh...

Marco Ricci authored 2 weeks ago

1711) @click.option(
1712)     '--unset',
1713)     'unset_settings',
1714)     multiple=True,
1715)     type=click.Choice([
1716)         'phrase',
1717)         'key',
1718)         'length',
1719)         'repeat',
1720)         'lower',
1721)         'upper',
1722)         'number',
1723)         'space',
1724)         'dash',
1725)         'symbol',
1726)     ]),
1727)     help=(
1728)         'with --config, also unsets the given setting; '
1729)         'may be specified multiple times'
1730)     ),
1731)     cls=CompatibilityOption,
1732) )
Marco Ricci Support exporting the `vaul...

Marco Ricci authored 2 weeks ago

1733) @click.option(
1734)     '--export-as',
1735)     type=click.Choice(['JSON', 'sh']),
1736)     default='JSON',
1737)     help='when exporting, export as JSON (default) or POSIX sh',
1738)     cls=CompatibilityOption,
1739) )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

1740) @click.version_option(version=dpp.__version__, prog_name=PROG_NAME)
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1741) @standard_logging_options
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1745)     ctx: click.Context,
1746)     /,
1747)     *,
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1748)     service: str | None = None,
1749)     use_phrase: bool = False,
1750)     use_key: bool = False,
1751)     length: int | None = None,
1752)     repeat: int | None = None,
1753)     lower: int | None = None,
1754)     upper: int | None = None,
1755)     number: int | None = None,
1756)     space: int | None = None,
1757)     dash: int | None = None,
1758)     symbol: int | None = None,
1759)     edit_notes: bool = False,
1760)     store_config_only: bool = False,
1761)     delete_service_settings: bool = False,
1762)     delete_globals: bool = False,
1763)     clear_all_settings: bool = False,
1764)     export_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
1765)     import_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1766)     overwrite_config: bool = False,
Marco Ricci Allow unsetting settings wh...

Marco Ricci authored 2 weeks ago

1767)     unset_settings: Sequence[str] = (),
Marco Ricci Support exporting the `vaul...

Marco Ricci authored 2 weeks ago

1768)     export_as: Literal['json', 'sh'] = 'json',
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1772)     Using a master passphrase or a master SSH key, derive a passphrase
1773)     for SERVICE, subject to length, character and character repetition
1774)     constraints.  The derivation is cryptographically strong, meaning
1775)     that even if a single passphrase is compromised, guessing the master
1776)     passphrase or a different service's passphrase is computationally
1777)     infeasible.  The derivation is also deterministic, given the same
1778)     inputs, thus the resulting passphrase need not be stored explicitly.
1779)     The service name and constraints themselves also need not be kept
1780)     secret; the latter are usually stored in a world-readable file.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1792) 
1793)     Parameters:
1794)         ctx (click.Context):
1795)             The `click` context.
1796) 
1797)     Other Parameters:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1850)         export_settings:
1851)             Command-line argument `-e`/`--export`.  If a file object,
1852)             then it must be open for writing and accept `str` inputs.
1853)             Otherwise, a filename to open for writing.  Using `-` for
1854)             standard output is supported.
1855)         import_settings:
1856)             Command-line argument `-i`/`--import`.  If a file object, it
1857)             must be open for reading and yield `str` values.  Otherwise,
1858)             a filename to open for reading.  Using `-` for standard
1859)             input is supported.
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1860)         overwrite_config:
1861)             Command-line arguments `--overwrite-existing` (True) and
1862)             `--merge-existing` (False).  Controls whether config saving
1863)             and config importing overwrite existing configurations, or
1864)             merge them section-wise instead.
Marco Ricci Allow unsetting settings wh...

Marco Ricci authored 2 weeks ago

1865)         unset_settings:
1866)             Command-line argument `--unset`.  If given together with
1867)             `--config`, unsets the specified settings (in addition to
1868)             any other changes requested).
Marco Ricci Support exporting the `vaul...

Marco Ricci authored 2 weeks ago

1869)         export_as:
1870)             Command-line argument `--export-as`.  If given together with
1871)             `--export`, selects the format to export the current
1872)             configuration as: JSON ("json", default) or POSIX sh ("sh").
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1874)     """  # noqa: D301
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1875)     logger = logging.getLogger(PROG_NAME)
1876)     deprecation = logging.getLogger(PROG_NAME + '.deprecation')
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

1882)             # Use match/case here once Python 3.9 becomes unsupported.
1883)             if isinstance(param, PasswordGenerationOption):
1884)                 group = PasswordGenerationOption
1885)             elif isinstance(param, ConfigurationOption):
1886)                 group = ConfigurationOption
1887)             elif isinstance(param, StorageManagementOption):
1888)                 group = StorageManagementOption
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1889)             elif isinstance(param, LoggingOption):
1890)                 group = LoggingOption
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1891)             elif isinstance(param, CompatibilityOption):
1892)                 group = CompatibilityOption
Marco Ricci Add support for Python 3.9

Marco Ricci authored 3 months ago

1893)             elif isinstance(param, OptionGroupOption):
1894)                 raise AssertionError(  # noqa: DOC501,TRY003,TRY004
1895)                     f'Unknown option group for {param!r}'  # noqa: EM102
1896)                 )
1897)             else:
1898)                 group = click.Option
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1899)             options_in_group.setdefault(group, []).append(param)
1900)         params_by_str[param.human_readable_name] = param
1901)         for name in param.opts + param.secondary_opts:
1902)             params_by_str[name] = param
1903) 
Marco Ricci Rewrite incompatible option...

Marco Ricci authored 3 weeks ago

1904)     @functools.cache
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1908)     def check_incompatible_options(
Marco Ricci Rewrite incompatible option...

Marco Ricci authored 3 weeks ago

1909)         param1: click.Parameter | str,
1910)         param2: click.Parameter | str,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

1911)     ) -> None:
Marco Ricci Rewrite incompatible option...

Marco Ricci authored 3 weeks ago

1912)         param1 = params_by_str[param1] if isinstance(param1, str) else param1
1913)         param2 = params_by_str[param2] if isinstance(param2, str) else param2
1914)         if param1 == param2:
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

1915)             return
Marco Ricci Rewrite incompatible option...

Marco Ricci authored 3 weeks ago

1916)         if not is_param_set(param1):
1917)             return
1918)         if is_param_set(param2):
1919)             param1_str = param1.human_readable_name
1920)             param2_str = param2.human_readable_name
1921)             raise click.BadOptionUsage(
1922)                 param1_str, f'mutually exclusive with {param2_str}', ctx=ctx
1923)             )
1924)         return
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1925) 
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1926)     def err(msg: Any, *args: Any, **kwargs: Any) -> NoReturn:  # noqa: ANN401
1927)         stacklevel = kwargs.pop('stacklevel', 1)
1928)         stacklevel += 1
1929)         logger.error(msg, *args, stacklevel=stacklevel, **kwargs)
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

1930)         ctx.exit(1)
1931) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1933)         try:
1934)             return _load_config()
1935)         except FileNotFoundError:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1936)             try:
1937)                 backup_config, exc = _migrate_and_load_old_config()
1938)             except FileNotFoundError:
1939)                 return {'services': {}}
Marco Ricci Make obtaining the compatib...

Marco Ricci authored 3 weeks ago

1940)             old_name = os.path.basename(
1941)                 _config_filename(subsystem='old settings.json')
1942)             )
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1943)             new_name = os.path.basename(_config_filename(subsystem='vault'))
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1944)             deprecation.warning(
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1945)                 (
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1946)                     'Using deprecated v0.1-style config file %r, '
1947)                     'instead of v0.2-style %r.  '
1948)                     'Support for v0.1-style config filenames will be '
1949)                     'removed in v1.0.'
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1950)                 ),
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1951)                 old_name,
1952)                 new_name,
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1953)             )
1954)             if isinstance(exc, OSError):
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1955)                 logger.warning(
1956)                     'Failed to migrate to %r: %s: %r',
1957)                     new_name,
1958)                     exc.strerror,
1959)                     exc.filename,
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1960)                 )
1961)             else:
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

1962)                 deprecation.info('Successfully migrated to %r.', new_name)
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1963)             return backup_config
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

1964)         except OSError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1965)             err('Cannot load config: %s: %r', e.strerror, e.filename)
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

1966)         except Exception as e:  # noqa: BLE001
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1967)             err('Cannot load config: %s', str(e), exc_info=e)
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

1968) 
1969)     def put_config(config: _types.VaultConfig, /) -> None:
1970)         try:
1971)             _save_config(config)
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

1972)         except OSError as exc:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1973)             err('Cannot store config: %s: %r', exc.strerror, exc.filename)
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

1974)         except Exception as exc:  # noqa: BLE001
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1975)             err('Cannot store config: %s', str(exc), exc_info=exc)
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1976) 
Marco Ricci Introduce a central user co...

Marco Ricci authored 3 weeks ago

1977)     def get_user_config() -> dict[str, Any]:
1978)         try:
1979)             return _load_user_config()
1980)         except FileNotFoundError:
1981)             return {}
1982)         except OSError as e:
1983)             err('Cannot load user config: %s: %r', e.strerror, e.filename)
1984)         except Exception as e:  # noqa: BLE001
1985)             err('Cannot load user config: %s', str(e), exc_info=e)
1986) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1988) 
1989)     check_incompatible_options('--phrase', '--key')
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1991)         for opt in options_in_group[group]:
1992)             if opt != params_by_str['--config']:
Marco Ricci Rewrite incompatible option...

Marco Ricci authored 3 weeks ago

1993)                 for other_opt in options_in_group[PasswordGenerationOption]:
1994)                     check_incompatible_options(opt, other_opt)
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1997)         for opt in options_in_group[group]:
Marco Ricci Rewrite incompatible option...

Marco Ricci authored 3 weeks ago

1998)             for other_opt in options_in_group[ConfigurationOption]:
1999)                 check_incompatible_options(opt, other_opt)
2000)             for other_opt in options_in_group[StorageManagementOption]:
2001)                 check_incompatible_options(opt, other_opt)
Marco Ricci Correctly model vault globa...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

2009)             raise click.UsageError(msg)  # noqa: DOC501
2010)     sv_options = [params_by_str['--notes'], params_by_str['--delete']]
2011)     for param in sv_options:
2012)         if is_param_set(param) and not service:
2013)             opt_str = param.opts[0]
2014)             msg = f'{opt_str} requires a SERVICE'
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

2016)     no_sv_options = [
2017)         params_by_str['--delete-globals'],
2018)         params_by_str['--clear'],
2019)         *options_in_group[StorageManagementOption],
2020)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

2026) 
Marco Ricci Introduce a central user co...

Marco Ricci authored 3 weeks ago

2027)     user_config = get_user_config()
2028) 
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

2029)     if service == '':  # noqa: PLC1901
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2030)         logger.warning(
2031)             'An empty SERVICE is not supported by vault(1).  '
2032)             'For compatibility, this will be treated as if SERVICE '
2033)             'was not supplied, i.e., it will error out, or '
2034)             'operate on global settings.'
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

2035)         )
2036) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2037)     if edit_notes:
2038)         assert service is not None
2039)         configuration = get_config()
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2046)             while notes_lines:
2047)                 line = notes_lines.popleft()
2048)                 if line.startswith(DEFAULT_NOTES_MARKER):
2049)                     notes_value = ''.join(notes_lines)
2050)                     break
2051)             else:
2052)                 if not notes_value.strip():
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

2055)                 notes_value.strip('\n')
2056)             )
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2058)     elif delete_service_settings:
2059)         assert service is not None
2060)         configuration = get_config()
2061)         if service in configuration['services']:
2062)             del configuration['services'][service]
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2064)     elif delete_globals:
2065)         configuration = get_config()
2066)         if 'global' in configuration:
2067)             del configuration['global']
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2071)     elif import_settings:
2072)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

2073)             # TODO(the-13th-letter): keep track of auto-close; try
2074)             # os.dup if feasible
Marco Ricci Document handling of file o...

Marco Ricci authored 3 weeks ago

2075)             infile = cast(
2076)                 TextIO,
2077)                 (
2078)                     import_settings
2079)                     if hasattr(import_settings, 'close')
2080)                     else click.open_file(os.fspath(import_settings), 'rt')
2081)                 ),
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2082)             )
Marco Ricci Document handling of file o...

Marco Ricci authored 3 weeks ago

2083)             # Don't specifically catch TypeError or ValueError here if
2084)             # the passed-in fileobj is not a readable text stream.  This
2085)             # will never happen on the command-line (thanks to `click`),
2086)             # and for programmatic use, our caller may want accurate
2087)             # error information.
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2088)             with infile:
2089)                 maybe_config = json.load(infile)
2090)         except json.JSONDecodeError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2091)             err('Cannot load config: cannot decode JSON: %s', e)
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2092)         except OSError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2093)             err('Cannot load config: %s: %r', e.strerror, e.filename)
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

2094)         cleaned = _types.clean_up_falsy_vault_config_values(maybe_config)
2095)         if not _types.is_vault_config(maybe_config):
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2096)             err('Cannot load config: %s', _INVALID_VAULT_CONFIG)
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

2097)         assert cleaned is not None
2098)         for step in cleaned:
2099)             # These are never fatal errors, because the semantics of
2100)             # vault upon encountering these settings are ill-specified,
2101)             # but not ill-defined.
2102)             if step.action == 'replace':
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2103)                 logger.warning(
2104)                     'Replacing invalid value %s for key %s with %s.',
2105)                     json.dumps(step.old_value),
2106)                     _types.json_path(step.path),
2107)                     json.dumps(step.new_value),
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

2108)                 )
2109)             else:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2110)                 logger.warning(
2111)                     'Removing ineffective setting %s = %s.',
2112)                     _types.json_path(step.path),
2113)                     json.dumps(step.old_value),
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

2115)         if '' in maybe_config['services']:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2116)             logger.warning(
2117)                 (
2118)                     'An empty SERVICE is not supported by vault(1), '
2119)                     'and the empty-string service settings will be '
2120)                     'inaccessible and ineffective.  To ensure that '
2121)                     'vault(1) and %s see the settings, move them '
2122)                     'into the "global" section.'
2123)                 ),
2124)                 PROG_NAME,
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

2125)             )
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

2126)         try:
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

2127)             _check_for_misleading_passphrase(
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

2128)                 ('global',),
2129)                 cast(dict[str, Any], maybe_config.get('global', {})),
2130)                 main_config=user_config,
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

2131)             )
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

2132)             for key, value in maybe_config['services'].items():
2133)                 _check_for_misleading_passphrase(
2134)                     ('services', key),
2135)                     cast(dict[str, Any], value),
2136)                     main_config=user_config,
2137)                 )
2138)         except AssertionError as e:
2139)             err('The configuration file is invalid.  ' + str(e))
Marco Ricci Fix empty key handling in `...

Marco Ricci authored 3 weeks ago

2140)         global_obj = maybe_config.get('global', {})
2141)         has_key = _types.js_truthiness(global_obj.get('key'))
2142)         has_phrase = _types.js_truthiness(global_obj.get('phrase'))
2143)         if has_key and has_phrase:
2144)             logger.warning(
2145)                 'Setting a global passphrase is ineffective '
2146)                 'because a key is also set.'
2147)             )
2148)         for service_name, service_obj in maybe_config['services'].items():
2149)             has_key = _types.js_truthiness(
2150)                 service_obj.get('key')
2151)             ) or _types.js_truthiness(global_obj.get('key'))
2152)             has_phrase = _types.js_truthiness(
2153)                 service_obj.get('phrase')
2154)             ) or _types.js_truthiness(global_obj.get('phrase'))
2155)             if has_key and has_phrase:
2156)                 logger.warning(
2157)                     (
2158)                         'Setting a service passphrase is ineffective '
2159)                         'because a key is also set: %s'
2160)                     ),
2161)                     json.dumps(service_name),
2162)                 )
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

2163)         if overwrite_config:
2164)             put_config(maybe_config)
2165)         else:
2166)             configuration = get_config()
2167)             merged_config: collections.ChainMap[str, Any] = (
2168)                 collections.ChainMap(
2169)                     {
2170)                         'services': collections.ChainMap(
2171)                             maybe_config['services'],
2172)                             configuration['services'],
2173)                         ),
2174)                     },
2175)                     {'global': maybe_config['global']}
2176)                     if 'global' in maybe_config
2177)                     else {},
2178)                     {'global': configuration['global']}
2179)                     if 'global' in configuration
2180)                     else {},
2181)                 )
2182)             )
2183)             new_config: Any = {
2184)                 k: dict(v) if isinstance(v, collections.ChainMap) else v
2185)                 for k, v in sorted(merged_config.items())
2186)             }
2187)             assert _types.is_vault_config(new_config)
2188)             put_config(new_config)
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2189)     elif export_settings:
2190)         configuration = get_config()
2191)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

2192)             # TODO(the-13th-letter): keep track of auto-close; try
2193)             # os.dup if feasible
Marco Ricci Document handling of file o...

Marco Ricci authored 3 weeks ago

2194)             outfile = cast(
2195)                 TextIO,
2196)                 (
2197)                     export_settings
2198)                     if hasattr(export_settings, 'close')
2199)                     else click.open_file(os.fspath(export_settings), 'wt')
2200)                 ),
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2201)             )
Marco Ricci Document handling of file o...

Marco Ricci authored 3 weeks ago

2202)             # Don't specifically catch TypeError or ValueError here if
2203)             # the passed-in fileobj is not a writable text stream.  This
2204)             # will never happen on the command-line (thanks to `click`),
2205)             # and for programmatic use, our caller may want accurate
2206)             # error information.
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2207)             with outfile:
Marco Ricci Support exporting the `vaul...

Marco Ricci authored 2 weeks ago

2208)                 if export_as == 'sh':
2209)                     this_ctx = ctx
2210)                     prog_name_pieces = collections.deque([
2211)                         this_ctx.info_name or 'vault',
2212)                     ])
2213)                     while (
2214)                         this_ctx.parent is not None
2215)                         and this_ctx.parent.info_name is not None
2216)                     ):
2217)                         prog_name_pieces.appendleft(this_ctx.parent.info_name)
2218)                         this_ctx = this_ctx.parent
2219)                     _print_config_as_sh_script(
2220)                         configuration,
2221)                         outfile=outfile,
2222)                         prog_name_list=prog_name_pieces,
2223)                     )
2224)                 else:
2225)                     json.dump(configuration, outfile)
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2226)         except OSError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2227)             err('Cannot store config: %s: %r', e.strerror, e.filename)
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

2235)         service_keys = {
2236)             'key',
2237)             'phrase',
2238)             'length',
2239)             'repeat',
2240)             'lower',
2241)             'upper',
2242)             'number',
2243)             'space',
2244)             'dash',
2245)             'symbol',
2246)         }
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

2248)             {
2249)                 k: v
2250)                 for k, v in locals().items()
2251)                 if k in service_keys and v is not None
2252)             },
2253)             cast(
2254)                 dict[str, Any],
2255)                 configuration['services'].get(service or '', {}),
2256)             ),
2257)             cast(dict[str, Any], configuration.get('global', {})),
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2258)         )
2259)         if use_key:
2260)             try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2261)                 key = base64.standard_b64encode(_select_ssh_key()).decode(
2262)                     'ASCII'
2263)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

2268)             except NotImplementedError:
2269)                 err(
2270)                     'Cannot connect to SSH agent because '
2271)                     'this Python version does not support UNIX domain sockets'
2272)                 )
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

2273)             except OSError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2274)                 err('Cannot connect to SSH agent: %s', e.strerror)
Marco Ricci Add a specific error class...

Marco Ricci authored 4 months ago

2275)             except (
2276)                 LookupError,
2277)                 RuntimeError,
2278)                 ssh_agent.SSHAgentFailedError,
2279)             ) as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2281)         elif use_phrase:
2282)             maybe_phrase = _prompt_for_passphrase()
2283)             if not maybe_phrase:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2285)             else:
2286)                 phrase = maybe_phrase
2287)         if store_config_only:
2288)             view: collections.ChainMap[str, Any]
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2289)             view = (
2290)                 collections.ChainMap(*settings.maps[:2])
2291)                 if service
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

2294)             if use_key:
2295)                 view['key'] = key
2296)             elif use_phrase:
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

2297)                 view['phrase'] = phrase
2298)                 settings_type = 'service' if service else 'global'
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

2299)                 try:
2300)                     _check_for_misleading_passphrase(
2301)                         ('services', service) if service else ('global',),
2302)                         {'phrase': phrase},
2303)                         main_config=user_config,
2304)                     )
2305)                 except AssertionError as e:
2306)                     err('The configuration file is invalid.  ' + str(e))
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

2307)                 if 'key' in settings:
Marco Ricci Fix empty key handling in `...

Marco Ricci authored 3 weeks ago

2308)                     if service:
2309)                         logger.warning(
2310)                             (
2311)                                 'Setting a service passphrase is ineffective '
2312)                                 'because a key is also set: %s'
2313)                             ),
2314)                             json.dumps(service),
2315)                         )
2316)                     else:
2317)                         logger.warning(
2318)                             'Setting a global passphrase is ineffective '
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2319)                             'because a key is also set.'
Marco Ricci Fix empty key handling in `...

Marco Ricci authored 3 weeks ago

2320)                         )
Marco Ricci Allow unsetting settings wh...

Marco Ricci authored 2 weeks ago

2321)             if not view.maps[0] and not unset_settings:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

2322)                 settings_type = 'service' if service else 'global'
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2325)                     f'actual settings'
2326)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

2327)                 raise click.UsageError(msg)
Marco Ricci Allow unsetting settings wh...

Marco Ricci authored 2 weeks ago

2328)             for setting in unset_settings:
2329)                 if setting in view.maps[0]:
2330)                     msg = (
2331)                         f'Attempted to unset and set --{setting} '
2332)                         f'at the same time.'
2333)                     )
2334)                     raise click.UsageError(msg)
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

2335)             subtree: dict[str, Any] = (
2336)                 configuration['services'].setdefault(service, {})  # type: ignore[assignment]
2337)                 if service
2338)                 else configuration.setdefault('global', {})
2339)             )
2340)             if overwrite_config:
2341)                 subtree.clear()
Marco Ricci Allow unsetting settings wh...

Marco Ricci authored 2 weeks ago

2342)             else:
2343)                 for setting in unset_settings:
2344)                     subtree.pop(setting, None)
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

2345)             subtree.update(view)
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2350)         else:
2351)             if not service:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

2354)             kwargs: dict[str, Any] = {
2355)                 k: v
2356)                 for k, v in settings.items()
2357)                 if k in service_keys and v is not None
2358)             }
2359) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

2360)             if use_phrase:
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

2361)                 try:
2362)                     _check_for_misleading_passphrase(
2363)                         _ORIGIN.INTERACTIVE,
2364)                         {'phrase': phrase},
2365)                         main_config=user_config,
2366)                     )
2367)                 except AssertionError as e:
2368)                     err('The configuration file is invalid.  ' + str(e))
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

2376)             if use_key or use_phrase:
Marco Ricci Hoist and add tests for int...

Marco Ricci authored 3 weeks ago

2377)                 kwargs['phrase'] = _key_to_phrase(
2378)                     key, error_callback=err
2379)                 ) if use_key else phrase
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2380)             elif kwargs.get('key'):
Marco Ricci Hoist and add tests for int...

Marco Ricci authored 3 weeks ago

2381)                 kwargs['phrase'] = _key_to_phrase(
2382)                     kwargs['key'], error_callback=err
2383)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2384)             elif kwargs.get('phrase'):
2385)                 pass
2386)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2389)                     'or in configuration'
2390)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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