c24003e853bd053cf88b2b9c3d940170dbc332ec
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 Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

19) import os
Marco Ricci Introduce a central user co...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

32) 
33) import click
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

36)     ParamSpec,
37)     Self,
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

38)     assert_never,
39) )
40) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

56)         Sequence,
57)     )
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

72) 
73) 
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

363) 
364)     """
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

371) 
372) 
Marco Ricci Shift option parsing and gr...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

528) 
529) 
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

530) # Top-level
531) # =========
532) 
533) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

686) 
687) 
688) # Exporter
689) # ========
690) 
691) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

692) @derivepassphrase.group(
693)     'export',
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

698)     },
699)     invoke_without_command=True,
700)     cls=_DefaultToVaultGroup,
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

785) 
786) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

787) @derivepassphrase_export.command(
788)     'vault',
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

896) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

931) 
932) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

938) 
939)     Returns:
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

955)     return data
956) 
957) 
Marco Ricci Permit one flaky test and f...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

996) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1052) 
1053)     Args:
1054)         conn:
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

1057) 
1058)     Yields:
Marco Ricci Convert old syntax for Yiel...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1061) 
1062)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1080) 
1081)     """
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1094) 
1095) 
1096) def _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

1153)     try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1165) 
1166) 
1167) def _select_ssh_key(
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1175) 
1176)     Args:
1177)         conn:
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1248) 
1249) 
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

1280) 
1281) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

1314)                 (
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

1319)                 formatted_key,
1320)                 form,
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 4 months ago

1322)             )
1323) 
1324) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1335) 
1336) class ConfigurationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1344) 
1345) class StorageManagementOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1352)     """
1353) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 weeks ago

1355) class CompatibilityOption(OptionGroupOption):
1356)     """Compatibility and incompatibility options for the CLI."""
1357) 
1358)     option_group_name = 'Options concerning compatibility with other tools'
1359) 
1360) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1361) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1366)     """Check that the occurrence constraint is valid (int, 0 or larger).
1367) 
1368)     Args:
1369)         ctx: The `click` context.
1370)         param: The current command-line parameter.
1371)         value: The parameter value to be checked.
1372) 
1373)     Returns:
1374)         The parsed parameter value.
1375) 
1376)     Raises:
1377)         click.BadParameter: The parameter value is invalid.
1378) 
1379)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1382)     if value is None:
1383)         return value
1384)     if isinstance(value, int):
1385)         int_value = value
1386)     else:
1387)         try:
1388)             int_value = int(value, 10)
1389)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1395)     return int_value
1396) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1397) 
1398) def _validate_length(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1403)     """Check that the length is valid (int, 1 or larger).
1404) 
1405)     Args:
1406)         ctx: The `click` context.
1407)         param: The current command-line parameter.
1408)         value: The parameter value to be checked.
1409) 
1410)     Returns:
1411)         The parsed parameter value.
1412) 
1413)     Raises:
1414)         click.BadParameter: The parameter value is invalid.
1415) 
1416)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1419)     if value is None:
1420)         return value
1421)     if isinstance(value, int):
1422)         int_value = value
1423)     else:
1424)         try:
1425)             int_value = int(value, 10)
1426)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1432)     return int_value
1433) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1434) 
1435) DEFAULT_NOTES_TEMPLATE = """\
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1436) # Enter notes below the line with the cut mark (ASCII scissors and
1437) # dashes).  Lines above the cut mark (such as this one) will be ignored.
1438) #
1439) # If you wish to clear the notes, leave everything beyond the cut mark
1440) # blank.  However, if you leave the *entire* file blank, also removing
1441) # the cut mark, then the edit is aborted, and the old notes contents are
1442) # retained.
1443) #
1444) # - - - - - >8 - - - - - >8 - - - - - >8 - - - - - >8 - - - - -
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1446) DEFAULT_NOTES_MARKER = '# - - - - - >8 - - - - -'
1447) 
1448) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

1449) @derivepassphrase.command(
1450)     'vault',
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1462)     """,
1463) )
1464) @click.option(
1465)     '-p',
1466)     '--phrase',
1467)     'use_phrase',
1468)     is_flag=True,
1469)     help='prompts you for your passphrase',
1470)     cls=PasswordGenerationOption,
1471) )
1472) @click.option(
1473)     '-k',
1474)     '--key',
1475)     'use_key',
1476)     is_flag=True,
1477)     help='uses your SSH private key to generate passwords',
1478)     cls=PasswordGenerationOption,
1479) )
1480) @click.option(
1481)     '-l',
1482)     '--length',
1483)     metavar='NUMBER',
1484)     callback=_validate_length,
1485)     help='emits password of length NUMBER',
1486)     cls=PasswordGenerationOption,
1487) )
1488) @click.option(
1489)     '-r',
1490)     '--repeat',
1491)     metavar='NUMBER',
1492)     callback=_validate_occurrence_constraint,
1493)     help='allows maximum of NUMBER repeated adjacent chars',
1494)     cls=PasswordGenerationOption,
1495) )
1496) @click.option(
1497)     '--lower',
1498)     metavar='NUMBER',
1499)     callback=_validate_occurrence_constraint,
1500)     help='includes at least NUMBER lowercase letters',
1501)     cls=PasswordGenerationOption,
1502) )
1503) @click.option(
1504)     '--upper',
1505)     metavar='NUMBER',
1506)     callback=_validate_occurrence_constraint,
1507)     help='includes at least NUMBER uppercase letters',
1508)     cls=PasswordGenerationOption,
1509) )
1510) @click.option(
1511)     '--number',
1512)     metavar='NUMBER',
1513)     callback=_validate_occurrence_constraint,
1514)     help='includes at least NUMBER digits',
1515)     cls=PasswordGenerationOption,
1516) )
1517) @click.option(
1518)     '--space',
1519)     metavar='NUMBER',
1520)     callback=_validate_occurrence_constraint,
1521)     help='includes at least NUMBER spaces',
1522)     cls=PasswordGenerationOption,
1523) )
1524) @click.option(
1525)     '--dash',
1526)     metavar='NUMBER',
1527)     callback=_validate_occurrence_constraint,
1528)     help='includes at least NUMBER "-" or "_"',
1529)     cls=PasswordGenerationOption,
1530) )
1531) @click.option(
1532)     '--symbol',
1533)     metavar='NUMBER',
1534)     callback=_validate_occurrence_constraint,
1535)     help='includes at least NUMBER symbol chars',
1536)     cls=PasswordGenerationOption,
1537) )
1538) @click.option(
1539)     '-n',
1540)     '--notes',
1541)     'edit_notes',
1542)     is_flag=True,
1543)     help='spawn an editor to edit notes for SERVICE',
1544)     cls=ConfigurationOption,
1545) )
1546) @click.option(
1547)     '-c',
1548)     '--config',
1549)     'store_config_only',
1550)     is_flag=True,
1551)     help='saves the given settings for SERVICE or global',
1552)     cls=ConfigurationOption,
1553) )
1554) @click.option(
1555)     '-x',
1556)     '--delete',
1557)     'delete_service_settings',
1558)     is_flag=True,
1559)     help='deletes settings for SERVICE',
1560)     cls=ConfigurationOption,
1561) )
1562) @click.option(
1563)     '--delete-globals',
1564)     is_flag=True,
1565)     help='deletes the global shared settings',
1566)     cls=ConfigurationOption,
1567) )
1568) @click.option(
1569)     '-X',
1570)     '--clear',
1571)     'clear_all_settings',
1572)     is_flag=True,
1573)     help='deletes all settings',
1574)     cls=ConfigurationOption,
1575) )
1576) @click.option(
1577)     '-e',
1578)     '--export',
1579)     'export_settings',
1580)     metavar='PATH',
1581)     help='export all saved settings into file PATH',
1582)     cls=StorageManagementOption,
1583) )
1584) @click.option(
1585)     '-i',
1586)     '--import',
1587)     'import_settings',
1588)     metavar='PATH',
1589)     help='import saved settings from file PATH',
1590)     cls=StorageManagementOption,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 weeks ago

1592) @click.option(
1593)     '--overwrite-existing/--merge-existing',
1594)     'overwrite_config',
1595)     default=False,
1596)     help='overwrite or merge (default) the existing configuration',
1597)     cls=CompatibilityOption,
1598) )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1604)     ctx: click.Context,
1605)     /,
1606)     *,
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1607)     service: str | None = None,
1608)     use_phrase: bool = False,
1609)     use_key: bool = False,
1610)     length: int | None = None,
1611)     repeat: int | None = None,
1612)     lower: int | None = None,
1613)     upper: int | None = None,
1614)     number: int | None = None,
1615)     space: int | None = None,
1616)     dash: int | None = None,
1617)     symbol: int | None = None,
1618)     edit_notes: bool = False,
1619)     store_config_only: bool = False,
1620)     delete_service_settings: bool = False,
1621)     delete_globals: bool = False,
1622)     clear_all_settings: bool = False,
1623)     export_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
1624)     import_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1625)     overwrite_config: bool = False,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1629)     Using a master passphrase or a master SSH key, derive a passphrase
1630)     for SERVICE, subject to length, character and character repetition
1631)     constraints.  The derivation is cryptographically strong, meaning
1632)     that even if a single passphrase is compromised, guessing the master
1633)     passphrase or a different service's passphrase is computationally
1634)     infeasible.  The derivation is also deterministic, given the same
1635)     inputs, thus the resulting passphrase need not be stored explicitly.
1636)     The service name and constraints themselves also need not be kept
1637)     secret; the latter are usually stored in a world-readable file.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1649) 
1650)     Parameters:
1651)         ctx (click.Context):
1652)             The `click` context.
1653) 
1654)     Other Parameters:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1707)         export_settings:
1708)             Command-line argument `-e`/`--export`.  If a file object,
1709)             then it must be open for writing and accept `str` inputs.
1710)             Otherwise, a filename to open for writing.  Using `-` for
1711)             standard output is supported.
1712)         import_settings:
1713)             Command-line argument `-i`/`--import`.  If a file object, it
1714)             must be open for reading and yield `str` values.  Otherwise,
1715)             a filename to open for reading.  Using `-` for standard
1716)             input is supported.
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1717)         overwrite_config:
1718)             Command-line arguments `--overwrite-existing` (True) and
1719)             `--merge-existing` (False).  Controls whether config saving
1720)             and config importing overwrite existing configurations, or
1721)             merge them section-wise instead.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

1731)             # Use match/case here once Python 3.9 becomes unsupported.
1732)             if isinstance(param, PasswordGenerationOption):
1733)                 group = PasswordGenerationOption
1734)             elif isinstance(param, ConfigurationOption):
1735)                 group = ConfigurationOption
1736)             elif isinstance(param, StorageManagementOption):
1737)                 group = StorageManagementOption
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 weeks ago

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

Marco Ricci authored 3 months ago

1742)             elif isinstance(param, OptionGroupOption):
1743)                 raise AssertionError(  # noqa: DOC501,TRY003,TRY004
1744)                     f'Unknown option group for {param!r}'  # noqa: EM102
1745)                 )
1746)             else:
1747)                 group = click.Option
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1748)             options_in_group.setdefault(group, []).append(param)
1749)         params_by_str[param.human_readable_name] = param
1750)         for name in param.opts + param.secondary_opts:
1751)             params_by_str[name] = param
1752) 
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1756)     def check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1760)         if isinstance(param, str):
1761)             param = params_by_str[param]
1762)         assert isinstance(param, click.Parameter)
1763)         if not is_param_set(param):
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

1764)             return
1765)         for other in incompatible:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1768)             assert isinstance(other, click.Parameter)
1769)             if other != param and is_param_set(other):
1770)                 opt_str = param.opts[0]
1771)                 other_str = other.opts[0]
1772)                 raise click.BadOptionUsage(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

1780)         ctx.exit(1)
1781) 
Marco Ricci Fix user interface errors i...

Marco Ricci authored 3 weeks ago

1782)     def key_to_phrase(key_: str | bytes | bytearray, /) -> bytes | bytearray:
1783)         key = base64.standard_b64decode(key_)
1784)         try:
1785)             with ssh_agent.SSHAgentClient.ensure_agent_subcontext() as client:
1786)                 try:
1787)                     return vault.Vault.phrase_from_key(key, conn=client)
1788)                 except ssh_agent.SSHAgentFailedError as e:
1789)                     try:
1790)                         keylist = client.list_keys()
1791)                     except ssh_agent.SSHAgentFailedError:
1792)                         pass
1793)                     except Exception as e2:  # noqa: BLE001
1794)                         e.__context__ = e2
1795)                     else:
1796)                         if not any(k == key for k, _ in keylist):
1797)                             err(
1798)                                 'The requested SSH key is not loaded '
1799)                                 'into the agent.'
1800)                             )
1801)                     err(e)
1802)         except KeyError:
1803)             err('Cannot find running SSH agent; check SSH_AUTH_SOCK')
1804)         except NotImplementedError:
1805)             err(
1806)                 'Cannot connect to SSH agent because '
1807)                 'this Python version does not support UNIX domain sockets'
1808)             )
1809)         except OSError as e:
1810)             err('Cannot connect to SSH agent: %s', e.strerror)
1811) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1813)         try:
1814)             return _load_config()
1815)         except FileNotFoundError:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1816)             try:
1817)                 backup_config, exc = _migrate_and_load_old_config()
1818)             except FileNotFoundError:
1819)                 return {'services': {}}
Marco Ricci Make obtaining the compatib...

Marco Ricci authored 3 weeks ago

1820)             old_name = os.path.basename(
1821)                 _config_filename(subsystem='old settings.json')
1822)             )
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

1831)                 old_name,
1832)                 new_name,
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

1835)                 logger.warning(
1836)                     'Failed to migrate to %r: %s: %r',
1837)                     new_name,
1838)                     exc.strerror,
1839)                     exc.filename,
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1840)                 )
1841)             else:
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

1848) 
1849)     def put_config(config: _types.VaultConfig, /) -> None:
1850)         try:
1851)             _save_config(config)
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 weeks ago

1857)     def get_user_config() -> dict[str, Any]:
1858)         try:
1859)             return _load_user_config()
1860)         except FileNotFoundError:
1861)             return {}
1862)         except OSError as e:
1863)             err('Cannot load user config: %s: %r', e.strerror, e.filename)
1864)         except Exception as e:  # noqa: BLE001
1865)             err('Cannot load user config: %s', str(e), exc_info=e)
1866) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1868) 
1869)     check_incompatible_options('--phrase', '--key')
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1874)                     opt, *options_in_group[PasswordGenerationOption]
1875)                 )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1880)                 opt,
1881)                 *options_in_group[ConfigurationOption],
1882)                 *options_in_group[StorageManagementOption],
1883)             )
Marco Ricci Correctly model vault globa...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

1891)             raise click.UsageError(msg)  # noqa: DOC501
1892)     sv_options = [params_by_str['--notes'], params_by_str['--delete']]
1893)     for param in sv_options:
1894)         if is_param_set(param) and not service:
1895)             opt_str = param.opts[0]
1896)             msg = f'{opt_str} requires a SERVICE'
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

1898)     no_sv_options = [
1899)         params_by_str['--delete-globals'],
1900)         params_by_str['--clear'],
1901)         *options_in_group[StorageManagementOption],
1902)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 weeks ago

1909)     user_config = get_user_config()
1910) 
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 2 months ago

1917)         )
1918) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1919)     if edit_notes:
1920)         assert service is not None
1921)         configuration = get_config()
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1928)             while notes_lines:
1929)                 line = notes_lines.popleft()
1930)                 if line.startswith(DEFAULT_NOTES_MARKER):
1931)                     notes_value = ''.join(notes_lines)
1932)                     break
1933)             else:
1934)                 if not notes_value.strip():
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1937)                 notes_value.strip('\n')
1938)             )
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1940)     elif delete_service_settings:
1941)         assert service is not None
1942)         configuration = get_config()
1943)         if service in configuration['services']:
1944)             del configuration['services'][service]
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1946)     elif delete_globals:
1947)         configuration = get_config()
1948)         if 'global' in configuration:
1949)             del configuration['global']
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1953)     elif import_settings:
1954)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

1957)             infile = (
1958)                 cast(TextIO, import_settings)
1959)                 if hasattr(import_settings, 'close')
1960)                 else click.open_file(os.fspath(import_settings), 'rt')
1961)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1962)             with infile:
1963)                 maybe_config = json.load(infile)
1964)         except json.JSONDecodeError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

1971)         assert cleaned is not None
1972)         for step in cleaned:
1973)             # These are never fatal errors, because the semantics of
1974)             # vault upon encountering these settings are ill-specified,
1975)             # but not ill-defined.
1976)             if step.action == 'replace':
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1977)                 logger.warning(
1978)                     'Replacing invalid value %s for key %s with %s.',
1979)                     json.dumps(step.old_value),
1980)                     _types.json_path(step.path),
1981)                     json.dumps(step.new_value),
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1982)                 )
1983)             else:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1984)                 logger.warning(
1985)                     'Removing ineffective setting %s = %s.',
1986)                     _types.json_path(step.path),
1987)                     json.dumps(step.old_value),
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

1990)             logger.warning(
1991)                 (
1992)                     'An empty SERVICE is not supported by vault(1), '
1993)                     'and the empty-string service settings will be '
1994)                     'inaccessible and ineffective.  To ensure that '
1995)                     'vault(1) and %s see the settings, move them '
1996)                     'into the "global" section.'
1997)                 ),
1998)                 PROG_NAME,
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

1999)             )
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 4 months ago

2005)             )
Marco Ricci Turn Unicode normalization...

Marco Ricci authored 3 weeks ago

2006)             for key, value in maybe_config['services'].items():
2007)                 _check_for_misleading_passphrase(
2008)                     ('services', key),
2009)                     cast(dict[str, Any], value),
2010)                     main_config=user_config,
2011)                 )
2012)         except AssertionError as e:
2013)             err('The configuration file is invalid.  ' + str(e))
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

2014)         if overwrite_config:
2015)             put_config(maybe_config)
2016)         else:
2017)             configuration = get_config()
2018)             merged_config: collections.ChainMap[str, Any] = (
2019)                 collections.ChainMap(
2020)                     {
2021)                         'services': collections.ChainMap(
2022)                             maybe_config['services'],
2023)                             configuration['services'],
2024)                         ),
2025)                     },
2026)                     {'global': maybe_config['global']}
2027)                     if 'global' in maybe_config
2028)                     else {},
2029)                     {'global': configuration['global']}
2030)                     if 'global' in configuration
2031)                     else {},
2032)                 )
2033)             )
2034)             new_config: Any = {
2035)                 k: dict(v) if isinstance(v, collections.ChainMap) else v
2036)                 for k, v in sorted(merged_config.items())
2037)             }
2038)             assert _types.is_vault_config(new_config)
2039)             put_config(new_config)
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2040)     elif export_settings:
2041)         configuration = get_config()
2042)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2045)             outfile = (
2046)                 cast(TextIO, export_settings)
2047)                 if hasattr(export_settings, 'close')
2048)                 else click.open_file(os.fspath(export_settings), 'wt')
2049)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2050)             with outfile:
2051)                 json.dump(configuration, outfile)
2052)         except OSError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

2061)         service_keys = {
2062)             'key',
2063)             'phrase',
2064)             'length',
2065)             'repeat',
2066)             'lower',
2067)             'upper',
2068)             'number',
2069)             'space',
2070)             'dash',
2071)             'symbol',
2072)         }
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

2074)             {
2075)                 k: v
2076)                 for k, v in locals().items()
2077)                 if k in service_keys and v is not None
2078)             },
2079)             cast(
2080)                 dict[str, Any],
2081)                 configuration['services'].get(service or '', {}),
2082)             ),
2083)             cast(dict[str, Any], configuration.get('global', {})),
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2084)         )
2085)         if use_key:
2086)             try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2087)                 key = base64.standard_b64encode(_select_ssh_key()).decode(
2088)                     'ASCII'
2089)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

2094)             except NotImplementedError:
2095)                 err(
2096)                     'Cannot connect to SSH agent because '
2097)                     'this Python version does not support UNIX domain sockets'
2098)                 )
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

2101)             except (
2102)                 LookupError,
2103)                 RuntimeError,
2104)                 ssh_agent.SSHAgentFailedError,
2105)             ) as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2107)         elif use_phrase:
2108)             maybe_phrase = _prompt_for_passphrase()
2109)             if not maybe_phrase:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2111)             else:
2112)                 phrase = maybe_phrase
2113)         if store_config_only:
2114)             view: collections.ChainMap[str, Any]
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2115)             view = (
2116)                 collections.ChainMap(*settings.maps[:2])
2117)                 if service
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

2120)             if use_key:
2121)                 view['key'] = key
2122)             elif use_phrase:
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 weeks ago

2125)                 try:
2126)                     _check_for_misleading_passphrase(
2127)                         ('services', service) if service else ('global',),
2128)                         {'phrase': phrase},
2129)                         main_config=user_config,
2130)                     )
2131)                 except AssertionError as e:
2132)                     err('The configuration file is invalid.  ' + str(e))
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

2133)                 if 'key' in settings:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

2134)                     logger.warning(
2135)                         (
2136)                             'Setting a %s passphrase is ineffective '
2137)                             'because a key is also set.'
2138)                         ),
2139)                         settings_type,
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2145)                     f'actual settings'
2146)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

2147)                 raise click.UsageError(msg)
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

2148)             subtree: dict[str, Any] = (
2149)                 configuration['services'].setdefault(service, {})  # type: ignore[assignment]
2150)                 if service
2151)                 else configuration.setdefault('global', {})
2152)             )
2153)             if overwrite_config:
2154)                 subtree.clear()
2155)             subtree.update(view)
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2160)         else:
2161)             if not service:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

2164)             kwargs: dict[str, Any] = {
2165)                 k: v
2166)                 for k, v in settings.items()
2167)                 if k in service_keys and v is not None
2168)             }
2169) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 weeks ago

2171)                 try:
2172)                     _check_for_misleading_passphrase(
2173)                         _ORIGIN.INTERACTIVE,
2174)                         {'phrase': phrase},
2175)                         main_config=user_config,
2176)                     )
2177)                 except AssertionError as e:
2178)                     err('The configuration file is invalid.  ' + str(e))
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

2190)             elif kwargs.get('phrase'):
2191)                 pass
2192)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2195)                     'or in configuration'
2196)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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