Add token_command support for Gmail targets
cover Add token_command support for Gmail targets
This series adds support for obtaining Gmail OAuth2 bearer tokens from an external command via a new token_command setting on Gmail targets (similar to passwordeval in msmtp or PassCmd in mbsync). This lets korgalore share an encrypted credential store or OAuth2 token helper (such as oama, git-credential helpers, or custom keyring/GPG scripts) with other mail tools without managing separate Google OAuth client secrets, running another browser login flow, or keeping an unencrypted token JSON file on disk.
Patch 1 extracts file-based OAuth credential management out of GmailTarget into a dedicated google_creds module so GmailTarget accepts any google.auth Credentials provider. Patch 2 adds the command-backed credential provider, wires up token_command, verifies Gmail access during kgl auth, and documents the new option.
---
Dmitry Torokhov (2):
Decouple GmailTarget from OAuth file credential management Add token_command support for Gmail targets
docs/configuration.rst | 10 +- korgalore-example.toml | 2 + man/korgalore.toml.5 | 12 +- src/korgalore/cli.py | 35 +++-- src/korgalore/gmail_target.py | 225 ++++++++++++++-------------- src/korgalore/google_creds.py | 336 ++++++++++++++++++++++++++++++++++++++++++ tests/test_cli_misc.py | 103 ++++++++++++- tests/test_gmail_target.py | 254 +++++++++++++++++-------------- tests/test_google_creds.py | 262 ++++++++++++++++++++++++++++++++ 9 files changed, 997 insertions(+), 242 deletions(-)
---
base-commit: ea22e7c8701e566328f197c748718cd689f9ea28
change-id: 20261104-token-command-2e22bf5ba436
Thanks.
Signature · 1 line
Dmitry
PATCH 1/2 Decouple GmailTarget from OAuth file credential management
Move OAuth client secrets and token file management out of GmailTarget into OAuthFileCredentials in google_creds, subclassing google.auth.credentials.Credentials, and pass credentials directly into GmailTarget via make_gmail_credentials.
This keeps Google OAuth credential transport separate from Gmail API delivery and configuration parsing, and prepares for supporting alternative credential providers.
--- src/korgalore/cli.py | 23 ++--- src/korgalore/gmail_target.py | 212 ++++++++++++++++++-------------------- src/korgalore/google_creds.py | 229 ++++++++++++++++++++++++++++++++++++++++++ tests/test_gmail_target.py | 229 +++++++++++++++++++++--------------------- tests/test_google_creds.py | 154 ++++++++++++++++++++++++++++ 5 files changed, 610 insertions(+), 237 deletions(-)
src/korgalore/cli.py +11 -12
@@ -54,7 +54,7 @@ from korgalore.digest import ( strip_reply_prefixes, ) from korgalore.dummy_target import DummyTarget -from korgalore.gmail_target import GmailTarget +from korgalore.gmail_target import GmailTarget, make_gmail_credentials from korgalore.imap_target import ImapTarget from korgalore.jmap_target import JmapTarget from korgalore.lei_feed import LeiFeed
@@ -280,8 +280,7 @@ def get_target(ctx: click.Context, identifier: str) -> Any: if target_type == 'gmail': service = get_gmail_target( identifier=identifier, - credentials_file=details.get('credentials', ''), - token_file=details.get('token', None), + details=details, interactive=interactive, ) elif target_type == 'maildir':
@@ -334,19 +333,19 @@ def get_target(ctx: click.Context, identifier: str) -> Any: def get_gmail_target( - identifier: str, credentials_file: str, token_file: str | None, interactive: bool = True + identifier: str, + details: Mapping[str, Any], + interactive: bool = True, ) -> GmailTarget: """Create a Gmail target service instance.""" - if not credentials_file: - logger.critical('No credentials file specified for Gmail target: %s', identifier) - raise click.Abort() - if not token_file: - cfgdir = get_xdg_config_dir() - token_file = str(cfgdir / f'gmail-{identifier}-token.json') try: - gt = GmailTarget( - identifier=identifier, credentials_file=credentials_file, token_file=token_file, interactive=interactive + creds = make_gmail_credentials( + identifier=identifier, + details=details, + interactive=interactive, + config_dir=get_xdg_config_dir(), ) + gt = GmailTarget(identifier=identifier, creds=creds) except ConfigurationError as fe: logger.critical('Error: %s', str(fe)) raise click.Abort() from fe
src/korgalore/gmail_target.py +100 -112
276 lines not on this page · raw message
src/korgalore/google_creds.py new file +229 -0
229 lines not on this page · raw message
tests/test_gmail_target.py +116 -113
296 lines not on this page · raw message
tests/test_google_creds.py new file +154 -0
154 lines not on this page · raw message
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
PATCH 2/2 Add token_command support for Gmail targets
In reply to Dmitry TorokhovAdd support for obtaining Gmail OAuth access tokens from an external command via the token_command configuration setting on Gmail targets.
This enables integrating with system token managers, secret stores, or command-line helpers without needing Google OAuth client secrets or running interactive OAuth login flows in a browser.
--- docs/configuration.rst | 10 +++- korgalore-example.toml | 2 + man/korgalore.toml.5 | 12 ++++- src/korgalore/cli.py | 12 ++++- src/korgalore/gmail_target.py | 27 +++++++--- src/korgalore/google_creds.py | 111 +++++++++++++++++++++++++++++++++++++++- tests/test_cli_misc.py | 103 +++++++++++++++++++++++++++++++++++++- tests/test_gmail_target.py | 35 +++++++++++-- tests/test_google_creds.py | 114 ++++++++++++++++++++++++++++++++++++++++-- 9 files changed, 404 insertions(+), 22 deletions(-)
docs/configuration.rst +9 -1
@@ -410,9 +410,17 @@ Gmail Target Parameters ~~~~~~~~~~~~~~~~~~~~~~~~ * ``type``: Must be ``'gmail'`` -* ``credentials``: Path to the OAuth credentials JSON file +* ``credentials``: Path to the OAuth credentials JSON file (required unless + ``token_command`` is specified) * ``token``: (Optional) Path to store the OAuth token. Defaults to ``~/.config/korgalore/gmail-{identifier}-token.json`` +* ``token_command``: (Optional) External command that prints a valid OAuth2 + bearer token to stdout. Mutually exclusive with both ``credentials`` and + ``token``. The command string is split using standard command-line syntax + and executed directly without a shell, with tilde and environment variable + expansion. The bearer token returned by the command must carry the OAuth + scopes required by korgalore (``https://www.googleapis.com/auth/gmail.labels`` + and ``https://www.googleapis.com/auth/gmail.insert``). Maildir Target Parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~
korgalore-example.toml +2 -0
@@ -3,6 +3,8 @@ [targets.personal] type = 'gmail' credentials = '/path/to/personal-credentials.json' +# Alternatively, obtain tokens from an external command: +# token_command = 'oama access personal' [targets.work] type = 'gmail'
man/korgalore.toml.5 +11 -1
@@ -30,11 +30,21 @@ name and a type that determines which parameters are required. Must be \fI'gmail'\fR. .TP .B credentials -Path to the OAuth credentials JSON file from Google Cloud Console. +Path to the OAuth credentials JSON file from Google Cloud Console (required +unless \fBtoken_command\fR is specified). .TP .B token (Optional) Path to store the OAuth token. Defaults to \fI~/.config/korgalore/gmail-<name>-token.json\fR. +.TP +.B token_command +(Optional) External command to execute that prints an OAuth2 bearer token to +stdout. Mutually exclusive with both \fBcredentials\fR and \fBtoken\fR. +The command is split into arguments using standard command-line syntax and +executed directly without a shell, with tilde and environment variable +expansion. The bearer token must carry the OAuth scopes required by +korgalore (\fIhttps://www.googleapis.com/auth/gmail.labels\fR and +\fIhttps://www.googleapis.com/auth/gmail.insert\fR). .RE .PP .B Maildir Targets
src/korgalore/cli.py +10 -2
@@ -1948,6 +1948,9 @@ def auth(ctx: click.Context, target: str | None) -> None: ts = get_target(ctx, identifier) ts.connect() logger.info('Authenticated target: %s (type: %s)', identifier, target_type) + except (ConfigurationError, AuthenticationError, RemoteError) as e: + logger.error('Failed to authenticate target %s: %s', identifier, e) + raise click.Abort() from e except click.Abort: logger.error('Failed to authenticate target: %s', identifier) raise
@@ -2483,7 +2486,12 @@ def yank(ctx: click.Context, target: str | None, labels: tuple[str, ...], thread uploaded = 0 failed = 0 - ts.connect() + try: + ts.connect() + except (ConfigurationError, AuthenticationError, liblore.RemoteError) as e: + logger.critical('Failed to connect to target "%s": %s', target, e) + raise click.Abort() from e + with click.progressbar( messages, label='Uploading thread', show_pos=True, file=progress_file(ctx.obj['hide_bar']) ) as bar:
@@ -2524,7 +2532,7 @@ def yank(ctx: click.Context, target: str | None, labels: tuple[str, ...], thread ts.connect() ts.import_message(raw_message, labels=labels_list) logger.info('Successfully uploaded message.') - except liblore.RemoteError as e: + except (ConfigurationError, AuthenticationError, liblore.RemoteError) as e: logger.critical('Failed to upload message: %s', str(e)) raise click.Abort() from e
src/korgalore/gmail_target.py +21 -6
@@ -11,7 +11,7 @@ from googleapiclient.discovery import Resource, build # type: ignore[import-unt from googleapiclient.errors import HttpError # type: ignore[import-untyped] from korgalore import AuthenticationError, ConfigurationError, RemoteError -from korgalore.google_creds import OAuthFileCredentials +from korgalore.google_creds import CommandCredentials, OAuthFileCredentials, parse_token_command from korgalore.message import RawMessage logger = logging.getLogger('korgalore')
@@ -53,8 +53,11 @@ class GmailTarget: Creates the Gmail API service object if not already connected. Raises: - ConfigurationError: If credentials file is not found during refresh. + ConfigurationError: If credentials file is missing or token_command + cannot be executed. AuthenticationError: If OAuth token refresh or authentication fails. + RemoteError: If token_command fails, times out, or returns an + invalid token. """ if self.service is not None: return
@@ -201,11 +204,23 @@ def make_gmail_credentials( Configured credentials instance compatible with ``GmailTarget``. Raises: - ConfigurationError: If required configuration keys are missing or have - invalid types. + ConfigurationError: If required configuration keys are missing, + mutually exclusive, or invalid. """ - if 'credentials' not in details: - raise ConfigurationError(f"No credentials file specified for Gmail target '{identifier}'.") + has_creds = 'credentials' in details + has_token = 'token' in details + has_cmd = 'token_command' in details + + if has_cmd: + if has_creds or has_token: + raise ConfigurationError( + f"Gmail target '{identifier}' cannot specify both 'token_command' and 'credentials'/'token'." + ) + command = parse_token_command(details['token_command'], f"Gmail target '{identifier}'") + return CommandCredentials(identifier=identifier, command=command) + + if not has_creds: + raise ConfigurationError(f"Gmail target '{identifier}' must specify either 'credentials' or 'token_command'.") creds_raw = details['credentials'] if not isinstance(creds_raw, str):
src/korgalore/google_creds.py +109 -2
126 lines not on this page · raw message
tests/test_cli_misc.py +101 -2
116 lines not on this page · raw message
tests/test_gmail_target.py +30 -5
@@ -10,7 +10,7 @@ from googleapiclient.errors import HttpError # type: ignore[import-untyped] from korgalore import AuthenticationError, ConfigurationError, RemoteError from korgalore.gmail_target import SCOPES, GmailTarget, make_gmail_credentials -from korgalore.google_creds import OAuthFileCredentials +from korgalore.google_creds import CommandCredentials, OAuthFileCredentials def make_target() -> tuple[GmailTarget, MagicMock]:
@@ -300,18 +300,43 @@ class TestGmailTargetImportMessage: class TestMakeGmailCredentials: """Tests for make_gmail_credentials configuration factory.""" - def test_no_credentials_raises(self) -> None: - """Omitting credentials raises ConfigurationError.""" - with pytest.raises(ConfigurationError, match='No credentials file specified'): + def test_no_credentials_or_token_command_raises(self) -> None: + """Must specify either credentials or token_command.""" + with pytest.raises(ConfigurationError, match='must specify either'): make_gmail_credentials('test', {}) + @pytest.mark.parametrize( + 'details', + [ + {'credentials': '/tmp/creds.json', 'token_command': 'echo token'}, + {'token': '/tmp/token.json', 'token_command': 'echo token'}, + ], + ids=['credentials-and-command', 'token-and-command'], + ) + def test_mutually_exclusive_token_command_options_raise(self, details: dict[str, object]) -> None: + """Specifying token_command alongside credentials or token raises ConfigurationError.""" + with pytest.raises(ConfigurationError, match='cannot specify both'): + make_gmail_credentials('test', details) + + def test_token_command_invalid_syntax_raises(self) -> None: + """Unclosed quotes in token_command raise ConfigurationError.""" + with pytest.raises(ConfigurationError, match='syntax'): + make_gmail_credentials('test', {'token_command': 'unclosed "quote'}) + + def test_token_command_returns_command_credentials(self) -> None: + """Valid token_command builds CommandCredentials without running interactive OAuth.""" + creds = make_gmail_credentials('test', {'token_command': 'get-token --profile work'}) + assert isinstance(creds, CommandCredentials) + assert creds.command == ['get-token', '--profile', 'work'] + @pytest.mark.parametrize( ('details', 'expected_match'), [ ({'credentials': 123}, "'credentials' must be a string"), ({'credentials': '/tmp/creds.json', 'token': 456}, "'token' must be a string"), + ({'token_command': 789}, "'token_command' must be a string"), ], - ids=['non-str-credentials', 'non-str-token'], + ids=['non-str-credentials', 'non-str-token', 'non-str-token-command'], ) def test_invalid_option_types_raise(self, details: dict[str, object], expected_match: str) -> None: """Non-string configuration values raise ConfigurationError."""
tests/test_google_creds.py +111 -3
127 lines not on this page · raw message
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
Konstantin Ryabitsev
AppliedQuoted 11 lines · Dmitry Torokhov
Add
token_commandsupport for Gmail targetsThis series adds support for obtaining Gmail OAuth2 bearer tokens from an external command via a new
token_commandsetting on Gmail targets (similar to passwordeval in msmtp or PassCmd in mbsync). This lets korgalore share an encrypted credential store or OAuth2 token helper (such as oama, git-credential helpers, or custom keyring/GPG scripts) with other mail tools without managing separate Google OAuth client secrets, running another browser login flow, or keeping an unencrypted token JSON file on disk.
Quoted 1 line
[...]
Applied, thanks!
[1/2] Decouple GmailTarget from OAuth file credential management
https://git.kernel.org/pub/scm/utils/korgalore/korgalore.git/commit/?id=1d5b42b214461500a8f3e00a9bac7fa8e0c04237 [2/2] Add token_command support for Gmail targets https://git.kernel.org/pub/scm/utils/korgalore/korgalore.git/commit/?id=c7bb04ec81b8b172b388345ceb48270dd2962c38
Best regards,
Signature · 1 line
Konstantin Ryabitsev <[email protected]>