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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

14) import enum
Marco Ricci Reintegrate all functionali...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

896) 
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

996) 
Marco Ricci Generate nicer documentatio...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

1153)     try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1248) 
1249) 
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1250) class _ORIGIN(enum.Enum):
1251)     INTERACTIVE: str = 'interactive'
1252) 
1253) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1256)     value: dict[str, Any],
1257)     *,
1258)     form: Literal['NFC', 'NFD', 'NFKC', 'NFKD'] = 'NFC',
1259) ) -> None:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

1261)     if 'phrase' in value:
1262)         phrase = value['phrase']
1263)         if not unicodedata.is_normalized(form, phrase):
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1264)             formatted_key = (
1265)                 key.value
1266)                 if isinstance(key, _ORIGIN)
1267)                 else _types.json_path(key)
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

1275)                 formatted_key,
1276)                 form,
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

1277)             )
1278) 
1279) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1290) 
1291) class ConfigurationOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1299) 
1300) class StorageManagementOption(OptionGroupOption):
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1307)     """
1308) 
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 weeks ago

1310) class CompatibilityOption(OptionGroupOption):
1311)     """Compatibility and incompatibility options for the CLI."""
1312) 
1313)     option_group_name = 'Options concerning compatibility with other tools'
1314) 
1315) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1316) def _validate_occurrence_constraint(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1321)     """Check that the occurrence constraint is valid (int, 0 or larger).
1322) 
1323)     Args:
1324)         ctx: The `click` context.
1325)         param: The current command-line parameter.
1326)         value: The parameter value to be checked.
1327) 
1328)     Returns:
1329)         The parsed parameter value.
1330) 
1331)     Raises:
1332)         click.BadParameter: The parameter value is invalid.
1333) 
1334)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1337)     if value is None:
1338)         return value
1339)     if isinstance(value, int):
1340)         int_value = value
1341)     else:
1342)         try:
1343)             int_value = int(value, 10)
1344)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1350)     return int_value
1351) 
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1352) 
1353) def _validate_length(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

1358)     """Check that the length is valid (int, 1 or larger).
1359) 
1360)     Args:
1361)         ctx: The `click` context.
1362)         param: The current command-line parameter.
1363)         value: The parameter value to be checked.
1364) 
1365)     Returns:
1366)         The parsed parameter value.
1367) 
1368)     Raises:
1369)         click.BadParameter: The parameter value is invalid.
1370) 
1371)     """
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1374)     if value is None:
1375)         return value
1376)     if isinstance(value, int):
1377)         int_value = value
1378)     else:
1379)         try:
1380)             int_value = int(value, 10)
1381)         except ValueError as e:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1387)     return int_value
1388) 
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

1389) 
1390) DEFAULT_NOTES_TEMPLATE = """\
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1391) # Enter notes below the line with the cut mark (ASCII scissors and
1392) # dashes).  Lines above the cut mark (such as this one) will be ignored.
1393) #
1394) # If you wish to clear the notes, leave everything beyond the cut mark
1395) # blank.  However, if you leave the *entire* file blank, also removing
1396) # the cut mark, then the edit is aborted, and the old notes contents are
1397) # retained.
1398) #
1399) # - - - - - >8 - - - - - >8 - - - - - >8 - - - - - >8 - - - - -
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1401) DEFAULT_NOTES_MARKER = '# - - - - - >8 - - - - -'
1402) 
1403) 
Marco Ricci Reimplement deprecated subc...

Marco Ricci authored 1 month ago

1404) @derivepassphrase.command(
1405)     'vault',
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1417)     """,
1418) )
1419) @click.option(
1420)     '-p',
1421)     '--phrase',
1422)     'use_phrase',
1423)     is_flag=True,
1424)     help='prompts you for your passphrase',
1425)     cls=PasswordGenerationOption,
1426) )
1427) @click.option(
1428)     '-k',
1429)     '--key',
1430)     'use_key',
1431)     is_flag=True,
1432)     help='uses your SSH private key to generate passwords',
1433)     cls=PasswordGenerationOption,
1434) )
1435) @click.option(
1436)     '-l',
1437)     '--length',
1438)     metavar='NUMBER',
1439)     callback=_validate_length,
1440)     help='emits password of length NUMBER',
1441)     cls=PasswordGenerationOption,
1442) )
1443) @click.option(
1444)     '-r',
1445)     '--repeat',
1446)     metavar='NUMBER',
1447)     callback=_validate_occurrence_constraint,
1448)     help='allows maximum of NUMBER repeated adjacent chars',
1449)     cls=PasswordGenerationOption,
1450) )
1451) @click.option(
1452)     '--lower',
1453)     metavar='NUMBER',
1454)     callback=_validate_occurrence_constraint,
1455)     help='includes at least NUMBER lowercase letters',
1456)     cls=PasswordGenerationOption,
1457) )
1458) @click.option(
1459)     '--upper',
1460)     metavar='NUMBER',
1461)     callback=_validate_occurrence_constraint,
1462)     help='includes at least NUMBER uppercase letters',
1463)     cls=PasswordGenerationOption,
1464) )
1465) @click.option(
1466)     '--number',
1467)     metavar='NUMBER',
1468)     callback=_validate_occurrence_constraint,
1469)     help='includes at least NUMBER digits',
1470)     cls=PasswordGenerationOption,
1471) )
1472) @click.option(
1473)     '--space',
1474)     metavar='NUMBER',
1475)     callback=_validate_occurrence_constraint,
1476)     help='includes at least NUMBER spaces',
1477)     cls=PasswordGenerationOption,
1478) )
1479) @click.option(
1480)     '--dash',
1481)     metavar='NUMBER',
1482)     callback=_validate_occurrence_constraint,
1483)     help='includes at least NUMBER "-" or "_"',
1484)     cls=PasswordGenerationOption,
1485) )
1486) @click.option(
1487)     '--symbol',
1488)     metavar='NUMBER',
1489)     callback=_validate_occurrence_constraint,
1490)     help='includes at least NUMBER symbol chars',
1491)     cls=PasswordGenerationOption,
1492) )
1493) @click.option(
1494)     '-n',
1495)     '--notes',
1496)     'edit_notes',
1497)     is_flag=True,
1498)     help='spawn an editor to edit notes for SERVICE',
1499)     cls=ConfigurationOption,
1500) )
1501) @click.option(
1502)     '-c',
1503)     '--config',
1504)     'store_config_only',
1505)     is_flag=True,
1506)     help='saves the given settings for SERVICE or global',
1507)     cls=ConfigurationOption,
1508) )
1509) @click.option(
1510)     '-x',
1511)     '--delete',
1512)     'delete_service_settings',
1513)     is_flag=True,
1514)     help='deletes settings for SERVICE',
1515)     cls=ConfigurationOption,
1516) )
1517) @click.option(
1518)     '--delete-globals',
1519)     is_flag=True,
1520)     help='deletes the global shared settings',
1521)     cls=ConfigurationOption,
1522) )
1523) @click.option(
1524)     '-X',
1525)     '--clear',
1526)     'clear_all_settings',
1527)     is_flag=True,
1528)     help='deletes all settings',
1529)     cls=ConfigurationOption,
1530) )
1531) @click.option(
1532)     '-e',
1533)     '--export',
1534)     'export_settings',
1535)     metavar='PATH',
1536)     help='export all saved settings into file PATH',
1537)     cls=StorageManagementOption,
1538) )
1539) @click.option(
1540)     '-i',
1541)     '--import',
1542)     'import_settings',
1543)     metavar='PATH',
1544)     help='import saved settings from file PATH',
1545)     cls=StorageManagementOption,
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 weeks ago

1547) @click.option(
1548)     '--overwrite-existing/--merge-existing',
1549)     'overwrite_config',
1550)     default=False,
1551)     help='overwrite or merge (default) the existing configuration',
1552)     cls=CompatibilityOption,
1553) )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 5 months ago

1559)     ctx: click.Context,
1560)     /,
1561)     *,
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1562)     service: str | None = None,
1563)     use_phrase: bool = False,
1564)     use_key: bool = False,
1565)     length: int | None = None,
1566)     repeat: int | None = None,
1567)     lower: int | None = None,
1568)     upper: int | None = None,
1569)     number: int | None = None,
1570)     space: int | None = None,
1571)     dash: int | None = None,
1572)     symbol: int | None = None,
1573)     edit_notes: bool = False,
1574)     store_config_only: bool = False,
1575)     delete_service_settings: bool = False,
1576)     delete_globals: bool = False,
1577)     clear_all_settings: bool = False,
1578)     export_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
1579)     import_settings: TextIO | pathlib.Path | os.PathLike[str] | None = None,
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1584)     Using a master passphrase or a master SSH key, derive a passphrase
1585)     for SERVICE, subject to length, character and character repetition
1586)     constraints.  The derivation is cryptographically strong, meaning
1587)     that even if a single passphrase is compromised, guessing the master
1588)     passphrase or a different service's passphrase is computationally
1589)     infeasible.  The derivation is also deterministic, given the same
1590)     inputs, thus the resulting passphrase need not be stored explicitly.
1591)     The service name and constraints themselves also need not be kept
1592)     secret; the latter are usually stored in a world-readable file.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

1604) 
1605)     Parameters:
1606)         ctx (click.Context):
1607)             The `click` context.
1608) 
1609)     Other Parameters:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1662)         export_settings:
1663)             Command-line argument `-e`/`--export`.  If a file object,
1664)             then it must be open for writing and accept `str` inputs.
1665)             Otherwise, a filename to open for writing.  Using `-` for
1666)             standard output is supported.
1667)         import_settings:
1668)             Command-line argument `-i`/`--import`.  If a file object, it
1669)             must be open for reading and yield `str` values.  Otherwise,
1670)             a filename to open for reading.  Using `-` for standard
1671)             input is supported.
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1672)         overwrite_config:
1673)             Command-line arguments `--overwrite-existing` (True) and
1674)             `--merge-existing` (False).  Controls whether config saving
1675)             and config importing overwrite existing configurations, or
1676)             merge them section-wise instead.
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

1686)             # Use match/case here once Python 3.9 becomes unsupported.
1687)             if isinstance(param, PasswordGenerationOption):
1688)                 group = PasswordGenerationOption
1689)             elif isinstance(param, ConfigurationOption):
1690)                 group = ConfigurationOption
1691)             elif isinstance(param, StorageManagementOption):
1692)                 group = StorageManagementOption
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 weeks ago

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

Marco Ricci authored 3 months ago

1697)             elif isinstance(param, OptionGroupOption):
1698)                 raise AssertionError(  # noqa: DOC501,TRY003,TRY004
1699)                     f'Unknown option group for {param!r}'  # noqa: EM102
1700)                 )
1701)             else:
1702)                 group = click.Option
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

1703)             options_in_group.setdefault(group, []).append(param)
1704)         params_by_str[param.human_readable_name] = param
1705)         for name in param.opts + param.secondary_opts:
1706)             params_by_str[name] = param
1707) 
Marco Ricci Fix typing issues in mypy s...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1711)     def check_incompatible_options(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

1715)         if isinstance(param, str):
1716)             param = params_by_str[param]
1717)         assert isinstance(param, click.Parameter)
1718)         if not is_param_set(param):
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

1719)             return
1720)         for other in incompatible:
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1723)             assert isinstance(other, click.Parameter)
1724)             if other != param and is_param_set(other):
1725)                 opt_str = param.opts[0]
1726)                 other_str = other.opts[0]
1727)                 raise click.BadOptionUsage(
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

1735)         ctx.exit(1)
1736) 
Marco Ricci Fix user interface errors i...

Marco Ricci authored 3 weeks ago

1737)     def key_to_phrase(key_: str | bytes | bytearray, /) -> bytes | bytearray:
1738)         key = base64.standard_b64decode(key_)
1739)         try:
1740)             with ssh_agent.SSHAgentClient.ensure_agent_subcontext() as client:
1741)                 try:
1742)                     return vault.Vault.phrase_from_key(key, conn=client)
1743)                 except ssh_agent.SSHAgentFailedError as e:
1744)                     try:
1745)                         keylist = client.list_keys()
1746)                     except ssh_agent.SSHAgentFailedError:
1747)                         pass
1748)                     except Exception as e2:  # noqa: BLE001
1749)                         e.__context__ = e2
1750)                     else:
1751)                         if not any(k == key for k, _ in keylist):
1752)                             err(
1753)                                 'The requested SSH key is not loaded '
1754)                                 'into the agent.'
1755)                             )
1756)                     err(e)
1757)         except KeyError:
1758)             err('Cannot find running SSH agent; check SSH_AUTH_SOCK')
1759)         except NotImplementedError:
1760)             err(
1761)                 'Cannot connect to SSH agent because '
1762)                 'this Python version does not support UNIX domain sockets'
1763)             )
1764)         except OSError as e:
1765)             err('Cannot connect to SSH agent: %s', e.strerror)
1766) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1768)         try:
1769)             return _load_config()
1770)         except FileNotFoundError:
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1771)             try:
1772)                 backup_config, exc = _migrate_and_load_old_config()
1773)             except FileNotFoundError:
1774)                 return {'services': {}}
Marco Ricci Make obtaining the compatib...

Marco Ricci authored 3 weeks ago

1775)             old_name = os.path.basename(
1776)                 _config_filename(subsystem='old settings.json')
1777)             )
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

1786)                 old_name,
1787)                 new_name,
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

1790)                 logger.warning(
1791)                     'Failed to migrate to %r: %s: %r',
1792)                     new_name,
1793)                     exc.strerror,
1794)                     exc.filename,
Marco Ricci Rename the configuration fi...

Marco Ricci authored 3 months ago

1795)                 )
1796)             else:
Marco Ricci Fix usage of `--debug`, `--...

Marco Ricci authored 3 weeks ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

1803) 
1804)     def put_config(config: _types.VaultConfig, /) -> None:
1805)         try:
1806)             _save_config(config)
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 weeks ago

1812)     def get_user_config() -> dict[str, Any]:
1813)         try:
1814)             return _load_user_config()
1815)         except FileNotFoundError:
1816)             return {}
1817)         except OSError as e:
1818)             err('Cannot load user config: %s: %r', e.strerror, e.filename)
1819)         except Exception as e:  # noqa: BLE001
1820)             err('Cannot load user config: %s', str(e), exc_info=e)
1821) 
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

1823) 
1824)     check_incompatible_options('--phrase', '--key')
Marco Ricci Add prototype command-line...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1829)                     opt, *options_in_group[PasswordGenerationOption]
1830)                 )
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1835)                 opt,
1836)                 *options_in_group[ConfigurationOption],
1837)                 *options_in_group[StorageManagementOption],
1838)             )
Marco Ricci Correctly model vault globa...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 2 months ago

1846)             raise click.UsageError(msg)  # noqa: DOC501
1847)     sv_options = [params_by_str['--notes'], params_by_str['--delete']]
1848)     for param in sv_options:
1849)         if is_param_set(param) and not service:
1850)             opt_str = param.opts[0]
1851)             msg = f'{opt_str} requires a SERVICE'
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

1853)     no_sv_options = [
1854)         params_by_str['--delete-globals'],
1855)         params_by_str['--clear'],
1856)         *options_in_group[StorageManagementOption],
1857)     ]
Marco Ricci Fortify the argument parsin...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 weeks ago

1864)     user_config = get_user_config()
1865) 
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 2 months ago

1872)         )
1873) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1874)     if edit_notes:
1875)         assert service is not None
1876)         configuration = get_config()
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1883)             while notes_lines:
1884)                 line = notes_lines.popleft()
1885)                 if line.startswith(DEFAULT_NOTES_MARKER):
1886)                     notes_value = ''.join(notes_lines)
1887)                     break
1888)             else:
1889)                 if not notes_value.strip():
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

1892)                 notes_value.strip('\n')
1893)             )
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1895)     elif delete_service_settings:
1896)         assert service is not None
1897)         configuration = get_config()
1898)         if service in configuration['services']:
1899)             del configuration['services'][service]
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1901)     elif delete_globals:
1902)         configuration = get_config()
1903)         if 'global' in configuration:
1904)             del configuration['global']
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

1908)     elif import_settings:
1909)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

1912)             infile = (
1913)                 cast(TextIO, import_settings)
1914)                 if hasattr(import_settings, 'close')
1915)                 else click.open_file(os.fspath(import_settings), 'rt')
1916)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1917)             with infile:
1918)                 maybe_config = json.load(infile)
1919)         except json.JSONDecodeError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 3 months ago

1926)         assert cleaned is not None
1927)         for step in cleaned:
1928)             # These are never fatal errors, because the semantics of
1929)             # vault upon encountering these settings are ill-specified,
1930)             # but not ill-defined.
1931)             if step.action == 'replace':
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1932)                 logger.warning(
1933)                     'Replacing invalid value %s for key %s with %s.',
1934)                     json.dumps(step.old_value),
1935)                     _types.json_path(step.path),
1936)                     json.dumps(step.new_value),
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

1937)                 )
1938)             else:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

1939)                 logger.warning(
1940)                     'Removing ineffective setting %s = %s.',
1941)                     _types.json_path(step.path),
1942)                     json.dumps(step.old_value),
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

1945)             logger.warning(
1946)                 (
1947)                     'An empty SERVICE is not supported by vault(1), '
1948)                     'and the empty-string service settings will be '
1949)                     'inaccessible and ineffective.  To ensure that '
1950)                     'vault(1) and %s see the settings, move them '
1951)                     'into the "global" section.'
1952)                 ),
1953)                 PROG_NAME,
Marco Ricci Warn the user upon supplyin...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 3 months ago

1955)         form = cast(
1956)             Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
1957)             maybe_config.get('global', {}).get(
1958)                 'unicode_normalization_form', 'NFC'
1959)             ),
1960)         )
1961)         assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
1962)         _check_for_misleading_passphrase(
1963)             ('global',),
1964)             cast(dict[str, Any], maybe_config.get('global', {})),
1965)             form=form,
1966)         )
1967)         for key, value in maybe_config['services'].items():
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

1971)                 form=form,
1972)             )
Marco Ricci Allow the user to overwrite...

Marco Ricci authored 4 weeks ago

1973)         if overwrite_config:
1974)             put_config(maybe_config)
1975)         else:
1976)             configuration = get_config()
1977)             merged_config: collections.ChainMap[str, Any] = (
1978)                 collections.ChainMap(
1979)                     {
1980)                         'services': collections.ChainMap(
1981)                             maybe_config['services'],
1982)                             configuration['services'],
1983)                         ),
1984)                     },
1985)                     {'global': maybe_config['global']}
1986)                     if 'global' in maybe_config
1987)                     else {},
1988)                     {'global': configuration['global']}
1989)                     if 'global' in configuration
1990)                     else {},
1991)                 )
1992)             )
1993)             new_config: Any = {
1994)                 k: dict(v) if isinstance(v, collections.ChainMap) else v
1995)                 for k, v in sorted(merged_config.items())
1996)             }
1997)             assert _types.is_vault_config(new_config)
1998)             put_config(new_config)
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

1999)     elif export_settings:
2000)         configuration = get_config()
2001)         try:
Marco Ricci Apply new ruff ruleset to c...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2004)             outfile = (
2005)                 cast(TextIO, export_settings)
2006)                 if hasattr(export_settings, 'close')
2007)                 else click.open_file(os.fspath(export_settings), 'wt')
2008)             )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2009)             with outfile:
2010)                 json.dump(configuration, outfile)
2011)         except OSError as e:
Marco Ricci Use the logging system to e...

Marco Ricci authored 1 month ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

2020)         service_keys = {
2021)             'key',
2022)             'phrase',
2023)             'length',
2024)             'repeat',
2025)             'lower',
2026)             'upper',
2027)             'number',
2028)             'space',
2029)             'dash',
2030)             'symbol',
2031)         }
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

2033)             {
2034)                 k: v
2035)                 for k, v in locals().items()
2036)                 if k in service_keys and v is not None
2037)             },
2038)             cast(
2039)                 dict[str, Any],
2040)                 configuration['services'].get(service or '', {}),
2041)             ),
2042)             cast(dict[str, Any], configuration.get('global', {})),
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

2043)         )
2044)         if use_key:
2045)             try:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2046)                 key = base64.standard_b64encode(_select_ssh_key()).decode(
2047)                     'ASCII'
2048)                 )
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 3 months ago

2053)             except NotImplementedError:
2054)                 err(
2055)                     'Cannot connect to SSH agent because '
2056)                     'this Python version does not support UNIX domain sockets'
2057)                 )
Marco Ricci Document and handle other e...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 1 month ago

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

Marco Ricci authored 4 months ago

2060)             except (
2061)                 LookupError,
2062)                 RuntimeError,
2063)                 ssh_agent.SSHAgentFailedError,
2064)             ) as e:
Marco Ricci Use better error message ha...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2066)         elif use_phrase:
2067)             maybe_phrase = _prompt_for_passphrase()
2068)             if not maybe_phrase:
Marco Ricci Fix error message capitaliz...

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2070)             else:
2071)                 phrase = maybe_phrase
2072)         if store_config_only:
2073)             view: collections.ChainMap[str, Any]
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

2074)             view = (
2075)                 collections.ChainMap(*settings.maps[:2])
2076)                 if service
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

2079)             if use_key:
2080)                 view['key'] = key
2081)             elif use_phrase:
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 4 months ago

2084)                 _check_for_misleading_passphrase(
2085)                     ('services', service) if service else ('global',),
2086)                     {'phrase': phrase},
2087)                 )
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 1 month ago

2089)                     logger.warning(
2090)                         (
2091)                             'Setting a %s passphrase is ineffective '
2092)                             'because a key is also set.'
2093)                         ),
2094)                         settings_type,
Marco Ricci Fix missing consideration o...

Marco Ricci authored 2 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2100)                     f'actual settings'
2101)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 weeks ago

2103)             subtree: dict[str, Any] = (
2104)                 configuration['services'].setdefault(service, {})  # type: ignore[assignment]
2105)                 if service
2106)                 else configuration.setdefault('global', {})
2107)             )
2108)             if overwrite_config:
2109)                 subtree.clear()
2110)             subtree.update(view)
Marco Ricci Consolidate `types` submodu...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 6 months ago

2115)         else:
2116)             if not service:
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

2119)             kwargs: dict[str, Any] = {
2120)                 k: v
2121)                 for k, v in settings.items()
2122)                 if k in service_keys and v is not None
2123)             }
2124) 
Marco Ricci Allow all textual strings,...

Marco Ricci authored 4 months ago

2125)             if use_phrase:
2126)                 form = cast(
2127)                     Literal['NFC', 'NFD', 'NFKC', 'NFKD'],
2128)                     configuration.get('global', {}).get(
2129)                         'unicode_normalization_form', 'NFC'
2130)                     ),
2131)                 )
2132)                 assert form in {'NFC', 'NFD', 'NFKC', 'NFKD'}
2133)                 _check_for_misleading_passphrase(
Marco Ricci Signal and list falsy value...

Marco Ricci authored 3 months ago

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

Marco Ricci authored 4 months ago

2135)                 )
2136) 
Marco Ricci Add finished command-line i...

Marco Ricci authored 6 months ago

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

Marco Ricci authored 3 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

2147)             elif kwargs.get('phrase'):
2148)                 pass
2149)             else:
Marco Ricci Reformat everything with ruff

Marco Ricci authored 5 months ago

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

Marco Ricci authored 4 months ago

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

Marco Ricci authored 5 months ago

2152)                     'or in configuration'
2153)                 )
Marco Ricci Fix style issues with ruff...

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 5 months ago

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

Marco Ricci authored 6 months ago

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