d15069d2db4040d444f65d7c3db6a854f4adcb92
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 Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

42) 
43) if TYPE_CHECKING:
44)     import pathlib
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

50)         Sequence,
51)     )
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

52) 
53) __author__ = dpp.__author__
54) __version__ = dpp.__version__
55) 
56) __all__ = ('derivepassphrase',)
57) 
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

60) 
61) # Error messages
62) _INVALID_VAULT_CONFIG = 'Invalid vault config'
63) _AGENT_COMMUNICATION_ERROR = 'Error communicating with the SSH agent'
64) _NO_USABLE_KEYS = 'No usable SSH keys were found'
65) _EMPTY_SELECTION = 'Empty selection'
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

66) 
67) 
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

347)     ctx: click.Context,
348)     /,
349)     param: click.Parameter | None = None,
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

357) 
358)     """
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

359)     # Note: If multiple options use this callback, then we will be
360)     # called multiple times.  Ensure the runs are idempotent.
361)     if param is None or value is None or ctx.resilient_parsing:
362)         return
363)     StandardCLILogging.cli_handler.setLevel(value)
364)     logging.getLogger(StandardCLILogging.package_name).setLevel(value)
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

365) 
366) 
Marco Ricci Shift option parsing and gr...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

466) class LoggingOption(OptionGroupOption):
467)     """Logging options for the CLI."""
468) 
469)     option_group_name = 'Logging'
470)     epilog = ''
471) 
472) 
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

522) 
523) 
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

524) # Top-level
525) # =========
526) 
527) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

572)             logger = logging.getLogger(PROG_NAME)
573)             deprecation = logging.getLogger(f'{PROG_NAME}.deprecation')
574)             deprecation.warning(
575)                 'A subcommand will be required in v1.0. '
576)                 'See --help for available subcommands.'
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

579)             cmd_name = 'vault'
580)             cmd = self.get_command(ctx, cmd_name)
581)             assert cmd is not None, 'Mandatory subcommand "vault" missing!'
582)             args = [cmd_name, *args]
583)         return cmd_name if cmd else None, cmd, args[1:]  # noqa: DOC201
584) 
585) 
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

672)         # See definition of click.Group.invoke, non-chained case.
673)         with ctx:
674)             sub_ctx = derivepassphrase_vault.make_context(
675)                 'vault', ctx.args, parent=ctx
676)             )
677)             with sub_ctx:
678)                 return derivepassphrase_vault.invoke(sub_ctx)
679)     return None
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

680) 
681) 
682) # Exporter
683) # ========
684) 
685) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

686) @derivepassphrase.group(
687)     'export',
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

688)     context_settings={
689)         'help_option_names': ['-h', '--help'],
690)         'ignore_unknown_options': True,
691)         'allow_interspersed_args': False,
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

692)     },
693)     invoke_without_command=True,
694)     cls=_DefaultToVaultGroup,
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

740) 
741) 
742) def _load_data(
743)     fmt: Literal['v0.2', 'v0.3', 'storeroom'],
744)     path: str | bytes | os.PathLike[str],
745)     key: bytes,
746) ) -> Any:  # noqa: ANN401
747)     contents: bytes
748)     module: types.ModuleType
Marco Ricci Add support for Python 3.9

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

779) 
780) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

781) @derivepassphrase_export.command(
782)     'vault',
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

849)             logger.error(
850)                 'Cannot parse %r as a valid config: %s: %r',
851)                 path,
852)                 exc.strerror,
853)                 exc.filename,
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

854)             )
855)             ctx.exit(1)
856)         except ModuleNotFoundError:
857)             # TODO(the-13th-letter): Use backslash continuation.
858)             # https://github.com/nedbat/coveragepy/issues/1836
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

859)             logger.error(
860)                 'Cannot load the required Python module "cryptography".'
861)             )
862)             logger.info('pip users: see the "export" extra.')
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

863)             ctx.exit(1)
864)         else:
865)             if not _types.is_vault_config(config):
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

867)                 ctx.exit(1)
868)             click.echo(json.dumps(config, indent=2, sort_keys=True))
869)             break
870)     else:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

872)         ctx.exit(1)
873) 
874) 
875) # Vault
876) # =====
877) 
878) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

879) def _config_filename(
880)     subsystem: str | None = 'settings',
881) ) -> str | bytes | pathlib.Path:
882)     """Return the filename of the configuration file for the subsystem.
883) 
884)     The (implicit default) file is currently named `settings.json`,
885)     located within the configuration directory as determined by the
886)     `DERIVEPASSPHRASE_PATH` environment variable, or by
887)     [`click.get_app_dir`][] in POSIX mode.  Depending on the requested
888)     subsystem, this will usually be a different file within that
889)     directory.
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

890) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

906) 
907)     """
908)     path: str | bytes | pathlib.Path
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

912)     # Use match/case here once Python 3.9 becomes unsupported.
913)     if subsystem is None:
914)         return path
915)     elif subsystem in {'vault', 'settings'}:  # noqa: RET505
916)         filename = f'{subsystem}.json'
917)     else:  # pragma: no cover
918)         msg = f'Unknown configuration subsystem: {subsystem!r}'
919)         raise AssertionError(msg)
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

921) 
922) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

928) 
929)     Returns:
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

931) 
932)     Raises:
933)         OSError:
934)             There was an OS error accessing the file.
935)         ValueError:
936)             The data loaded from the file is not a vault(1)-compatible
937)             config.
938) 
939)     """
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

945)     return data
946) 
947) 
Marco Ricci Permit one flaky test and f...

Marco Ricci authored 3 months ago

948) def _migrate_and_load_old_config() -> tuple[
949)     _types.VaultConfig, OSError | None
950) ]:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

956) 
957)     Returns:
958)         The vault settings, and an optional exception encountered during
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

961) 
962)     Raises:
963)         OSError:
964)             There was an OS error accessing the old file.
965)         ValueError:
966)             The data loaded from the file is not a vault(1)-compatible
967)             config.
968) 
969)     """
970)     new_filename = _config_filename(subsystem='vault')
971)     old_filename = _config_filename()
972)     with open(old_filename, 'rb') as fileobj:
973)         data = json.load(fileobj)
974)     if not _types.is_vault_config(data):
975)         raise ValueError(_INVALID_VAULT_CONFIG)
976)     try:
977)         os.replace(old_filename, new_filename)
978)     except OSError as exc:
979)         return data, exc
980)     else:
981)         return data, None
982) 
983) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

986) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

989) 
990)     Args:
991)         config:
992)             vault configuration to save.
993) 
994)     Raises:
995)         OSError:
996)             There was an OS error accessing or writing the file.
997)         ValueError:
998)             The data cannot be stored as a vault(1)-compatible config.
999) 
1000)     """
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1004)     filedir = os.path.dirname(os.path.abspath(filename))
1005)     try:
1006)         os.makedirs(filedir, exist_ok=False)
1007)     except FileExistsError:
1008)         if not os.path.isdir(filedir):
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1011)         json.dump(config, fileobj)
1012) 
1013) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1021) 
1022)     Args:
1023)         conn:
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

1026) 
1027)     Yields:
Marco Ricci Convert old syntax for Yiel...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1030) 
1031)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

1032)         KeyError:
1033)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
1034)             variable was not found.
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1049) 
1050)     """
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

1056)         suitable_keys = copy.copy(all_key_comment_pairs)
1057)         for pair in all_key_comment_pairs:
1058)             key, _comment = pair
1059)             if vault.Vault.is_suitable_ssh_key(key, client=client):
1060)                 yield pair
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1063) 
1064) 
1065) def _prompt_for_selection(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1068)     single_choice_prompt: str = 'Confirm this choice?',
1069) ) -> int:
1070)     """Prompt user for a choice among the given items.
1071) 
1072)     Print the heading, if any, then present the items to the user.  If
1073)     there are multiple items, prompt the user for a selection, validate
1074)     the choice, then return the list index of the selected item.  If
1075)     there is only a single item, request confirmation for that item
1076)     instead, and return the correct index.
1077) 
1078)     Args:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1081)         heading:
1082)             A heading for the list of items, to print immediately
1083)             before.  Defaults to a reasonable standard heading.  If
1084)             explicitly empty, print no heading.
1085)         single_choice_prompt:
1086)             The confirmation prompt if there is only a single possible
1087)             choice.  Defaults to a reasonable standard prompt.
1088) 
1089)     Returns:
1090)         An index into the items sequence, indicating the user's
1091)         selection.
1092) 
1093)     Raises:
1094)         IndexError:
1095)             The user made an invalid or empty selection, or requested an
1096)             abort.
1097) 
1098)     """
1099)     n = len(items)
1100)     if heading:
1101)         click.echo(click.style(heading, bold=True))
1102)     for i, x in enumerate(items, start=1):
1103)         click.echo(click.style(f'[{i}]', bold=True), nl=False)
1104)         click.echo(' ', nl=False)
1105)         click.echo(x)
1106)     if n > 1:
1107)         choices = click.Choice([''] + [str(i) for i in range(1, n + 1)])
1108)         choice = click.prompt(
1109)             f'Your selection? (1-{n}, leave empty to abort)',
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1110)             err=True,
1111)             type=choices,
1112)             show_choices=False,
1113)             show_default=False,
1114)             default='',
1115)         )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1119)     prompt_suffix = (
1120)         ' ' if single_choice_prompt.endswith(tuple('?.!')) else ': '
1121)     )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

1122)     try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1123)         click.confirm(
1124)             single_choice_prompt,
1125)             prompt_suffix=prompt_suffix,
1126)             err=True,
1127)             abort=True,
1128)             default=False,
1129)             show_default=False,
1130)         )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

1131)     except click.Abort:
1132)         raise IndexError(_EMPTY_SELECTION) from None
1133)     return 0
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1134) 
1135) 
1136) def _select_ssh_key(
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1144) 
1145)     Args:
1146)         conn:
Marco Ricci Support one-off SSH agent c...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

1149) 
1150)     Returns:
1151)         The selected SSH key.
1152) 
1153)     Raises:
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

1154)         KeyError:
1155)             `conn` was `None`, and the `SSH_AUTH_SOCK` environment
1156)             variable was not found.
Marco Ricci Fail gracefully if UNIX dom...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1164)         IndexError:
1165)             The user made an invalid or empty selection, or requested an
1166)             abort.
Marco Ricci Distinguish between a key l...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1174)     """
1175)     suitable_keys = list(_get_suitable_ssh_keys(conn))
1176)     key_listing: list[str] = []
Marco Ricci Move `sequin` and `ssh_agen...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

1181)         remaining_key_display_length = KEY_DISPLAY_LENGTH - 1 - len(keytype)
1182)         key_extract = min(
1183)             key_str,
1184)             '...' + key_str[-remaining_key_display_length:],
1185)             key=len,
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1190)         key_listing,
1191)         heading='Suitable SSH keys:',
1192)         single_choice_prompt='Use this key?',
1193)     )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1194)     return suitable_keys[choice].key
1195) 
1196) 
1197) def _prompt_for_passphrase() -> str:
1198)     """Interactively prompt for the passphrase.
1199) 
1200)     Calls [`click.prompt`][] internally.  Moved into a separate function
1201)     mainly for testing/mocking purposes.
1202) 
1203)     Returns:
1204)         The user input.
1205) 
1206)     """
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

1207)     return cast(
1208)         str,
1209)         click.prompt(
1210)             'Passphrase',
1211)             default='',
1212)             hide_input=True,
1213)             show_default=False,
1214)             err=True,
1215)         ),
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1217) 
1218) 
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1219) class _ORIGIN(enum.Enum):
1220)     INTERACTIVE: str = 'interactive'
1221) 
1222) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1225)     value: dict[str, Any],
1226)     *,
1227)     form: Literal['NFC', 'NFD', 'NFKC', 'NFKD'] = 'NFC',
1228) ) -> None:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1229)     logger = logging.getLogger(PROG_NAME)
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

1230)     if 'phrase' in value:
1231)         phrase = value['phrase']
1232)         if not unicodedata.is_normalized(form, phrase):
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1233)             formatted_key = (
1234)                 key.value
1235)                 if isinstance(key, _ORIGIN)
1236)                 else _types.json_path(key)
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

1240)                     'the %s passphrase is not %s-normalized. '
1241)                     'Make sure to double-check this is really the '
1242)                     'passphrase you want.'
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

1244)                 formatted_key,
1245)                 form,
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

1246)             )
1247) 
1248) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1259) 
1260) class ConfigurationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1268) 
1269) class StorageManagementOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1276)     """
1277) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 weeks ago

1279) class CompatibilityOption(OptionGroupOption):
1280)     """Compatibility and incompatibility options for the CLI."""
1281) 
1282)     option_group_name = 'Options concerning compatibility with other tools'
1283) 
1284) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1285) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1290)     """Check that the occurrence constraint is valid (int, 0 or larger).
1291) 
1292)     Args:
1293)         ctx: The `click` context.
1294)         param: The current command-line parameter.
1295)         value: The parameter value to be checked.
1296) 
1297)     Returns:
1298)         The parsed parameter value.
1299) 
1300)     Raises:
1301)         click.BadParameter: The parameter value is invalid.
1302) 
1303)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1306)     if value is None:
1307)         return value
1308)     if isinstance(value, int):
1309)         int_value = value
1310)     else:
1311)         try:
1312)             int_value = int(value, 10)
1313)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1319)     return int_value
1320) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1321) 
1322) def _validate_length(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1327)     """Check that the length is valid (int, 1 or larger).
1328) 
1329)     Args:
1330)         ctx: The `click` context.
1331)         param: The current command-line parameter.
1332)         value: The parameter value to be checked.
1333) 
1334)     Returns:
1335)         The parsed parameter value.
1336) 
1337)     Raises:
1338)         click.BadParameter: The parameter value is invalid.
1339) 
1340)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1343)     if value is None:
1344)         return value
1345)     if isinstance(value, int):
1346)         int_value = value
1347)     else:
1348)         try:
1349)             int_value = int(value, 10)
1350)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1356)     return int_value
1357) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1358) 
1359) DEFAULT_NOTES_TEMPLATE = """\
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1360) # Enter notes below the line with the cut mark (ASCII scissors and
1361) # dashes).  Lines above the cut mark (such as this one) will be ignored.
1362) #
1363) # If you wish to clear the notes, leave everything beyond the cut mark
1364) # blank.  However, if you leave the *entire* file blank, also removing
1365) # the cut mark, then the edit is aborted, and the old notes contents are
1366) # retained.
1367) #
1368) # - - - - - >8 - - - - - >8 - - - - - >8 - - - - - >8 - - - - -
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1370) DEFAULT_NOTES_MARKER = '# - - - - - >8 - - - - -'
1371) 
1372) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

1373) @derivepassphrase.command(
1374)     'vault',
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1386)     """,
1387) )
1388) @click.option(
1389)     '-p',
1390)     '--phrase',
1391)     'use_phrase',
1392)     is_flag=True,
1393)     help='prompts you for your passphrase',
1394)     cls=PasswordGenerationOption,
1395) )
1396) @click.option(
1397)     '-k',
1398)     '--key',
1399)     'use_key',
1400)     is_flag=True,
1401)     help='uses your SSH private key to generate passwords',
1402)     cls=PasswordGenerationOption,
1403) )
1404) @click.option(
1405)     '-l',
1406)     '--length',
1407)     metavar='NUMBER',
1408)     callback=_validate_length,
1409)     help='emits password of length NUMBER',
1410)     cls=PasswordGenerationOption,
1411) )
1412) @click.option(
1413)     '-r',
1414)     '--repeat',
1415)     metavar='NUMBER',
1416)     callback=_validate_occurrence_constraint,
1417)     help='allows maximum of NUMBER repeated adjacent chars',
1418)     cls=PasswordGenerationOption,
1419) )
1420) @click.option(
1421)     '--lower',
1422)     metavar='NUMBER',
1423)     callback=_validate_occurrence_constraint,
1424)     help='includes at least NUMBER lowercase letters',
1425)     cls=PasswordGenerationOption,
1426) )
1427) @click.option(
1428)     '--upper',
1429)     metavar='NUMBER',
1430)     callback=_validate_occurrence_constraint,
1431)     help='includes at least NUMBER uppercase letters',
1432)     cls=PasswordGenerationOption,
1433) )
1434) @click.option(
1435)     '--number',
1436)     metavar='NUMBER',
1437)     callback=_validate_occurrence_constraint,
1438)     help='includes at least NUMBER digits',
1439)     cls=PasswordGenerationOption,
1440) )
1441) @click.option(
1442)     '--space',
1443)     metavar='NUMBER',
1444)     callback=_validate_occurrence_constraint,
1445)     help='includes at least NUMBER spaces',
1446)     cls=PasswordGenerationOption,
1447) )
1448) @click.option(
1449)     '--dash',
1450)     metavar='NUMBER',
1451)     callback=_validate_occurrence_constraint,
1452)     help='includes at least NUMBER "-" or "_"',
1453)     cls=PasswordGenerationOption,
1454) )
1455) @click.option(
1456)     '--symbol',
1457)     metavar='NUMBER',
1458)     callback=_validate_occurrence_constraint,
1459)     help='includes at least NUMBER symbol chars',
1460)     cls=PasswordGenerationOption,
1461) )
1462) @click.option(
1463)     '-n',
1464)     '--notes',
1465)     'edit_notes',
1466)     is_flag=True,
1467)     help='spawn an editor to edit notes for SERVICE',
1468)     cls=ConfigurationOption,
1469) )
1470) @click.option(
1471)     '-c',
1472)     '--config',
1473)     'store_config_only',
1474)     is_flag=True,
1475)     help='saves the given settings for SERVICE or global',
1476)     cls=ConfigurationOption,
1477) )
1478) @click.option(
1479)     '-x',
1480)     '--delete',
1481)     'delete_service_settings',
1482)     is_flag=True,
1483)     help='deletes settings for SERVICE',
1484)     cls=ConfigurationOption,
1485) )
1486) @click.option(
1487)     '--delete-globals',
1488)     is_flag=True,
1489)     help='deletes the global shared settings',
1490)     cls=ConfigurationOption,
1491) )
1492) @click.option(
1493)     '-X',
1494)     '--clear',
1495)     'clear_all_settings',
1496)     is_flag=True,
1497)     help='deletes all settings',
1498)     cls=ConfigurationOption,
1499) )
1500) @click.option(
1501)     '-e',
1502)     '--export',
1503)     'export_settings',
1504)     metavar='PATH',
1505)     help='export all saved settings into file PATH',
1506)     cls=StorageManagementOption,
1507) )
1508) @click.option(
1509)     '-i',
1510)     '--import',
1511)     'import_settings',
1512)     metavar='PATH',
1513)     help='import saved settings from file PATH',
1514)     cls=StorageManagementOption,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 weeks ago

1516) @click.option(
1517)     '--overwrite-existing/--merge-existing',
1518)     'overwrite_config',
1519)     default=False,
1520)     help='overwrite or merge (default) the existing configuration',
1521)     cls=CompatibilityOption,
1522) )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1528)     ctx: click.Context,
1529)     /,
1530)     *,
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1531)     service: str | None = None,
1532)     use_phrase: bool = False,
1533)     use_key: bool = False,
1534)     length: int | None = None,
1535)     repeat: int | None = None,
1536)     lower: int | None = None,
1537)     upper: int | None = None,
1538)     number: int | None = None,
1539)     space: int | None = None,
1540)     dash: int | None = None,
1541)     symbol: int | None = None,
1542)     edit_notes: bool = False,
1543)     store_config_only: bool = False,
1544)     delete_service_settings: bool = False,
1545)     delete_globals: bool = False,
1546)     clear_all_settings: bool = False,
1547)     export_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
1548)     import_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1553)     Using a master passphrase or a master SSH key, derive a passphrase
1554)     for SERVICE, subject to length, character and character repetition
1555)     constraints.  The derivation is cryptographically strong, meaning
1556)     that even if a single passphrase is compromised, guessing the master
1557)     passphrase or a different service's passphrase is computationally
1558)     infeasible.  The derivation is also deterministic, given the same
1559)     inputs, thus the resulting passphrase need not be stored explicitly.
1560)     The service name and constraints themselves also need not be kept
1561)     secret; the latter are usually stored in a world-readable file.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1573) 
1574)     Parameters:
1575)         ctx (click.Context):
1576)             The `click` context.
1577) 
1578)     Other Parameters:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1631)         export_settings:
1632)             Command-line argument `-e`/`--export`.  If a file object,
1633)             then it must be open for writing and accept `str` inputs.
1634)             Otherwise, a filename to open for writing.  Using `-` for
1635)             standard output is supported.
1636)         import_settings:
1637)             Command-line argument `-i`/`--import`.  If a file object, it
1638)             must be open for reading and yield `str` values.  Otherwise,
1639)             a filename to open for reading.  Using `-` for standard
1640)             input is supported.
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1641)         overwrite_config:
1642)             Command-line arguments `--overwrite-existing` (True) and
1643)             `--merge-existing` (False).  Controls whether config saving
1644)             and config importing overwrite existing configurations, or
1645)             merge them section-wise instead.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

1655)             # Use match/case here once Python 3.9 becomes unsupported.
1656)             if isinstance(param, PasswordGenerationOption):
1657)                 group = PasswordGenerationOption
1658)             elif isinstance(param, ConfigurationOption):
1659)                 group = ConfigurationOption
1660)             elif isinstance(param, StorageManagementOption):
1661)                 group = StorageManagementOption
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 weeks ago

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

Marco Ricci authored 3 months ago

1666)             elif isinstance(param, OptionGroupOption):
1667)                 raise AssertionError(  # noqa: DOC501,TRY003,TRY004
1668)                     f'Unknown option group for {param!r}'  # noqa: EM102
1669)                 )
1670)             else:
1671)                 group = click.Option
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1672)             options_in_group.setdefault(group, []).append(param)
1673)         params_by_str[param.human_readable_name] = param
1674)         for name in param.opts + param.secondary_opts:
1675)             params_by_str[name] = param
1676) 
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1680)     def check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1684)         if isinstance(param, str):
1685)             param = params_by_str[param]
1686)         assert isinstance(param, click.Parameter)
1687)         if not is_param_set(param):
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

1688)             return
1689)         for other in incompatible:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1692)             assert isinstance(other, click.Parameter)
1693)             if other != param and is_param_set(other):
1694)                 opt_str = param.opts[0]
1695)                 other_str = other.opts[0]
1696)                 raise click.BadOptionUsage(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

1704)         ctx.exit(1)
1705) 
Marco Ricci Fix user interface errors i...

Marco Ricci authored 3 weeks ago

1706)     def key_to_phrase(key_: str | bytes | bytearray, /) -> bytes | bytearray:
1707)         key = base64.standard_b64decode(key_)
1708)         try:
1709)             with ssh_agent.SSHAgentClient.ensure_agent_subcontext() as client:
1710)                 try:
1711)                     return vault.Vault.phrase_from_key(key, conn=client)
1712)                 except ssh_agent.SSHAgentFailedError as e:
1713)                     try:
1714)                         keylist = client.list_keys()
1715)                     except ssh_agent.SSHAgentFailedError:
1716)                         pass
1717)                     except Exception as e2:  # noqa: BLE001
1718)                         e.__context__ = e2
1719)                     else:
1720)                         if not any(k == key for k, _ in keylist):
1721)                             err(
1722)                                 'The requested SSH key is not loaded '
1723)                                 'into the agent.'
1724)                             )
1725)                     err(e)
1726)         except KeyError:
1727)             err('Cannot find running SSH agent; check SSH_AUTH_SOCK')
1728)         except NotImplementedError:
1729)             err(
1730)                 'Cannot connect to SSH agent because '
1731)                 'this Python version does not support UNIX domain sockets'
1732)             )
1733)         except OSError as e:
1734)             err('Cannot connect to SSH agent: %s', e.strerror)
1735) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1737)         try:
1738)             return _load_config()
1739)         except FileNotFoundError:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1740)             try:
1741)                 backup_config, exc = _migrate_and_load_old_config()
1742)             except FileNotFoundError:
1743)                 return {'services': {}}
1744)             old_name = os.path.basename(_config_filename())
1745)             new_name = os.path.basename(_config_filename(subsystem='vault'))
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

1753)                 old_name,
1754)                 new_name,
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

1757)                 logger.warning(
1758)                     'Failed to migrate to %r: %s: %r',
1759)                     new_name,
1760)                     exc.strerror,
1761)                     exc.filename,
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1762)                 )
1763)             else:
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

1770) 
1771)     def put_config(config: _types.VaultConfig, /) -> None:
1772)         try:
1773)             _save_config(config)
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1780) 
1781)     check_incompatible_options('--phrase', '--key')
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1786)                     opt, *options_in_group[PasswordGenerationOption]
1787)                 )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1792)                 opt,
1793)                 *options_in_group[ConfigurationOption],
1794)                 *options_in_group[StorageManagementOption],
1795)             )
Marco Ricci Correctly model vault globa...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

1803)             raise click.UsageError(msg)  # noqa: DOC501
1804)     sv_options = [params_by_str['--notes'], params_by_str['--delete']]
1805)     for param in sv_options:
1806)         if is_param_set(param) and not service:
1807)             opt_str = param.opts[0]
1808)             msg = f'{opt_str} requires a SERVICE'
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

1810)     no_sv_options = [
1811)         params_by_str['--delete-globals'],
1812)         params_by_str['--clear'],
1813)         *options_in_group[StorageManagementOption],
1814)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 2 months ago

1827)         )
1828) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1829)     if edit_notes:
1830)         assert service is not None
1831)         configuration = get_config()
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1838)             while notes_lines:
1839)                 line = notes_lines.popleft()
1840)                 if line.startswith(DEFAULT_NOTES_MARKER):
1841)                     notes_value = ''.join(notes_lines)
1842)                     break
1843)             else:
1844)                 if not notes_value.strip():
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1847)                 notes_value.strip('\n')
1848)             )
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1850)     elif delete_service_settings:
1851)         assert service is not None
1852)         configuration = get_config()
1853)         if service in configuration['services']:
1854)             del configuration['services'][service]
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1856)     elif delete_globals:
1857)         configuration = get_config()
1858)         if 'global' in configuration:
1859)             del configuration['global']
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1863)     elif import_settings:
1864)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

1867)             infile = (
1868)                 cast(TextIO, import_settings)
1869)                 if hasattr(import_settings, 'close')
1870)                 else click.open_file(os.fspath(import_settings), 'rt')
1871)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1872)             with infile:
1873)                 maybe_config = json.load(infile)
1874)         except json.JSONDecodeError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

1881)         assert cleaned is not None
1882)         for step in cleaned:
1883)             # These are never fatal errors, because the semantics of
1884)             # vault upon encountering these settings are ill-specified,
1885)             # but not ill-defined.
1886)             if step.action == 'replace':
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1887)                 logger.warning(
1888)                     'Replacing invalid value %s for key %s with %s.',
1889)                     json.dumps(step.old_value),
1890)                     _types.json_path(step.path),
1891)                     json.dumps(step.new_value),
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1892)                 )
1893)             else:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1894)                 logger.warning(
1895)                     'Removing ineffective setting %s = %s.',
1896)                     _types.json_path(step.path),
1897)                     json.dumps(step.old_value),
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

1900)             logger.warning(
1901)                 (
1902)                     'An empty SERVICE is not supported by vault(1), '
1903)                     'and the empty-string service settings will be '
1904)                     'inaccessible and ineffective.  To ensure that '
1905)                     'vault(1) and %s see the settings, move them '
1906)                     'into the "global" section.'
1907)                 ),
1908)                 PROG_NAME,
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

1909)             )
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1910)         form = cast(
1911)             Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1912)             maybe_config.get('global', {}).get(
1913)                 'unicode_normalization_form', 'NFC'
1914)             ),
1915)         )
1916)         assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1917)         _check_for_misleading_passphrase(
1918)             ('global',),
1919)             cast(dict[str, Any], maybe_config.get('global', {})),
1920)             form=form,
1921)         )
1922)         for key, value in maybe_config['services'].items():
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1926)                 form=form,
1927)             )
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1928)         if overwrite_config:
1929)             put_config(maybe_config)
1930)         else:
1931)             configuration = get_config()
1932)             merged_config: collections.ChainMap[str, Any] = (
1933)                 collections.ChainMap(
1934)                     {
1935)                         'services': collections.ChainMap(
1936)                             maybe_config['services'],
1937)                             configuration['services'],
1938)                         ),
1939)                     },
1940)                     {'global': maybe_config['global']}
1941)                     if 'global' in maybe_config
1942)                     else {},
1943)                     {'global': configuration['global']}
1944)                     if 'global' in configuration
1945)                     else {},
1946)                 )
1947)             )
1948)             new_config: Any = {
1949)                 k: dict(v) if isinstance(v, collections.ChainMap) else v
1950)                 for k, v in sorted(merged_config.items())
1951)             }
1952)             assert _types.is_vault_config(new_config)
1953)             put_config(new_config)
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1954)     elif export_settings:
1955)         configuration = get_config()
1956)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

1959)             outfile = (
1960)                 cast(TextIO, export_settings)
1961)                 if hasattr(export_settings, 'close')
1962)                 else click.open_file(os.fspath(export_settings), 'wt')
1963)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1964)             with outfile:
1965)                 json.dump(configuration, outfile)
1966)         except OSError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1975)         service_keys = {
1976)             'key',
1977)             'phrase',
1978)             'length',
1979)             'repeat',
1980)             'lower',
1981)             'upper',
1982)             'number',
1983)             'space',
1984)             'dash',
1985)             'symbol',
1986)         }
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1988)             {
1989)                 k: v
1990)                 for k, v in locals().items()
1991)                 if k in service_keys and v is not None
1992)             },
1993)             cast(
1994)                 dict[str, Any],
1995)                 configuration['services'].get(service or '', {}),
1996)             ),
1997)             cast(dict[str, Any], configuration.get('global', {})),
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1998)         )
1999)         if use_key:
2000)             try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2001)                 key = base64.standard_b64encode(_select_ssh_key()).decode(
2002)                     'ASCII'
2003)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

2008)             except NotImplementedError:
2009)                 err(
2010)                     'Cannot connect to SSH agent because '
2011)                     'this Python version does not support UNIX domain sockets'
2012)                 )
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

2015)             except (
2016)                 LookupError,
2017)                 RuntimeError,
2018)                 ssh_agent.SSHAgentFailedError,
2019)             ) as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2021)         elif use_phrase:
2022)             maybe_phrase = _prompt_for_passphrase()
2023)             if not maybe_phrase:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2025)             else:
2026)                 phrase = maybe_phrase
2027)         if store_config_only:
2028)             view: collections.ChainMap[str, Any]
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2029)             view = (
2030)                 collections.ChainMap(*settings.maps[:2])
2031)                 if service
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

2034)             if use_key:
2035)                 view['key'] = key
2036)             elif use_phrase:
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

2039)                 _check_for_misleading_passphrase(
2040)                     ('services', service) if service else ('global',),
2041)                     {'phrase': phrase},
2042)                 )
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

2044)                     logger.warning(
2045)                         (
2046)                             'Setting a %s passphrase is ineffective '
2047)                             'because a key is also set.'
2048)                         ),
2049)                         settings_type,
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2055)                     f'actual settings'
2056)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 weeks ago

2058)             subtree: dict[str, Any] = (
2059)                 configuration['services'].setdefault(service, {})  # type: ignore[assignment]
2060)                 if service
2061)                 else configuration.setdefault('global', {})
2062)             )
2063)             if overwrite_config:
2064)                 subtree.clear()
2065)             subtree.update(view)
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2070)         else:
2071)             if not service:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

2074)             kwargs: dict[str, Any] = {
2075)                 k: v
2076)                 for k, v in settings.items()
2077)                 if k in service_keys and v is not None
2078)             }
2079) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

2080)             if use_phrase:
2081)                 form = cast(
2082)                     Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
2083)                     configuration.get('global', {}).get(
2084)                         'unicode_normalization_form', 'NFC'
2085)                     ),
2086)                 )
2087)                 assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
2088)                 _check_for_misleading_passphrase(
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

2090)                 )
2091) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

2102)             elif kwargs.get('phrase'):
2103)                 pass
2104)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2107)                     'or in configuration'
2108)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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